blob: 6b597d117df47b75fc06efb3c5e63045de32c9ff [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
David Chisnall44663db2009-08-17 16:35:33 +000029
Douglas Gregoraa57e862009-02-18 21:56:37 +000030/// \brief Determine whether the use of this declaration is valid, and
31/// emit any corresponding diagnostics.
32///
33/// This routine diagnoses various problems with referencing
34/// declarations that can occur when using a declaration. For example,
35/// it might warn if a deprecated or unavailable declaration is being
36/// used, or produce an error (and return true) if a C++0x deleted
37/// function is being used.
38///
39/// \returns true if there was an error (this declaration cannot be
40/// referenced), false otherwise.
41bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000042 // See if the decl is deprecated.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000043 if (D->getAttr<DeprecatedAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000044 // Implementing deprecated stuff requires referencing deprecated
45 // stuff. Don't warn if we are implementing a deprecated
46 // construct.
Chris Lattnerfb1bb822009-02-16 19:35:30 +000047 bool isSilenced = false;
48
49 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
50 // If this reference happens *in* a deprecated function or method, don't
51 // warn.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000052 isSilenced = ND->getAttr<DeprecatedAttr>();
Chris Lattnerfb1bb822009-02-16 19:35:30 +000053
54 // If this is an Objective-C method implementation, check to see if the
55 // method was deprecated on the declaration, not the definition.
56 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
57 // The semantic decl context of a ObjCMethodDecl is the
58 // ObjCImplementationDecl.
59 if (ObjCImplementationDecl *Impl
60 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
61
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +000062 MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
Chris Lattnerfb1bb822009-02-16 19:35:30 +000063 MD->isInstanceMethod());
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000064 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
Chris Lattnerfb1bb822009-02-16 19:35:30 +000065 }
66 }
67 }
68
69 if (!isSilenced)
Chris Lattner2cb744b2009-02-15 22:43:40 +000070 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
71 }
72
Douglas Gregoraa57e862009-02-18 21:56:37 +000073 // See if this is a deleted function.
Douglas Gregor6f8c3682009-02-24 04:26:15 +000074 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000075 if (FD->isDeleted()) {
76 Diag(Loc, diag::err_deleted_function_use);
77 Diag(D->getLocation(), diag::note_unavailable_here) << true;
78 return true;
79 }
Douglas Gregor6f8c3682009-02-24 04:26:15 +000080 }
Douglas Gregoraa57e862009-02-18 21:56:37 +000081
82 // See if the decl is unavailable
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000083 if (D->getAttr<UnavailableAttr>()) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000084 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
Douglas Gregoraa57e862009-02-18 21:56:37 +000085 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
86 }
87
Douglas Gregoraa57e862009-02-18 21:56:37 +000088 return false;
Chris Lattner2cb744b2009-02-15 22:43:40 +000089}
90
Fariborz Jahanian180f3412009-05-13 18:09:35 +000091/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
92/// (and other functions in future), which have been declared with sentinel
93/// attribute. It warns if call does not have the sentinel argument.
94///
95void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
96 Expr **Args, unsigned NumArgs)
97{
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000098 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Fariborz Jahanian79d29e72009-05-13 23:20:50 +000099 if (!attr)
100 return;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000101 int sentinelPos = attr->getSentinel();
102 int nullPos = attr->getNullPos();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000103
Mike Stumpe127ae32009-05-16 07:39:55 +0000104 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
105 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000106 unsigned int i = 0;
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000107 bool warnNotEnoughArgs = false;
108 int isMethod = 0;
109 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
110 // skip over named parameters.
111 ObjCMethodDecl::param_iterator P, E = MD->param_end();
112 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
113 if (nullPos)
114 --nullPos;
115 else
116 ++i;
117 }
118 warnNotEnoughArgs = (P != E || i >= NumArgs);
119 isMethod = 1;
Mike Stump90fc78e2009-08-04 21:02:39 +0000120 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000121 // skip over named parameters.
122 ObjCMethodDecl::param_iterator P, E = FD->param_end();
123 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
124 if (nullPos)
125 --nullPos;
126 else
127 ++i;
128 }
129 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump90fc78e2009-08-04 21:02:39 +0000130 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000131 // block or function pointer call.
132 QualType Ty = V->getType();
133 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
134 const FunctionType *FT = Ty->isFunctionPointerType()
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000135 ? Ty->getAs<PointerType>()->getPointeeType()->getAsFunctionType()
136 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAsFunctionType();
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000137 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
138 unsigned NumArgsInProto = Proto->getNumArgs();
139 unsigned k;
140 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
141 if (nullPos)
142 --nullPos;
143 else
144 ++i;
145 }
146 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
147 }
148 if (Ty->isBlockPointerType())
149 isMethod = 2;
Mike Stump90fc78e2009-08-04 21:02:39 +0000150 } else
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000151 return;
Mike Stump90fc78e2009-08-04 21:02:39 +0000152 } else
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000153 return;
154
155 if (warnNotEnoughArgs) {
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000156 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000157 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000158 return;
159 }
160 int sentinel = i;
161 while (sentinelPos > 0 && i < NumArgs-1) {
162 --sentinelPos;
163 ++i;
164 }
165 if (sentinelPos > 0) {
166 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000167 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000168 return;
169 }
170 while (i < NumArgs-1) {
171 ++i;
172 ++sentinel;
173 }
174 Expr *sentinelExpr = Args[sentinel];
175 if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() ||
176 !sentinelExpr->isNullPointerConstant(Context))) {
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000177 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000178 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000179 }
180 return;
Fariborz Jahanian180f3412009-05-13 18:09:35 +0000181}
182
Douglas Gregor3bb30002009-02-26 21:00:50 +0000183SourceRange Sema::getExprRange(ExprTy *E) const {
184 Expr *Ex = (Expr *)E;
185 return Ex? Ex->getSourceRange() : SourceRange();
186}
187
Chris Lattner299b8842008-07-25 21:10:04 +0000188//===----------------------------------------------------------------------===//
189// Standard Promotions and Conversions
190//===----------------------------------------------------------------------===//
191
Chris Lattner299b8842008-07-25 21:10:04 +0000192/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
193void Sema::DefaultFunctionArrayConversion(Expr *&E) {
194 QualType Ty = E->getType();
195 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
196
Chris Lattner299b8842008-07-25 21:10:04 +0000197 if (Ty->isFunctionType())
198 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +0000199 else if (Ty->isArrayType()) {
200 // In C90 mode, arrays only promote to pointers if the array expression is
201 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
202 // type 'array of type' is converted to an expression that has type 'pointer
203 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
204 // that has type 'array of type' ...". The relevant change is "an lvalue"
205 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +0000206 //
207 // C++ 4.2p1:
208 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
209 // T" can be converted to an rvalue of type "pointer to T".
210 //
211 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
212 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson5c09af02009-08-07 23:48:20 +0000213 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
214 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner2aa68822008-07-25 21:33:13 +0000215 }
Chris Lattner299b8842008-07-25 21:10:04 +0000216}
217
Douglas Gregor70b307e2009-05-01 20:41:21 +0000218/// \brief Whether this is a promotable bitfield reference according
219/// to C99 6.3.1.1p2, bullet 2.
220///
221/// \returns the type this bit-field will promote to, or NULL if no
222/// promotion occurs.
223static QualType isPromotableBitField(Expr *E, ASTContext &Context) {
Douglas Gregor531434b2009-05-02 02:18:30 +0000224 FieldDecl *Field = E->getBitField();
225 if (!Field)
Douglas Gregor70b307e2009-05-01 20:41:21 +0000226 return QualType();
227
228 const BuiltinType *BT = Field->getType()->getAsBuiltinType();
229 if (!BT)
230 return QualType();
231
232 if (BT->getKind() != BuiltinType::Bool &&
233 BT->getKind() != BuiltinType::Int &&
234 BT->getKind() != BuiltinType::UInt)
235 return QualType();
236
237 llvm::APSInt BitWidthAP;
238 if (!Field->getBitWidth()->isIntegerConstantExpr(BitWidthAP, Context))
239 return QualType();
240
241 uint64_t BitWidth = BitWidthAP.getZExtValue();
242 uint64_t IntSize = Context.getTypeSize(Context.IntTy);
243 if (BitWidth < IntSize ||
244 (Field->getType()->isSignedIntegerType() && BitWidth == IntSize))
245 return Context.IntTy;
246
247 if (BitWidth == IntSize && Field->getType()->isUnsignedIntegerType())
248 return Context.UnsignedIntTy;
249
250 return QualType();
251}
252
Chris Lattner299b8842008-07-25 21:10:04 +0000253/// UsualUnaryConversions - Performs various conversions that are common to most
254/// operators (C99 6.3). The conversions of array and function types are
255/// sometimes surpressed. For example, the array->pointer conversion doesn't
256/// apply if the array is an argument to the sizeof or address (&) operators.
257/// In these instances, this routine should *not* be called.
258Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
259 QualType Ty = Expr->getType();
260 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
261
Douglas Gregor70b307e2009-05-01 20:41:21 +0000262 // C99 6.3.1.1p2:
263 //
264 // The following may be used in an expression wherever an int or
265 // unsigned int may be used:
266 // - an object or expression with an integer type whose integer
267 // conversion rank is less than or equal to the rank of int
268 // and unsigned int.
269 // - A bit-field of type _Bool, int, signed int, or unsigned int.
270 //
271 // If an int can represent all values of the original type, the
272 // value is converted to an int; otherwise, it is converted to an
273 // unsigned int. These are called the integer promotions. All
274 // other types are unchanged by the integer promotions.
275 if (Ty->isPromotableIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000276 ImpCastExprToType(Expr, Context.IntTy);
Douglas Gregor70b307e2009-05-01 20:41:21 +0000277 return Expr;
278 } else {
279 QualType T = isPromotableBitField(Expr, Context);
280 if (!T.isNull()) {
281 ImpCastExprToType(Expr, T);
282 return Expr;
283 }
284 }
285
286 DefaultFunctionArrayConversion(Expr);
Chris Lattner299b8842008-07-25 21:10:04 +0000287 return Expr;
288}
289
Chris Lattner9305c3d2008-07-25 22:25:12 +0000290/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
291/// do not have a prototype. Arguments that have type float are promoted to
292/// double. All other argument types are converted by UsualUnaryConversions().
293void Sema::DefaultArgumentPromotion(Expr *&Expr) {
294 QualType Ty = Expr->getType();
295 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
296
297 // If this is a 'float' (CVR qualified or typedef) promote to double.
298 if (const BuiltinType *BT = Ty->getAsBuiltinType())
299 if (BT->getKind() == BuiltinType::Float)
300 return ImpCastExprToType(Expr, Context.DoubleTy);
301
302 UsualUnaryConversions(Expr);
303}
304
Chris Lattner81f00ed2009-04-12 08:11:20 +0000305/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
306/// will warn if the resulting type is not a POD type, and rejects ObjC
307/// interfaces passed by value. This returns true if the argument type is
308/// completely illegal.
309bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000310 DefaultArgumentPromotion(Expr);
311
Chris Lattner81f00ed2009-04-12 08:11:20 +0000312 if (Expr->getType()->isObjCInterfaceType()) {
313 Diag(Expr->getLocStart(),
314 diag::err_cannot_pass_objc_interface_to_vararg)
315 << Expr->getType() << CT;
316 return true;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000317 }
Chris Lattner81f00ed2009-04-12 08:11:20 +0000318
319 if (!Expr->getType()->isPODType())
320 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
321 << Expr->getType() << CT;
322
323 return false;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000324}
325
326
Chris Lattner299b8842008-07-25 21:10:04 +0000327/// UsualArithmeticConversions - Performs various conversions that are common to
328/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
329/// routine returns the first non-arithmetic type found. The client is
330/// responsible for emitting appropriate error diagnostics.
331/// FIXME: verify the conversion rules for "complex int" are consistent with
332/// GCC.
333QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
334 bool isCompAssign) {
Eli Friedman3cd92882009-03-28 01:22:36 +0000335 if (!isCompAssign)
Chris Lattner299b8842008-07-25 21:10:04 +0000336 UsualUnaryConversions(lhsExpr);
Eli Friedman3cd92882009-03-28 01:22:36 +0000337
338 UsualUnaryConversions(rhsExpr);
Douglas Gregor70d26122008-11-12 17:17:38 +0000339
Chris Lattner299b8842008-07-25 21:10:04 +0000340 // For conversion purposes, we ignore any qualifiers.
341 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000342 QualType lhs =
343 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
344 QualType rhs =
345 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000346
347 // If both types are identical, no conversion is needed.
348 if (lhs == rhs)
349 return lhs;
350
351 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
352 // The caller can deal with this (e.g. pointer + int).
353 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
354 return lhs;
355
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000356 // Perform bitfield promotions.
357 QualType LHSBitfieldPromoteTy = isPromotableBitField(lhsExpr, Context);
358 if (!LHSBitfieldPromoteTy.isNull())
359 lhs = LHSBitfieldPromoteTy;
360 QualType RHSBitfieldPromoteTy = isPromotableBitField(rhsExpr, Context);
361 if (!RHSBitfieldPromoteTy.isNull())
362 rhs = RHSBitfieldPromoteTy;
363
Douglas Gregor70d26122008-11-12 17:17:38 +0000364 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman3cd92882009-03-28 01:22:36 +0000365 if (!isCompAssign)
Douglas Gregor70d26122008-11-12 17:17:38 +0000366 ImpCastExprToType(lhsExpr, destType);
Eli Friedman3cd92882009-03-28 01:22:36 +0000367 ImpCastExprToType(rhsExpr, destType);
Douglas Gregor70d26122008-11-12 17:17:38 +0000368 return destType;
369}
370
371QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
372 // Perform the usual unary conversions. We do this early so that
373 // integral promotions to "int" can allow us to exit early, in the
374 // lhs == rhs check. Also, for conversion purposes, we ignore any
375 // qualifiers. For example, "const float" and "float" are
376 // equivalent.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000377 if (lhs->isPromotableIntegerType())
378 lhs = Context.IntTy;
379 else
380 lhs = lhs.getUnqualifiedType();
381 if (rhs->isPromotableIntegerType())
382 rhs = Context.IntTy;
383 else
384 rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000385
Chris Lattner299b8842008-07-25 21:10:04 +0000386 // If both types are identical, no conversion is needed.
387 if (lhs == rhs)
388 return lhs;
389
390 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
391 // The caller can deal with this (e.g. pointer + int).
392 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
393 return lhs;
394
395 // At this point, we have two different arithmetic types.
396
397 // Handle complex types first (C99 6.3.1.8p1).
398 if (lhs->isComplexType() || rhs->isComplexType()) {
399 // if we have an integer operand, the result is the complex type.
400 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
401 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000402 return lhs;
403 }
404 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
405 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000406 return rhs;
407 }
408 // This handles complex/complex, complex/float, or float/complex.
409 // When both operands are complex, the shorter operand is converted to the
410 // type of the longer, and that is the type of the result. This corresponds
411 // to what is done when combining two real floating-point operands.
412 // The fun begins when size promotion occur across type domains.
413 // From H&S 6.3.4: When one operand is complex and the other is a real
414 // floating-point type, the less precise type is converted, within it's
415 // real or complex domain, to the precision of the other type. For example,
416 // when combining a "long double" with a "double _Complex", the
417 // "double _Complex" is promoted to "long double _Complex".
418 int result = Context.getFloatingTypeOrder(lhs, rhs);
419
420 if (result > 0) { // The left side is bigger, convert rhs.
421 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000422 } else if (result < 0) { // The right side is bigger, convert lhs.
423 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000424 }
425 // At this point, lhs and rhs have the same rank/size. Now, make sure the
426 // domains match. This is a requirement for our implementation, C99
427 // does not require this promotion.
428 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
429 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000430 return rhs;
431 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000432 return lhs;
433 }
434 }
435 return lhs; // The domain/size match exactly.
436 }
437 // Now handle "real" floating types (i.e. float, double, long double).
438 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
439 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000440 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000441 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000442 return lhs;
443 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000444 if (rhs->isComplexIntegerType()) {
445 // convert rhs to the complex floating point type.
446 return Context.getComplexType(lhs);
447 }
448 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000449 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000450 return rhs;
451 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000452 if (lhs->isComplexIntegerType()) {
453 // convert lhs to the complex floating point type.
454 return Context.getComplexType(rhs);
455 }
Chris Lattner299b8842008-07-25 21:10:04 +0000456 // We have two real floating types, float/complex combos were handled above.
457 // Convert the smaller operand to the bigger result.
458 int result = Context.getFloatingTypeOrder(lhs, rhs);
Chris Lattner2cb744b2009-02-15 22:43:40 +0000459 if (result > 0) // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000460 return lhs;
Chris Lattner2cb744b2009-02-15 22:43:40 +0000461 assert(result < 0 && "illegal float comparison");
462 return rhs; // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000463 }
464 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
465 // Handle GCC complex int extension.
466 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
467 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
468
469 if (lhsComplexInt && rhsComplexInt) {
470 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
Chris Lattner2cb744b2009-02-15 22:43:40 +0000471 rhsComplexInt->getElementType()) >= 0)
472 return lhs; // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000473 return rhs;
474 } else if (lhsComplexInt && rhs->isIntegerType()) {
475 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000476 return lhs;
477 } else if (rhsComplexInt && lhs->isIntegerType()) {
478 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000479 return rhs;
480 }
481 }
482 // Finally, we have two differing integer types.
483 // The rules for this case are in C99 6.3.1.8
484 int compare = Context.getIntegerTypeOrder(lhs, rhs);
485 bool lhsSigned = lhs->isSignedIntegerType(),
486 rhsSigned = rhs->isSignedIntegerType();
487 QualType destType;
488 if (lhsSigned == rhsSigned) {
489 // Same signedness; use the higher-ranked type
490 destType = compare >= 0 ? lhs : rhs;
491 } else if (compare != (lhsSigned ? 1 : -1)) {
492 // The unsigned type has greater than or equal rank to the
493 // signed type, so use the unsigned type
494 destType = lhsSigned ? rhs : lhs;
495 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
496 // The two types are different widths; if we are here, that
497 // means the signed type is larger than the unsigned type, so
498 // use the signed type.
499 destType = lhsSigned ? lhs : rhs;
500 } else {
501 // The signed type is higher-ranked than the unsigned type,
502 // but isn't actually any bigger (like unsigned int and long
503 // on most 32-bit systems). Use the unsigned type corresponding
504 // to the signed type.
505 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
506 }
Chris Lattner299b8842008-07-25 21:10:04 +0000507 return destType;
508}
509
510//===----------------------------------------------------------------------===//
511// Semantic Analysis for various Expression Types
512//===----------------------------------------------------------------------===//
513
514
Steve Naroff87d58b42007-09-16 03:34:24 +0000515/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000516/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
517/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
518/// multiple tokens. However, the common case is that StringToks points to one
519/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000520///
521Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000522Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000523 assert(NumStringToks && "Must have at least one string!");
524
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000525 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000526 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000527 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000528
529 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
530 for (unsigned i = 0; i != NumStringToks; ++i)
531 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000532
Chris Lattnera6dcce32008-02-11 00:02:17 +0000533 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000534 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000535 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000536
537 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
538 if (getLangOptions().CPlusPlus)
539 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000540
Chris Lattnera6dcce32008-02-11 00:02:17 +0000541 // Get an array type for the string, according to C99 6.4.5. This includes
542 // the nul terminator character as well as the string length for pascal
543 // strings.
544 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattner14032222009-02-26 23:01:51 +0000545 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000546 ArrayType::Normal, 0);
Chris Lattnerc3144742009-02-18 05:49:11 +0000547
Chris Lattner4b009652007-07-25 00:24:17 +0000548 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattneraa491192009-02-18 06:40:38 +0000549 return Owned(StringLiteral::Create(Context, Literal.GetString(),
550 Literal.GetStringLength(),
551 Literal.AnyWide, StrTy,
552 &StringTokLocs[0],
553 StringTokLocs.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000554}
555
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000556/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
557/// CurBlock to VD should cause it to be snapshotted (as we do for auto
558/// variables defined outside the block) or false if this is not needed (e.g.
559/// for values inside the block or for globals).
560///
Chris Lattner0b464252009-04-21 22:26:47 +0000561/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
562/// up-to-date.
563///
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000564static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
565 ValueDecl *VD) {
566 // If the value is defined inside the block, we couldn't snapshot it even if
567 // we wanted to.
568 if (CurBlock->TheDecl == VD->getDeclContext())
569 return false;
570
571 // If this is an enum constant or function, it is constant, don't snapshot.
572 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
573 return false;
574
575 // If this is a reference to an extern, static, or global variable, no need to
576 // snapshot it.
577 // FIXME: What about 'const' variables in C++?
578 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner0b464252009-04-21 22:26:47 +0000579 if (!Var->hasLocalStorage())
580 return false;
581
582 // Blocks that have these can't be constant.
583 CurBlock->hasBlockDeclRefExprs = true;
584
585 // If we have nested blocks, the decl may be declared in an outer block (in
586 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
587 // be defined outside all of the current blocks (in which case the blocks do
588 // all get the bit). Walk the nesting chain.
589 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
590 NextBlock = NextBlock->PrevBlockInfo) {
591 // If we found the defining block for the variable, don't mark the block as
592 // having a reference outside it.
593 if (NextBlock->TheDecl == VD->getDeclContext())
594 break;
595
596 // Otherwise, the DeclRef from the inner block causes the outer one to need
597 // a snapshot as well.
598 NextBlock->hasBlockDeclRefExprs = true;
599 }
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000600
601 return true;
602}
603
604
605
Steve Naroff0acc9c92007-09-15 18:49:24 +0000606/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000607/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000608/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000609/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000610/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000611Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
612 IdentifierInfo &II,
613 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000614 const CXXScopeSpec *SS,
615 bool isAddressOfOperand) {
616 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000617 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000618}
619
Douglas Gregor566782a2009-01-06 05:10:23 +0000620/// BuildDeclRefExpr - Build either a DeclRefExpr or a
621/// QualifiedDeclRefExpr based on whether or not SS is a
622/// nested-name-specifier.
Anders Carlsson4571d812009-06-24 00:10:43 +0000623Sema::OwningExprResult
Sebastian Redl0c9da212009-02-03 20:19:35 +0000624Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
625 bool TypeDependent, bool ValueDependent,
626 const CXXScopeSpec *SS) {
Anders Carlsson9bd48662009-06-26 19:16:07 +0000627 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
628 Diag(Loc,
629 diag::err_auto_variable_cannot_appear_in_own_initializer)
630 << D->getDeclName();
631 return ExprError();
632 }
Anders Carlsson4571d812009-06-24 00:10:43 +0000633
634 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
635 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
636 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
637 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
638 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
639 << D->getIdentifier() << FD->getDeclName();
640 Diag(D->getLocation(), diag::note_local_variable_declared_here)
641 << D->getIdentifier();
642 return ExprError();
643 }
644 }
645 }
646 }
647
Douglas Gregor98189262009-06-19 23:52:42 +0000648 MarkDeclarationReferenced(Loc, D);
Anders Carlsson4571d812009-06-24 00:10:43 +0000649
650 Expr *E;
Douglas Gregor7e508262009-03-19 03:51:16 +0000651 if (SS && !SS->isEmpty()) {
Anders Carlsson4571d812009-06-24 00:10:43 +0000652 E = new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
653 ValueDependent, SS->getRange(),
Douglas Gregor041e9292009-03-26 23:56:24 +0000654 static_cast<NestedNameSpecifier *>(SS->getScopeRep()));
Douglas Gregor7e508262009-03-19 03:51:16 +0000655 } else
Anders Carlsson4571d812009-06-24 00:10:43 +0000656 E = new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
657
658 return Owned(E);
Douglas Gregor566782a2009-01-06 05:10:23 +0000659}
660
Douglas Gregor723d3332009-01-07 00:43:41 +0000661/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
662/// variable corresponding to the anonymous union or struct whose type
663/// is Record.
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000664static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
665 RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000666 assert(Record->isAnonymousStructOrUnion() &&
667 "Record must be an anonymous struct or union!");
668
Mike Stumpe127ae32009-05-16 07:39:55 +0000669 // FIXME: Once Decls are directly linked together, this will be an O(1)
670 // operation rather than a slow walk through DeclContext's vector (which
671 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregor723d3332009-01-07 00:43:41 +0000672 DeclContext *Ctx = Record->getDeclContext();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000673 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
674 DEnd = Ctx->decls_end();
Douglas Gregor723d3332009-01-07 00:43:41 +0000675 D != DEnd; ++D) {
676 if (*D == Record) {
677 // The object for the anonymous struct/union directly
678 // follows its type in the list of declarations.
679 ++D;
680 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000681 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000682 return *D;
683 }
684 }
685
686 assert(false && "Missing object for anonymous record");
687 return 0;
688}
689
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000690/// \brief Given a field that represents a member of an anonymous
691/// struct/union, build the path from that field's context to the
692/// actual member.
693///
694/// Construct the sequence of field member references we'll have to
695/// perform to get to the field in the anonymous union/struct. The
696/// list of members is built from the field outward, so traverse it
697/// backwards to go from an object in the current context to the field
698/// we found.
699///
700/// \returns The variable from which the field access should begin,
701/// for an anonymous struct/union that is not a member of another
702/// class. Otherwise, returns NULL.
703VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
704 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000705 assert(Field->getDeclContext()->isRecord() &&
706 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
707 && "Field must be stored inside an anonymous struct or union");
708
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000709 Path.push_back(Field);
Douglas Gregor723d3332009-01-07 00:43:41 +0000710 VarDecl *BaseObject = 0;
711 DeclContext *Ctx = Field->getDeclContext();
712 do {
713 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000714 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000715 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000716 Path.push_back(AnonField);
Douglas Gregor723d3332009-01-07 00:43:41 +0000717 else {
718 BaseObject = cast<VarDecl>(AnonObject);
719 break;
720 }
721 Ctx = Ctx->getParent();
722 } while (Ctx->isRecord() &&
723 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000724
725 return BaseObject;
726}
727
728Sema::OwningExprResult
729Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
730 FieldDecl *Field,
731 Expr *BaseObjectExpr,
732 SourceLocation OpLoc) {
733 llvm::SmallVector<FieldDecl *, 4> AnonFields;
734 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
735 AnonFields);
736
Douglas Gregor723d3332009-01-07 00:43:41 +0000737 // Build the expression that refers to the base object, from
738 // which we will build a sequence of member references to each
739 // of the anonymous union objects and, eventually, the field we
740 // found via name lookup.
741 bool BaseObjectIsPointer = false;
742 unsigned ExtraQuals = 0;
743 if (BaseObject) {
744 // BaseObject is an anonymous struct/union variable (and is,
745 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000746 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregor98189262009-06-19 23:52:42 +0000747 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff774e4152009-01-21 00:14:39 +0000748 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump9afab102009-02-19 03:04:26 +0000749 SourceLocation());
Douglas Gregor723d3332009-01-07 00:43:41 +0000750 ExtraQuals
751 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
752 } else if (BaseObjectExpr) {
753 // The caller provided the base object expression. Determine
754 // whether its a pointer and whether it adds any qualifiers to the
755 // anonymous struct/union fields we're looking into.
756 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000757 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000758 BaseObjectIsPointer = true;
759 ObjectType = ObjectPtr->getPointeeType();
760 }
761 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
762 } else {
763 // We've found a member of an anonymous struct/union that is
764 // inside a non-anonymous struct/union, so in a well-formed
765 // program our base object expression is "this".
766 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
767 if (!MD->isStatic()) {
768 QualType AnonFieldType
769 = Context.getTagDeclType(
770 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
771 QualType ThisType = Context.getTagDeclType(MD->getParent());
772 if ((Context.getCanonicalType(AnonFieldType)
773 == Context.getCanonicalType(ThisType)) ||
774 IsDerivedFrom(ThisType, AnonFieldType)) {
775 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000776 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000777 MD->getThisType(Context));
Douglas Gregor723d3332009-01-07 00:43:41 +0000778 BaseObjectIsPointer = true;
779 }
780 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000781 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
782 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000783 }
784 ExtraQuals = MD->getTypeQualifiers();
785 }
786
787 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000788 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
789 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000790 }
791
792 // Build the implicit member references to the field of the
793 // anonymous struct/union.
794 Expr *Result = BaseObjectExpr;
Mon P Wang04d89cb2009-07-22 03:08:17 +0000795 unsigned BaseAddrSpace = BaseObjectExpr->getType().getAddressSpace();
Douglas Gregor723d3332009-01-07 00:43:41 +0000796 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
797 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
798 FI != FIEnd; ++FI) {
799 QualType MemberType = (*FI)->getType();
800 if (!(*FI)->isMutable()) {
801 unsigned combinedQualifiers
802 = MemberType.getCVRQualifiers() | ExtraQuals;
803 MemberType = MemberType.getQualifiedType(combinedQualifiers);
804 }
Mon P Wang04d89cb2009-07-22 03:08:17 +0000805 if (BaseAddrSpace != MemberType.getAddressSpace())
806 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor98189262009-06-19 23:52:42 +0000807 MarkDeclarationReferenced(Loc, *FI);
Steve Naroff774e4152009-01-21 00:14:39 +0000808 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
809 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000810 BaseObjectIsPointer = false;
811 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregor723d3332009-01-07 00:43:41 +0000812 }
813
Sebastian Redlcd883f72009-01-18 18:53:16 +0000814 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000815}
816
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000817/// ActOnDeclarationNameExpr - The parser has read some kind of name
818/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
819/// performs lookup on that name and returns an expression that refers
820/// to that name. This routine isn't directly called from the parser,
821/// because the parser doesn't know about DeclarationName. Rather,
822/// this routine is called by ActOnIdentifierExpr,
823/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
824/// which form the DeclarationName from the corresponding syntactic
825/// forms.
826///
827/// HasTrailingLParen indicates whether this identifier is used in a
828/// function call context. LookupCtx is only used for a C++
829/// qualified-id (foo::bar) to indicate the class or namespace that
830/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000831///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000832/// isAddressOfOperand means that this expression is the direct operand
833/// of an address-of operator. This matters because this is the only
834/// situation where a qualified name referencing a non-static member may
835/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000836Sema::OwningExprResult
837Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
838 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000839 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000840 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000841 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000842 if (SS && SS->isInvalid())
843 return ExprError();
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000844
845 // C++ [temp.dep.expr]p3:
846 // An id-expression is type-dependent if it contains:
847 // -- a nested-name-specifier that contains a class-name that
848 // names a dependent type.
Douglas Gregorf3a200f2009-05-29 14:49:33 +0000849 // FIXME: Member of the current instantiation.
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000850 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000851 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
852 Loc, SS->getRange(),
Anders Carlsson4e8d5692009-07-09 00:05:08 +0000853 static_cast<NestedNameSpecifier *>(SS->getScopeRep()),
854 isAddressOfOperand));
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000855 }
856
Douglas Gregor411889e2009-02-13 23:20:09 +0000857 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
858 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000859
Sebastian Redlcd883f72009-01-18 18:53:16 +0000860 if (Lookup.isAmbiguous()) {
861 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
862 SS && SS->isSet() ? SS->getRange()
863 : SourceRange());
864 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000865 }
866
867 NamedDecl *D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000868
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000869 // If this reference is in an Objective-C method, then ivar lookup happens as
870 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000871 IdentifierInfo *II = Name.getAsIdentifierInfo();
872 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000873 // There are two cases to handle here. 1) scoped lookup could have failed,
874 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000875 // found a decl, but that decl is outside the current instance method (i.e.
876 // a global variable). In these two cases, we do a lookup for an ivar with
877 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000878 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000879 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000880 ObjCInterfaceDecl *ClassDeclared;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000881 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000882 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000883 if (DiagnoseUseOfDecl(IV, Loc))
884 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000885
886 // If we're referencing an invalid decl, just return this as a silent
887 // error node. The error diagnostic was already emitted on the decl.
888 if (IV->isInvalidDecl())
889 return ExprError();
890
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000891 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
892 // If a class method attemps to use a free standing ivar, this is
893 // an error.
894 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
895 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
896 << IV->getDeclName());
897 // If a class method uses a global variable, even if an ivar with
898 // same name exists, use the global.
899 if (!IsClsMethod) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000900 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
901 ClassDeclared != IFace)
902 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Mike Stumpe127ae32009-05-16 07:39:55 +0000903 // FIXME: This should use a new expr for a direct reference, don't
904 // turn this into Self->ivar, just return a BareIVarExpr or something.
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000905 IdentifierInfo &II = Context.Idents.get("self");
Argiris Kirtzidis3bb49042009-07-18 08:49:37 +0000906 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, SourceLocation(),
907 II, false);
Douglas Gregor98189262009-06-19 23:52:42 +0000908 MarkDeclarationReferenced(Loc, IV);
Daniel Dunbarf5254bd2009-04-21 01:19:28 +0000909 return Owned(new (Context)
910 ObjCIvarRefExpr(IV, IV->getType(), Loc,
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000911 SelfExpr.takeAs<Expr>(), true, true));
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000912 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000913 }
Mike Stump90fc78e2009-08-04 21:02:39 +0000914 } else if (getCurMethodDecl()->isInstanceMethod()) {
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000915 // We should warn if a local variable hides an ivar.
916 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000917 ObjCInterfaceDecl *ClassDeclared;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000918 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000919 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
920 IFace == ClassDeclared)
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000921 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000922 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000923 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000924 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000925 if (D == 0 && II->isStr("super")) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000926 QualType T;
927
928 if (getCurMethodDecl()->isInstanceMethod())
Steve Naroff329ec222009-07-10 23:34:53 +0000929 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
930 getCurMethodDecl()->getClassInterface()));
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000931 else
932 T = Context.getObjCClassType();
Steve Naroff774e4152009-01-21 00:14:39 +0000933 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000934 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000935 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000936
Douglas Gregoraa57e862009-02-18 21:56:37 +0000937 // Determine whether this name might be a candidate for
938 // argument-dependent lookup.
939 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
940 HasTrailingLParen;
941
942 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000943 // We've seen something of the form
944 //
945 // identifier(
946 //
947 // and we did not find any entity by the name
948 // "identifier". However, this identifier is still subject to
949 // argument-dependent lookup, so keep track of the name.
950 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
951 Context.OverloadTy,
952 Loc));
953 }
954
Chris Lattner4b009652007-07-25 00:24:17 +0000955 if (D == 0) {
956 // Otherwise, this could be an implicitly declared function reference (legal
957 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000958 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000959 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000960 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000961 else {
962 // If this name wasn't predeclared and if this is not a function call,
963 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000964 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000965 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
966 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000967 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
968 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000969 return ExprError(Diag(Loc, diag::err_undeclared_use)
970 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000971 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000972 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000973 }
974 }
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000975
976 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
977 // Warn about constructs like:
978 // if (void *X = foo()) { ... } else { X }.
979 // In the else block, the pointer is always false.
980
981 // FIXME: In a template instantiation, we don't have scope
982 // information to check this property.
983 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
984 Scope *CheckS = S;
985 while (CheckS) {
986 if (CheckS->isWithinElse() &&
987 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
988 if (Var->getType()->isBooleanType())
989 ExprError(Diag(Loc, diag::warn_value_always_false)
990 << Var->getDeclName());
991 else
992 ExprError(Diag(Loc, diag::warn_value_always_zero)
993 << Var->getDeclName());
994 break;
995 }
996
997 // Move up one more control parent to check again.
998 CheckS = CheckS->getControlParent();
999 if (CheckS)
1000 CheckS = CheckS->getParent();
1001 }
1002 }
1003 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
1004 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1005 // C99 DR 316 says that, if a function type comes from a
1006 // function definition (without a prototype), that type is only
1007 // used for checking compatibility. Therefore, when referencing
1008 // the function, we pretend that we don't have the full function
1009 // type.
1010 if (DiagnoseUseOfDecl(Func, Loc))
1011 return ExprError();
Douglas Gregor723d3332009-01-07 00:43:41 +00001012
Douglas Gregor6ef403d2009-06-30 15:47:41 +00001013 QualType T = Func->getType();
1014 QualType NoProtoType = T;
1015 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
1016 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
1017 return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
1018 }
1019 }
1020
1021 return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand);
1022}
Fariborz Jahanian80b859e2009-07-29 18:40:24 +00001023/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanian843336e2009-07-29 19:40:11 +00001024bool
Fariborz Jahanian80b859e2009-07-29 18:40:24 +00001025Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
1026 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
1027 if (CXXRecordDecl *RD =
1028 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
1029 QualType DestType =
1030 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +00001031 if (DestType->isDependentType() || From->getType()->isDependentType())
1032 return false;
1033 QualType FromRecordType = From->getType();
1034 QualType DestRecordType = DestType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001035 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +00001036 DestType = Context.getPointerType(DestType);
1037 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian80b859e2009-07-29 18:40:24 +00001038 }
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +00001039 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
1040 CheckDerivedToBaseConversion(FromRecordType,
1041 DestRecordType,
1042 From->getSourceRange().getBegin(),
1043 From->getSourceRange()))
1044 return true;
Anders Carlsson85186942009-07-31 01:23:52 +00001045 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
1046 /*isLvalue=*/true);
Fariborz Jahanian80b859e2009-07-29 18:40:24 +00001047 }
Fariborz Jahanian843336e2009-07-29 19:40:11 +00001048 return false;
Fariborz Jahanian80b859e2009-07-29 18:40:24 +00001049}
Douglas Gregor6ef403d2009-06-30 15:47:41 +00001050
1051/// \brief Complete semantic analysis for a reference to the given declaration.
1052Sema::OwningExprResult
1053Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
1054 bool HasTrailingLParen,
1055 const CXXScopeSpec *SS,
1056 bool isAddressOfOperand) {
1057 assert(D && "Cannot refer to a NULL declaration");
1058 DeclarationName Name = D->getDeclName();
1059
Sebastian Redl0c9da212009-02-03 20:19:35 +00001060 // If this is an expression of the form &Class::member, don't build an
1061 // implicit member ref, because we want a pointer to the member in general,
1062 // not any specific instance's member.
1063 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001064 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor09be81b2009-02-04 17:27:36 +00001065 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +00001066 QualType DType;
1067 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1068 DType = FD->getType().getNonReferenceType();
1069 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1070 DType = Method->getType();
1071 } else if (isa<OverloadedFunctionDecl>(D)) {
1072 DType = Context.OverloadTy;
1073 }
1074 // Could be an inner type. That's diagnosed below, so ignore it here.
1075 if (!DType.isNull()) {
1076 // The pointer is type- and value-dependent if it points into something
1077 // dependent.
Douglas Gregorf3a200f2009-05-29 14:49:33 +00001078 bool Dependent = DC->isDependentContext();
Anders Carlsson4571d812009-06-24 00:10:43 +00001079 return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
Sebastian Redl0c9da212009-02-03 20:19:35 +00001080 }
1081 }
1082 }
1083
Douglas Gregor723d3332009-01-07 00:43:41 +00001084 // We may have found a field within an anonymous union or struct
1085 // (C++ [class.union]).
1086 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
1087 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
1088 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001089
Douglas Gregor3257fb52008-12-22 05:46:06 +00001090 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1091 if (!MD->isStatic()) {
1092 // C++ [class.mfct.nonstatic]p2:
1093 // [...] if name lookup (3.4.1) resolves the name in the
1094 // id-expression to a nonstatic nontype member of class X or of
1095 // a base class of X, the id-expression is transformed into a
1096 // class member access expression (5.2.5) using (*this) (9.3.2)
1097 // as the postfix-expression to the left of the '.' operator.
1098 DeclContext *Ctx = 0;
1099 QualType MemberType;
1100 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1101 Ctx = FD->getDeclContext();
1102 MemberType = FD->getType();
1103
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001104 if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
Douglas Gregor3257fb52008-12-22 05:46:06 +00001105 MemberType = RefType->getPointeeType();
1106 else if (!FD->isMutable()) {
1107 unsigned combinedQualifiers
1108 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
1109 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1110 }
1111 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1112 if (!Method->isStatic()) {
1113 Ctx = Method->getParent();
1114 MemberType = Method->getType();
1115 }
1116 } else if (OverloadedFunctionDecl *Ovl
1117 = dyn_cast<OverloadedFunctionDecl>(D)) {
1118 for (OverloadedFunctionDecl::function_iterator
1119 Func = Ovl->function_begin(),
1120 FuncEnd = Ovl->function_end();
1121 Func != FuncEnd; ++Func) {
1122 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
1123 if (!DMethod->isStatic()) {
1124 Ctx = Ovl->getDeclContext();
1125 MemberType = Context.OverloadTy;
1126 break;
1127 }
1128 }
1129 }
Douglas Gregor723d3332009-01-07 00:43:41 +00001130
1131 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001132 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
1133 QualType ThisType = Context.getTagDeclType(MD->getParent());
1134 if ((Context.getCanonicalType(CtxType)
1135 == Context.getCanonicalType(ThisType)) ||
1136 IsDerivedFrom(ThisType, CtxType)) {
1137 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +00001138 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +00001139 MD->getThisType(Context));
Douglas Gregor98189262009-06-19 23:52:42 +00001140 MarkDeclarationReferenced(Loc, D);
Fariborz Jahanian843336e2009-07-29 19:40:11 +00001141 if (PerformObjectMemberConversion(This, D))
1142 return ExprError();
Anders Carlsson9fbe6872009-08-08 16:55:18 +00001143 if (DiagnoseUseOfDecl(D, Loc))
1144 return ExprError();
Douglas Gregor09be81b2009-02-04 17:27:36 +00001145 return Owned(new (Context) MemberExpr(This, true, D,
Eli Friedman1653e232009-04-29 17:56:47 +00001146 Loc, MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001147 }
1148 }
1149 }
1150 }
1151
Douglas Gregor8acb7272008-12-11 16:49:14 +00001152 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001153 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1154 if (MD->isStatic())
1155 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +00001156 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
1157 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001158 }
1159
Douglas Gregor3257fb52008-12-22 05:46:06 +00001160 // Any other ways we could have found the field in a well-formed
1161 // program would have been turned into implicit member expressions
1162 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001163 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
1164 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001165 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00001166
Chris Lattner4b009652007-07-25 00:24:17 +00001167 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001168 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +00001169 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001170 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001171 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001172 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +00001173
Steve Naroffd6163f32008-09-05 22:11:13 +00001174 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +00001175 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001176 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
1177 false, false, SS);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001178 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001179 return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
1180 false, false, SS);
Steve Naroffd6163f32008-09-05 22:11:13 +00001181 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001182
Douglas Gregoraa57e862009-02-18 21:56:37 +00001183 // Check whether this declaration can be used. Note that we suppress
1184 // this check when we're going to perform argument-dependent lookup
1185 // on this function name, because this might not be the function
1186 // that overload resolution actually selects.
Douglas Gregor6ef403d2009-06-30 15:47:41 +00001187 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
1188 HasTrailingLParen;
Douglas Gregoraa57e862009-02-18 21:56:37 +00001189 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1190 return ExprError();
1191
Steve Naroffd6163f32008-09-05 22:11:13 +00001192 // Only create DeclRefExpr's for valid Decl's.
1193 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001194 return ExprError();
1195
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001196 // If the identifier reference is inside a block, and it refers to a value
1197 // that is outside the block, create a BlockDeclRefExpr instead of a
1198 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1199 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +00001200 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001201 // We do not do this for things like enum constants, global variables, etc,
1202 // as they do not get snapshotted.
1203 //
1204 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregor98189262009-06-19 23:52:42 +00001205 MarkDeclarationReferenced(Loc, VD);
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001206 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff52059382008-10-10 01:28:17 +00001207 // The BlocksAttr indicates the variable is bound by-reference.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00001208 if (VD->getAttr<BlocksAttr>())
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001209 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001210 // This is to record that a 'const' was actually synthesize and added.
1211 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff52059382008-10-10 01:28:17 +00001212 // Variable will be bound by-copy, make it const within the closure.
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001213
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001214 ExprTy.addConst();
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001215 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
1216 constAdded));
Steve Naroff52059382008-10-10 01:28:17 +00001217 }
1218 // If this reference is not in a block or if the referenced variable is
1219 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001220
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001221 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +00001222 bool ValueDependent = false;
1223 if (getLangOptions().CPlusPlus) {
1224 // C++ [temp.dep.expr]p3:
1225 // An id-expression is type-dependent if it contains:
1226 // - an identifier that was declared with a dependent type,
1227 if (VD->getType()->isDependentType())
1228 TypeDependent = true;
1229 // - FIXME: a template-id that is dependent,
1230 // - a conversion-function-id that specifies a dependent type,
1231 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1232 Name.getCXXNameType()->isDependentType())
1233 TypeDependent = true;
1234 // - a nested-name-specifier that contains a class-name that
1235 // names a dependent type.
1236 else if (SS && !SS->isEmpty()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001237 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregora5d84612008-12-10 20:57:37 +00001238 DC; DC = DC->getParent()) {
1239 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +00001240 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +00001241 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1242 if (Context.getTypeDeclType(Record)->isDependentType()) {
1243 TypeDependent = true;
1244 break;
1245 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001246 }
1247 }
1248 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001249
Douglas Gregora5d84612008-12-10 20:57:37 +00001250 // C++ [temp.dep.constexpr]p2:
1251 //
1252 // An identifier is value-dependent if it is:
1253 // - a name declared with a dependent type,
1254 if (TypeDependent)
1255 ValueDependent = true;
1256 // - the name of a non-type template parameter,
1257 else if (isa<NonTypeTemplateParmDecl>(VD))
1258 ValueDependent = true;
1259 // - a constant with integral or enumeration type and is
1260 // initialized with an expression that is value-dependent
Eli Friedman1f7744a2009-06-11 01:11:20 +00001261 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
1262 if (Dcl->getType().getCVRQualifiers() == QualType::Const &&
1263 Dcl->getInit()) {
1264 ValueDependent = Dcl->getInit()->isValueDependent();
1265 }
1266 }
Douglas Gregora5d84612008-12-10 20:57:37 +00001267 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001268
Anders Carlsson4571d812009-06-24 00:10:43 +00001269 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1270 TypeDependent, ValueDependent, SS);
Chris Lattner4b009652007-07-25 00:24:17 +00001271}
1272
Sebastian Redlcd883f72009-01-18 18:53:16 +00001273Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1274 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +00001275 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001276
Chris Lattner4b009652007-07-25 00:24:17 +00001277 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001278 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +00001279 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1280 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1281 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001282 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001283
Chris Lattner7e637512008-01-12 08:14:25 +00001284 // Pre-defined identifiers are of type char[x], where x is the length of the
1285 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001286 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +00001287 if (FunctionDecl *FD = getCurFunctionDecl())
1288 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +00001289 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1290 Length = MD->getSynthesizedMethodSize();
1291 else {
1292 Diag(Loc, diag::ext_predef_outside_function);
1293 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1294 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1295 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001296
1297
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001298 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001299 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001300 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +00001301 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +00001302}
1303
Sebastian Redlcd883f72009-01-18 18:53:16 +00001304Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +00001305 llvm::SmallString<16> CharBuffer;
1306 CharBuffer.resize(Tok.getLength());
1307 const char *ThisTokBegin = &CharBuffer[0];
1308 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001309
Chris Lattner4b009652007-07-25 00:24:17 +00001310 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1311 Tok.getLocation(), PP);
1312 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001313 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001314
1315 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1316
Sebastian Redl75324932009-01-20 22:23:13 +00001317 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1318 Literal.isWide(),
1319 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001320}
1321
Sebastian Redlcd883f72009-01-18 18:53:16 +00001322Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1323 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001324 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1325 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001326 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001327 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001328 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001329 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001330 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001331
Chris Lattner4b009652007-07-25 00:24:17 +00001332 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001333 // Add padding so that NumericLiteralParser can overread by one character.
1334 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001335 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001336
Chris Lattner4b009652007-07-25 00:24:17 +00001337 // Get the spelling of the token, which eliminates trigraphs, etc.
1338 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001339
Chris Lattner4b009652007-07-25 00:24:17 +00001340 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1341 Tok.getLocation(), PP);
1342 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001343 return ExprError();
1344
Chris Lattner1de66eb2007-08-26 03:42:43 +00001345 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001346
Chris Lattner1de66eb2007-08-26 03:42:43 +00001347 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001348 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001349 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001350 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001351 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001352 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001353 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001354 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001355
1356 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1357
Ted Kremenekddedbe22007-11-29 00:56:49 +00001358 // isExact will be set by GetFloatValue().
1359 bool isExact = false;
Chris Lattnerff1bf1a2009-06-29 17:34:55 +00001360 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1361 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001362
Chris Lattner1de66eb2007-08-26 03:42:43 +00001363 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001364 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001365 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001366 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001367
Neil Booth7421e9c2007-08-29 22:00:19 +00001368 // long long is a C99 feature.
1369 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001370 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001371 Diag(Tok.getLocation(), diag::ext_longlong);
1372
Chris Lattner4b009652007-07-25 00:24:17 +00001373 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001374 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001375
Chris Lattner4b009652007-07-25 00:24:17 +00001376 if (Literal.GetIntegerValue(ResultVal)) {
1377 // If this value didn't fit into uintmax_t, warn and force to ull.
1378 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001379 Ty = Context.UnsignedLongLongTy;
1380 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001381 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001382 } else {
1383 // If this value fits into a ULL, try to figure out what else it fits into
1384 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001385
Chris Lattner4b009652007-07-25 00:24:17 +00001386 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1387 // be an unsigned int.
1388 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1389
1390 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001391 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001392 if (!Literal.isLong && !Literal.isLongLong) {
1393 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001394 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001395
Chris Lattner4b009652007-07-25 00:24:17 +00001396 // Does it fit in a unsigned int?
1397 if (ResultVal.isIntN(IntSize)) {
1398 // Does it fit in a signed int?
1399 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001400 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001401 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001402 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001403 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001404 }
Chris Lattner4b009652007-07-25 00:24:17 +00001405 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001406
Chris Lattner4b009652007-07-25 00:24:17 +00001407 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001408 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001409 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001410
Chris Lattner4b009652007-07-25 00:24:17 +00001411 // Does it fit in a unsigned long?
1412 if (ResultVal.isIntN(LongSize)) {
1413 // Does it fit in a signed long?
1414 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001415 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001416 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001417 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001418 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001419 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001420 }
1421
Chris Lattner4b009652007-07-25 00:24:17 +00001422 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001423 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001424 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001425
Chris Lattner4b009652007-07-25 00:24:17 +00001426 // Does it fit in a unsigned long long?
1427 if (ResultVal.isIntN(LongLongSize)) {
1428 // Does it fit in a signed long long?
1429 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001430 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001431 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001432 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001433 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001434 }
1435 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001436
Chris Lattner4b009652007-07-25 00:24:17 +00001437 // If we still couldn't decide a type, we probably have something that
1438 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001439 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001440 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001441 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001442 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001443 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001444
Chris Lattnere4068872008-05-09 05:59:00 +00001445 if (ResultVal.getBitWidth() != Width)
1446 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001447 }
Sebastian Redl75324932009-01-20 22:23:13 +00001448 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001449 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001450
Chris Lattner1de66eb2007-08-26 03:42:43 +00001451 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1452 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001453 Res = new (Context) ImaginaryLiteral(Res,
1454 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001455
1456 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001457}
1458
Sebastian Redlcd883f72009-01-18 18:53:16 +00001459Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1460 SourceLocation R, ExprArg Val) {
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001461 Expr *E = Val.takeAs<Expr>();
Chris Lattner48d7f382008-04-02 04:24:33 +00001462 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001463 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001464}
1465
1466/// The UsualUnaryConversions() function is *not* called by this routine.
1467/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001468bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001469 SourceLocation OpLoc,
1470 const SourceRange &ExprRange,
1471 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001472 if (exprType->isDependentType())
1473 return false;
1474
Chris Lattner4b009652007-07-25 00:24:17 +00001475 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001476 if (isa<FunctionType>(exprType)) {
Chris Lattner95933c12009-04-24 00:30:45 +00001477 // alignof(function) is allowed as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001478 if (isSizeof)
1479 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1480 return false;
1481 }
1482
Chris Lattner95933c12009-04-24 00:30:45 +00001483 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001484 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001485 Diag(OpLoc, diag::ext_sizeof_void_type)
1486 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001487 return false;
1488 }
Chris Lattnere1127c42009-04-21 19:55:16 +00001489
Chris Lattner95933c12009-04-24 00:30:45 +00001490 if (RequireCompleteType(OpLoc, exprType,
1491 isSizeof ? diag::err_sizeof_incomplete_type :
1492 diag::err_alignof_incomplete_type,
1493 ExprRange))
1494 return true;
1495
1496 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianbf2b0952009-04-24 17:34:33 +00001497 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner95933c12009-04-24 00:30:45 +00001498 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnerf3ce8572009-04-24 22:30:50 +00001499 << exprType << isSizeof << ExprRange;
1500 return true;
Chris Lattnere1127c42009-04-21 19:55:16 +00001501 }
1502
Chris Lattner95933c12009-04-24 00:30:45 +00001503 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001504}
1505
Chris Lattner8d9f7962009-01-24 20:17:12 +00001506bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1507 const SourceRange &ExprRange) {
1508 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001509
Chris Lattner8d9f7962009-01-24 20:17:12 +00001510 // alignof decl is always ok.
1511 if (isa<DeclRefExpr>(E))
1512 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001513
1514 // Cannot know anything else if the expression is dependent.
1515 if (E->isTypeDependent())
1516 return false;
1517
Douglas Gregor531434b2009-05-02 02:18:30 +00001518 if (E->getBitField()) {
1519 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1520 return true;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001521 }
Douglas Gregor531434b2009-05-02 02:18:30 +00001522
1523 // Alignment of a field access is always okay, so long as it isn't a
1524 // bit-field.
1525 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump6eeaa782009-07-22 18:58:19 +00001526 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor531434b2009-05-02 02:18:30 +00001527 return false;
1528
Chris Lattner8d9f7962009-01-24 20:17:12 +00001529 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1530}
1531
Douglas Gregor396f1142009-03-13 21:01:28 +00001532/// \brief Build a sizeof or alignof expression given a type operand.
1533Action::OwningExprResult
1534Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1535 bool isSizeOf, SourceRange R) {
1536 if (T.isNull())
1537 return ExprError();
1538
1539 if (!T->isDependentType() &&
1540 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1541 return ExprError();
1542
1543 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1544 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1545 Context.getSizeType(), OpLoc,
1546 R.getEnd()));
1547}
1548
1549/// \brief Build a sizeof or alignof expression given an expression
1550/// operand.
1551Action::OwningExprResult
1552Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1553 bool isSizeOf, SourceRange R) {
1554 // Verify that the operand is valid.
1555 bool isInvalid = false;
1556 if (E->isTypeDependent()) {
1557 // Delay type-checking for type-dependent expressions.
1558 } else if (!isSizeOf) {
1559 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor531434b2009-05-02 02:18:30 +00001560 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor396f1142009-03-13 21:01:28 +00001561 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1562 isInvalid = true;
1563 } else {
1564 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1565 }
1566
1567 if (isInvalid)
1568 return ExprError();
1569
1570 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1571 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1572 Context.getSizeType(), OpLoc,
1573 R.getEnd()));
1574}
1575
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001576/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1577/// the same for @c alignof and @c __alignof
1578/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001579Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001580Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1581 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001582 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001583 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001584
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001585 if (isType) {
Douglas Gregor396f1142009-03-13 21:01:28 +00001586 QualType ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1587 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1588 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001589
Douglas Gregor396f1142009-03-13 21:01:28 +00001590 // Get the end location.
1591 Expr *ArgEx = (Expr *)TyOrEx;
1592 Action::OwningExprResult Result
1593 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1594
1595 if (Result.isInvalid())
1596 DeleteExpr(ArgEx);
1597
1598 return move(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001599}
1600
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001601QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001602 if (V->isTypeDependent())
1603 return Context.DependentTy;
Chris Lattner03931a72007-08-24 21:16:53 +00001604
Chris Lattnera16e42d2007-08-26 05:39:26 +00001605 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001606 if (const ComplexType *CT = V->getType()->getAsComplexType())
1607 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001608
1609 // Otherwise they pass through real integer and floating point types here.
1610 if (V->getType()->isArithmeticType())
1611 return V->getType();
1612
1613 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001614 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1615 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001616 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001617}
1618
1619
Chris Lattner4b009652007-07-25 00:24:17 +00001620
Sebastian Redl8b769972009-01-19 00:08:26 +00001621Action::OwningExprResult
1622Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1623 tok::TokenKind Kind, ExprArg Input) {
Nate Begemane85f43d2009-08-10 23:49:36 +00001624 // Since this might be a postfix expression, get rid of ParenListExprs.
1625 Input = MaybeConvertParenListExprToParenExpr(S, move(Input));
Sebastian Redl8b769972009-01-19 00:08:26 +00001626 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001627
Chris Lattner4b009652007-07-25 00:24:17 +00001628 UnaryOperator::Opcode Opc;
1629 switch (Kind) {
1630 default: assert(0 && "Unknown unary op!");
1631 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1632 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1633 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001634
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001635 if (getLangOptions().CPlusPlus &&
1636 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1637 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001638 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001639 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1640
1641 // C++ [over.inc]p1:
1642 //
1643 // [...] If the function is a member function with one
1644 // parameter (which shall be of type int) or a non-member
1645 // function with two parameters (the second of which shall be
1646 // of type int), it defines the postfix increment operator ++
1647 // for objects of that type. When the postfix increment is
1648 // called as a result of using the ++ operator, the int
1649 // argument will have value zero.
1650 Expr *Args[2] = {
1651 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001652 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1653 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001654 };
1655
1656 // Build the candidate set for overloading
1657 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001658 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001659
1660 // Perform overload resolution.
1661 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001662 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001663 case OR_Success: {
1664 // We found a built-in operator or an overloaded operator.
1665 FunctionDecl *FnDecl = Best->Function;
1666
1667 if (FnDecl) {
1668 // We matched an overloaded operator. Build a call to that
1669 // operator.
1670
1671 // Convert the arguments.
1672 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1673 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001674 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001675 } else {
1676 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001677 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001678 FnDecl->getParamDecl(0)->getType(),
1679 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001680 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001681 }
1682
1683 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001684 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001685 = FnDecl->getType()->getAsFunctionType()->getResultType();
1686 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001687
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001688 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001689 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001690 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001691 UsualUnaryConversions(FnExpr);
1692
Sebastian Redl8b769972009-01-19 00:08:26 +00001693 Input.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001694 Args[0] = Arg;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001695 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1696 Args, 2, ResultTy,
1697 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001698 } else {
1699 // We matched a built-in operator. Convert the arguments, then
1700 // break out so that we will build the appropriate built-in
1701 // operator node.
1702 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1703 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001704 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001705
1706 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001707 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001708 }
1709
1710 case OR_No_Viable_Function:
1711 // No viable function; fall through to handling this as a
1712 // built-in operator, which will produce an error message for us.
1713 break;
1714
1715 case OR_Ambiguous:
1716 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1717 << UnaryOperator::getOpcodeStr(Opc)
1718 << Arg->getSourceRange();
1719 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001720 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001721
1722 case OR_Deleted:
1723 Diag(OpLoc, diag::err_ovl_deleted_oper)
1724 << Best->Function->isDeleted()
1725 << UnaryOperator::getOpcodeStr(Opc)
1726 << Arg->getSourceRange();
1727 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1728 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001729 }
1730
1731 // Either we found no viable overloaded operator or we matched a
1732 // built-in operator. In either case, fall through to trying to
1733 // build a built-in operation.
1734 }
1735
Eli Friedman94d30952009-07-22 23:24:42 +00001736 Input.release();
1737 Input = Arg;
Eli Friedman79341142009-07-22 22:25:00 +00001738 return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
Chris Lattner4b009652007-07-25 00:24:17 +00001739}
1740
Sebastian Redl8b769972009-01-19 00:08:26 +00001741Action::OwningExprResult
1742Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1743 ExprArg Idx, SourceLocation RLoc) {
Nate Begemane85f43d2009-08-10 23:49:36 +00001744 // Since this might be a postfix expression, get rid of ParenListExprs.
1745 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1746
Sebastian Redl8b769972009-01-19 00:08:26 +00001747 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1748 *RHSExp = static_cast<Expr*>(Idx.get());
Nate Begemane85f43d2009-08-10 23:49:36 +00001749
Douglas Gregor80723c52008-11-19 17:17:41 +00001750 if (getLangOptions().CPlusPlus &&
Douglas Gregorde72f3e2009-05-19 00:01:19 +00001751 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1752 Base.release();
1753 Idx.release();
1754 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1755 Context.DependentTy, RLoc));
1756 }
1757
1758 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001759 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001760 LHSExp->getType()->isEnumeralType() ||
1761 RHSExp->getType()->isRecordType() ||
1762 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001763 // Add the appropriate overloaded operators (C++ [over.match.oper])
1764 // to the candidate set.
1765 OverloadCandidateSet CandidateSet;
1766 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001767 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1768 SourceRange(LLoc, RLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001769
Douglas Gregor80723c52008-11-19 17:17:41 +00001770 // Perform overload resolution.
1771 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001772 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001773 case OR_Success: {
1774 // We found a built-in operator or an overloaded operator.
1775 FunctionDecl *FnDecl = Best->Function;
1776
1777 if (FnDecl) {
1778 // We matched an overloaded operator. Build a call to that
1779 // operator.
1780
1781 // Convert the arguments.
1782 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1783 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1784 PerformCopyInitialization(RHSExp,
1785 FnDecl->getParamDecl(0)->getType(),
1786 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001787 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001788 } else {
1789 // Convert the arguments.
1790 if (PerformCopyInitialization(LHSExp,
1791 FnDecl->getParamDecl(0)->getType(),
1792 "passing") ||
1793 PerformCopyInitialization(RHSExp,
1794 FnDecl->getParamDecl(1)->getType(),
1795 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001796 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001797 }
1798
1799 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001800 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001801 = FnDecl->getType()->getAsFunctionType()->getResultType();
1802 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001803
Douglas Gregor80723c52008-11-19 17:17:41 +00001804 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001805 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1806 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001807 UsualUnaryConversions(FnExpr);
1808
Sebastian Redl8b769972009-01-19 00:08:26 +00001809 Base.release();
1810 Idx.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001811 Args[0] = LHSExp;
1812 Args[1] = RHSExp;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001813 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1814 FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001815 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001816 } else {
1817 // We matched a built-in operator. Convert the arguments, then
1818 // break out so that we will build the appropriate built-in
1819 // operator node.
1820 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1821 "passing") ||
1822 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1823 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001824 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001825
1826 break;
1827 }
1828 }
1829
1830 case OR_No_Viable_Function:
1831 // No viable function; fall through to handling this as a
1832 // built-in operator, which will produce an error message for us.
1833 break;
1834
1835 case OR_Ambiguous:
1836 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1837 << "[]"
1838 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1839 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001840 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001841
1842 case OR_Deleted:
1843 Diag(LLoc, diag::err_ovl_deleted_oper)
1844 << Best->Function->isDeleted()
1845 << "[]"
1846 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1847 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1848 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001849 }
1850
1851 // Either we found no viable overloaded operator or we matched a
1852 // built-in operator. In either case, fall through to trying to
1853 // build a built-in operation.
1854 }
1855
Chris Lattner4b009652007-07-25 00:24:17 +00001856 // Perform default conversions.
1857 DefaultFunctionArrayConversion(LHSExp);
1858 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001859
Chris Lattner4b009652007-07-25 00:24:17 +00001860 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1861
1862 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001863 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001864 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001865 // and index from the expression types.
1866 Expr *BaseExpr, *IndexExpr;
1867 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001868 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1869 BaseExpr = LHSExp;
1870 IndexExpr = RHSExp;
1871 ResultType = Context.DependentTy;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001872 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001873 BaseExpr = LHSExp;
1874 IndexExpr = RHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001875 ResultType = PTy->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001876 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001877 // Handle the uncommon case of "123[Ptr]".
1878 BaseExpr = RHSExp;
1879 IndexExpr = LHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001880 ResultType = PTy->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00001881 } else if (const ObjCObjectPointerType *PTy =
1882 LHSTy->getAsObjCObjectPointerType()) {
1883 BaseExpr = LHSExp;
1884 IndexExpr = RHSExp;
1885 ResultType = PTy->getPointeeType();
1886 } else if (const ObjCObjectPointerType *PTy =
1887 RHSTy->getAsObjCObjectPointerType()) {
1888 // Handle the uncommon case of "123[Ptr]".
1889 BaseExpr = RHSExp;
1890 IndexExpr = LHSExp;
1891 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001892 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1893 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001894 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001895
Chris Lattner4b009652007-07-25 00:24:17 +00001896 // FIXME: need to deal with const...
1897 ResultType = VTy->getElementType();
Eli Friedmand4614072009-04-25 23:46:54 +00001898 } else if (LHSTy->isArrayType()) {
1899 // If we see an array that wasn't promoted by
1900 // DefaultFunctionArrayConversion, it must be an array that
1901 // wasn't promoted because of the C90 rule that doesn't
1902 // allow promoting non-lvalue arrays. Warn, then
1903 // force the promotion here.
1904 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1905 LHSExp->getSourceRange();
1906 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1907 LHSTy = LHSExp->getType();
1908
1909 BaseExpr = LHSExp;
1910 IndexExpr = RHSExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001911 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmand4614072009-04-25 23:46:54 +00001912 } else if (RHSTy->isArrayType()) {
1913 // Same as previous, except for 123[f().a] case
1914 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1915 RHSExp->getSourceRange();
1916 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1917 RHSTy = RHSExp->getType();
1918
1919 BaseExpr = RHSExp;
1920 IndexExpr = LHSExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001921 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001922 } else {
Chris Lattner7264d212009-04-25 22:50:55 +00001923 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1924 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00001925 }
Chris Lattner4b009652007-07-25 00:24:17 +00001926 // C99 6.5.2.1p1
Nate Begemane85f43d2009-08-10 23:49:36 +00001927 if (!(IndexExpr->getType()->isIntegerType() &&
1928 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner7264d212009-04-25 22:50:55 +00001929 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1930 << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001931
Douglas Gregor05e28f62009-03-24 19:52:54 +00001932 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1933 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1934 // type. Note that Functions are not objects, and that (in C99 parlance)
1935 // incomplete types are not object types.
1936 if (ResultType->isFunctionType()) {
1937 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1938 << ResultType << BaseExpr->getSourceRange();
1939 return ExprError();
1940 }
Chris Lattner95933c12009-04-24 00:30:45 +00001941
Douglas Gregor05e28f62009-03-24 19:52:54 +00001942 if (!ResultType->isDependentType() &&
Chris Lattner95933c12009-04-24 00:30:45 +00001943 RequireCompleteType(LLoc, ResultType, diag::err_subscript_incomplete_type,
Douglas Gregor05e28f62009-03-24 19:52:54 +00001944 BaseExpr->getSourceRange()))
1945 return ExprError();
Chris Lattner95933c12009-04-24 00:30:45 +00001946
1947 // Diagnose bad cases where we step over interface counts.
1948 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1949 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1950 << ResultType << BaseExpr->getSourceRange();
1951 return ExprError();
1952 }
1953
Sebastian Redl8b769972009-01-19 00:08:26 +00001954 Base.release();
1955 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001956 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001957 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001958}
1959
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001960QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001961CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001962 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001963 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001964
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001965 // The vector accessor can't exceed the number of elements.
1966 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001967
Mike Stump9afab102009-02-19 03:04:26 +00001968 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001969 // special names that indicate a subset of exactly half the elements are
1970 // to be selected.
1971 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001972
Nate Begeman1486b502009-01-18 01:47:54 +00001973 // This flag determines whether or not CompName has an 's' char prefix,
1974 // indicating that it is a string of hex values to be used as vector indices.
Nate Begemane2ed6f72009-06-25 21:06:09 +00001975 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001976
1977 // Check that we've found one of the special components, or that the component
1978 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001979 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001980 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1981 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001982 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001983 do
1984 compStr++;
1985 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001986 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001987 do
1988 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001989 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001990 }
Nate Begeman1486b502009-01-18 01:47:54 +00001991
Mike Stump9afab102009-02-19 03:04:26 +00001992 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001993 // We didn't get to the end of the string. This means the component names
1994 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001995 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1996 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001997 return QualType();
1998 }
Mike Stump9afab102009-02-19 03:04:26 +00001999
Nate Begeman1486b502009-01-18 01:47:54 +00002000 // Ensure no component accessor exceeds the width of the vector type it
2001 // operates on.
2002 if (!HalvingSwizzle) {
2003 compStr = CompName.getName();
2004
2005 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00002006 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00002007
2008 while (*compStr) {
2009 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2010 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2011 << baseType << SourceRange(CompLoc);
2012 return QualType();
2013 }
2014 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00002015 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00002016
Nate Begeman1486b502009-01-18 01:47:54 +00002017 // If this is a halving swizzle, verify that the base type has an even
2018 // number of elements.
2019 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002020 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002021 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00002022 return QualType();
2023 }
Mike Stump9afab102009-02-19 03:04:26 +00002024
Steve Naroff1b8a46c2007-07-27 22:15:19 +00002025 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00002026 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00002027 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00002028 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00002029 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00002030 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
2031 : CompName.getLength();
2032 if (HexSwizzle)
2033 CompSize--;
2034
Steve Naroff1b8a46c2007-07-27 22:15:19 +00002035 if (CompSize == 1)
2036 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00002037
Nate Begemanaf6ed502008-04-18 23:10:10 +00002038 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00002039 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00002040 // diagostics look bad. We want extended vector types to appear built-in.
2041 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2042 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2043 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00002044 }
2045 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00002046}
2047
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002048static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
2049 IdentifierInfo &Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002050 const Selector &Sel,
2051 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002052
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002053 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(&Member))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002054 return PD;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002055 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002056 return OMD;
2057
2058 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2059 E = PDecl->protocol_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002060 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
2061 Context))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002062 return D;
2063 }
2064 return 0;
2065}
2066
Steve Naroffc75c1a82009-06-17 22:40:22 +00002067static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002068 IdentifierInfo &Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002069 const Selector &Sel,
2070 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002071 // Check protocols on qualified interfaces.
2072 Decl *GDecl = 0;
Steve Naroffc75c1a82009-06-17 22:40:22 +00002073 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002074 E = QIdTy->qual_end(); I != E; ++I) {
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002075 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002076 GDecl = PD;
2077 break;
2078 }
2079 // Also must look for a getter name which uses property syntax.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002080 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002081 GDecl = OMD;
2082 break;
2083 }
2084 }
2085 if (!GDecl) {
Steve Naroffc75c1a82009-06-17 22:40:22 +00002086 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002087 E = QIdTy->qual_end(); I != E; ++I) {
2088 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002089 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002090 if (GDecl)
2091 return GDecl;
2092 }
2093 }
2094 return GDecl;
2095}
Chris Lattner2cb744b2009-02-15 22:43:40 +00002096
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002097/// FindMethodInNestedImplementations - Look up a method in current and
2098/// all base class implementations.
2099///
2100ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
2101 const ObjCInterfaceDecl *IFace,
2102 const Selector &Sel) {
2103 ObjCMethodDecl *Method = 0;
Argiris Kirtzidisb1c4ee52009-07-21 00:06:04 +00002104 if (ObjCImplementationDecl *ImpDecl = IFace->getImplementation())
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002105 Method = ImpDecl->getInstanceMethod(Sel);
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002106
2107 if (!Method && IFace->getSuperClass())
2108 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
2109 return Method;
2110}
2111
Sebastian Redl8b769972009-01-19 00:08:26 +00002112Action::OwningExprResult
2113Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2114 tok::TokenKind OpKind, SourceLocation MemberLoc,
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00002115 IdentifierInfo &Member,
Douglas Gregorda61ad22009-08-06 03:17:00 +00002116 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
2117 // FIXME: handle the CXXScopeSpec for proper lookup of qualified-ids
2118 if (SS && SS->isInvalid())
2119 return ExprError();
2120
Nate Begemane85f43d2009-08-10 23:49:36 +00002121 // Since this might be a postfix expression, get rid of ParenListExprs.
2122 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
2123
Anders Carlssonc154a722009-05-01 19:30:39 +00002124 Expr *BaseExpr = Base.takeAs<Expr>();
Steve Naroff2cb66382007-07-26 03:11:44 +00002125 assert(BaseExpr && "no record expression");
Nate Begemane85f43d2009-08-10 23:49:36 +00002126
Steve Naroff137e11d2007-12-16 21:42:28 +00002127 // Perform default conversions.
2128 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00002129
Steve Naroff2cb66382007-07-26 03:11:44 +00002130 QualType BaseType = BaseExpr->getType();
David Chisnall44663db2009-08-17 16:35:33 +00002131 // If this is an Objective-C pseudo-builtin and a definition is provided then
2132 // use that.
2133 if (BaseType->isObjCIdType()) {
2134 // We have an 'id' type. Rather than fall through, we check if this
2135 // is a reference to 'isa'.
2136 if (BaseType != Context.ObjCIdRedefinitionType) {
2137 BaseType = Context.ObjCIdRedefinitionType;
2138 ImpCastExprToType(BaseExpr, BaseType);
2139 }
2140 } else if (BaseType->isObjCClassType() &&
2141 BaseType != Context.ObjCClassRedefinitionType) {
2142 BaseType = Context.ObjCClassRedefinitionType;
2143 ImpCastExprToType(BaseExpr, BaseType);
2144 }
Steve Naroff2cb66382007-07-26 03:11:44 +00002145 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00002146
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002147 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2148 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00002149 if (OpKind == tok::arrow) {
Anders Carlsson72d3c662009-05-15 23:10:19 +00002150 if (BaseType->isDependentType())
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002151 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2152 BaseExpr, true,
2153 OpLoc,
2154 DeclarationName(&Member),
2155 MemberLoc));
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002156 else if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff2cb66382007-07-26 03:11:44 +00002157 BaseType = PT->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00002158 else if (BaseType->isObjCObjectPointerType())
2159 ;
Steve Naroff2cb66382007-07-26 03:11:44 +00002160 else
Sebastian Redl8b769972009-01-19 00:08:26 +00002161 return ExprError(Diag(MemberLoc,
2162 diag::err_typecheck_member_reference_arrow)
2163 << BaseType << BaseExpr->getSourceRange());
Anders Carlsson72d3c662009-05-15 23:10:19 +00002164 } else {
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002165 if (BaseType->isDependentType()) {
2166 // Require that the base type isn't a pointer type
2167 // (so we'll report an error for)
2168 // T* t;
2169 // t.f;
2170 //
2171 // In Obj-C++, however, the above expression is valid, since it could be
2172 // accessing the 'f' property if T is an Obj-C interface. The extra check
2173 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002174 const PointerType *PT = BaseType->getAs<PointerType>();
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002175
2176 if (!PT || (getLangOptions().ObjC1 &&
2177 !PT->getPointeeType()->isRecordType()))
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002178 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2179 BaseExpr, false,
2180 OpLoc,
2181 DeclarationName(&Member),
2182 MemberLoc));
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002183 }
Chris Lattner4b009652007-07-25 00:24:17 +00002184 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002185
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002186 // Handle field access to simple records. This also handles access to fields
2187 // of the ObjC 'id' struct.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002188 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00002189 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorc84d8932009-03-09 16:13:40 +00002190 if (RequireCompleteType(OpLoc, BaseType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002191 diag::err_typecheck_incomplete_tag,
2192 BaseExpr->getSourceRange()))
2193 return ExprError();
2194
Douglas Gregorda61ad22009-08-06 03:17:00 +00002195 DeclContext *DC = RDecl;
2196 if (SS && SS->isSet()) {
2197 // If the member name was a qualified-id, look into the
2198 // nested-name-specifier.
2199 DC = computeDeclContext(*SS, false);
2200
2201 // FIXME: If DC is not computable, we should build a
2202 // CXXUnresolvedMemberExpr.
2203 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2204 }
2205
Steve Naroff2cb66382007-07-26 03:11:44 +00002206 // The record definition is complete, now make sure the member is valid.
Sebastian Redl8b769972009-01-19 00:08:26 +00002207 LookupResult Result
Douglas Gregorda61ad22009-08-06 03:17:00 +00002208 = LookupQualifiedName(DC, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00002209 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002210
Douglas Gregor12431cb2009-08-06 05:28:30 +00002211 if (SS && SS->isSet()) {
Douglas Gregorda61ad22009-08-06 03:17:00 +00002212 QualType BaseTypeCanon
2213 = Context.getCanonicalType(BaseType).getUnqualifiedType();
2214 QualType MemberTypeCanon
2215 = Context.getCanonicalType(
2216 Context.getTypeDeclType(
2217 dyn_cast<TypeDecl>(Result.getAsDecl()->getDeclContext())));
2218
2219 if (BaseTypeCanon != MemberTypeCanon &&
2220 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2221 return ExprError(Diag(SS->getBeginLoc(),
2222 diag::err_not_direct_base_or_virtual)
2223 << MemberTypeCanon << BaseTypeCanon);
2224 }
2225
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002226 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00002227 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
2228 << &Member << BaseExpr->getSourceRange());
Chris Lattner84ad8332009-03-31 08:18:48 +00002229 if (Result.isAmbiguous()) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002230 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
2231 MemberLoc, BaseExpr->getSourceRange());
2232 return ExprError();
Chris Lattner84ad8332009-03-31 08:18:48 +00002233 }
2234
2235 NamedDecl *MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002236
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002237 // If the decl being referenced had an error, return an error for this
2238 // sub-expr without emitting another error, in order to avoid cascading
2239 // error cases.
2240 if (MemberDecl->isInvalidDecl())
2241 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002242
Douglas Gregoraa57e862009-02-18 21:56:37 +00002243 // Check the use of this field
2244 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2245 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002246
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002247 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00002248 // We may have found a field within an anonymous union or struct
2249 // (C++ [class.union]).
2250 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00002251 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00002252 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00002253
Douglas Gregor82d44772008-12-20 23:49:58 +00002254 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002255 QualType MemberType = FD->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002256 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
Douglas Gregor82d44772008-12-20 23:49:58 +00002257 MemberType = Ref->getPointeeType();
2258 else {
Mon P Wang04d89cb2009-07-22 03:08:17 +00002259 unsigned BaseAddrSpace = BaseType.getAddressSpace();
Douglas Gregor82d44772008-12-20 23:49:58 +00002260 unsigned combinedQualifiers =
2261 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002262 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00002263 combinedQualifiers &= ~QualType::Const;
2264 MemberType = MemberType.getQualifiedType(combinedQualifiers);
Mon P Wang04d89cb2009-07-22 03:08:17 +00002265 if (BaseAddrSpace != MemberType.getAddressSpace())
2266 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor82d44772008-12-20 23:49:58 +00002267 }
Eli Friedman76b49832008-02-06 22:48:16 +00002268
Douglas Gregorcad27f62009-06-22 23:06:13 +00002269 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanian843336e2009-07-29 19:40:11 +00002270 if (PerformObjectMemberConversion(BaseExpr, FD))
2271 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002272 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
2273 MemberLoc, MemberType));
Chris Lattner84ad8332009-03-31 08:18:48 +00002274 }
2275
Douglas Gregorcad27f62009-06-22 23:06:13 +00002276 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2277 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Steve Naroff774e4152009-01-21 00:14:39 +00002278 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Chris Lattner84ad8332009-03-31 08:18:48 +00002279 Var, MemberLoc,
2280 Var->getType().getNonReferenceType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002281 }
2282 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2283 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Mike Stump9afab102009-02-19 03:04:26 +00002284 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Chris Lattner84ad8332009-03-31 08:18:48 +00002285 MemberFn, MemberLoc,
2286 MemberFn->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002287 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002288 if (OverloadedFunctionDecl *Ovl
2289 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00002290 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Chris Lattner84ad8332009-03-31 08:18:48 +00002291 MemberLoc, Context.OverloadTy));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002292 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2293 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Mike Stump9afab102009-02-19 03:04:26 +00002294 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
2295 Enum, MemberLoc, Enum->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002296 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002297 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00002298 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2299 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00002300
Douglas Gregor82d44772008-12-20 23:49:58 +00002301 // We found a declaration kind that we didn't expect. This is a
2302 // generic error message that tells the user that she can't refer
2303 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00002304 return ExprError(Diag(MemberLoc,
2305 diag::err_typecheck_member_reference_unknown)
2306 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00002307 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002308
Steve Naroff329ec222009-07-10 23:34:53 +00002309 // Handle properties on ObjC 'Class' types.
Steve Naroff7982a642009-07-13 17:19:15 +00002310 if (OpKind == tok::period && BaseType->isObjCClassType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00002311 // Also must look for a getter name which uses property syntax.
2312 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2313 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2314 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2315 ObjCMethodDecl *Getter;
2316 // FIXME: need to also look locally in the implementation.
2317 if ((Getter = IFace->lookupClassMethod(Sel))) {
2318 // Check the use of this method.
2319 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2320 return ExprError();
2321 }
2322 // If we found a getter then this may be a valid dot-reference, we
2323 // will look for the matching setter, in case it is needed.
2324 Selector SetterSel =
2325 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2326 PP.getSelectorTable(), &Member);
2327 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2328 if (!Setter) {
2329 // If this reference is in an @implementation, also check for 'private'
2330 // methods.
2331 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
2332 }
2333 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002334 if (!Setter)
2335 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff329ec222009-07-10 23:34:53 +00002336
2337 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2338 return ExprError();
2339
2340 if (Getter || Setter) {
2341 QualType PType;
2342
2343 if (Getter)
2344 PType = Getter->getResultType();
2345 else {
2346 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2347 E = Setter->param_end(); PI != E; ++PI)
2348 PType = (*PI)->getType();
2349 }
2350 // FIXME: we must check that the setter has property type.
2351 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2352 Setter, MemberLoc, BaseExpr));
2353 }
2354 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2355 << &Member << BaseType);
2356 }
2357 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002358 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2359 // (*Obj).ivar.
Steve Naroff329ec222009-07-10 23:34:53 +00002360 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2361 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
2362 const ObjCObjectPointerType *OPT = BaseType->getAsObjCObjectPointerType();
2363 const ObjCInterfaceType *IFaceT =
2364 OPT ? OPT->getInterfaceType() : BaseType->getAsObjCInterfaceType();
Steve Naroff4e743962009-07-16 00:25:06 +00002365 if (IFaceT) {
2366 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2367 ObjCInterfaceDecl *ClassDeclared;
2368 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(&Member, ClassDeclared);
2369
2370 if (IV) {
2371 // If the decl being referenced had an error, return an error for this
2372 // sub-expr without emitting another error, in order to avoid cascading
2373 // error cases.
2374 if (IV->isInvalidDecl())
2375 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00002376
Steve Naroff4e743962009-07-16 00:25:06 +00002377 // Check whether we can reference this field.
2378 if (DiagnoseUseOfDecl(IV, MemberLoc))
2379 return ExprError();
2380 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2381 IV->getAccessControl() != ObjCIvarDecl::Package) {
2382 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2383 if (ObjCMethodDecl *MD = getCurMethodDecl())
2384 ClassOfMethodDecl = MD->getClassInterface();
2385 else if (ObjCImpDecl && getCurFunctionDecl()) {
2386 // Case of a c-function declared inside an objc implementation.
2387 // FIXME: For a c-style function nested inside an objc implementation
2388 // class, there is no implementation context available, so we pass
2389 // down the context as argument to this routine. Ideally, this context
2390 // need be passed down in the AST node and somehow calculated from the
2391 // AST for a function decl.
2392 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
2393 if (ObjCImplementationDecl *IMPD =
2394 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2395 ClassOfMethodDecl = IMPD->getClassInterface();
2396 else if (ObjCCategoryImplDecl* CatImplClass =
2397 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2398 ClassOfMethodDecl = CatImplClass->getClassInterface();
2399 }
2400
2401 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2402 if (ClassDeclared != IDecl ||
2403 ClassOfMethodDecl != ClassDeclared)
2404 Diag(MemberLoc, diag::error_private_ivar_access)
2405 << IV->getDeclName();
Mike Stump90fc78e2009-08-04 21:02:39 +00002406 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2407 // @protected
Steve Naroff4e743962009-07-16 00:25:06 +00002408 Diag(MemberLoc, diag::error_protected_ivar_access)
2409 << IV->getDeclName();
Steve Narofff9606572009-03-04 18:34:24 +00002410 }
Steve Naroff4e743962009-07-16 00:25:06 +00002411
2412 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2413 MemberLoc, BaseExpr,
2414 OpKind == tok::arrow));
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002415 }
Steve Naroff4e743962009-07-16 00:25:06 +00002416 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
2417 << IDecl->getDeclName() << &Member
2418 << BaseExpr->getSourceRange());
Fariborz Jahanian09772392008-12-13 22:20:28 +00002419 }
Chris Lattnera57cf472008-07-21 04:28:12 +00002420 }
Steve Naroff7bffd372009-07-15 18:40:39 +00002421 // Handle properties on 'id' and qualified "id".
2422 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
2423 BaseType->isObjCQualifiedIdType())) {
2424 const ObjCObjectPointerType *QIdTy = BaseType->getAsObjCObjectPointerType();
2425
Steve Naroff329ec222009-07-10 23:34:53 +00002426 // Check protocols on qualified interfaces.
2427 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2428 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2429 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2430 // Check the use of this declaration
2431 if (DiagnoseUseOfDecl(PD, MemberLoc))
2432 return ExprError();
2433
2434 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2435 MemberLoc, BaseExpr));
2436 }
2437 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2438 // Check the use of this method.
2439 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2440 return ExprError();
2441
2442 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
2443 OMD->getResultType(),
2444 OMD, OpLoc, MemberLoc,
2445 NULL, 0));
2446 }
2447 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002448
Steve Naroff329ec222009-07-10 23:34:53 +00002449 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2450 << &Member << BaseType);
2451 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002452 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2453 // pointer to a (potentially qualified) interface type.
Steve Naroff329ec222009-07-10 23:34:53 +00002454 const ObjCObjectPointerType *OPT;
2455 if (OpKind == tok::period &&
2456 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2457 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2458 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
2459
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002460 // Search for a declared property first.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002461 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002462 // Check whether we can reference this property.
2463 if (DiagnoseUseOfDecl(PD, MemberLoc))
2464 return ExprError();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002465 QualType ResTy = PD->getType();
2466 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002467 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian80ccaa92009-05-08 20:20:55 +00002468 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2469 ResTy = Getter->getResultType();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002470 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner51f6fb32009-02-16 18:35:08 +00002471 MemberLoc, BaseExpr));
2472 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002473 // Check protocols on qualified interfaces.
Steve Naroff8194a542009-07-20 17:56:53 +00002474 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2475 E = OPT->qual_end(); I != E; ++I)
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002476 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002477 // Check whether we can reference this property.
2478 if (DiagnoseUseOfDecl(PD, MemberLoc))
2479 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00002480
Steve Naroff774e4152009-01-21 00:14:39 +00002481 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002482 MemberLoc, BaseExpr));
2483 }
Steve Naroff329ec222009-07-10 23:34:53 +00002484 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2485 E = OPT->qual_end(); I != E; ++I)
2486 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
2487 // Check whether we can reference this property.
2488 if (DiagnoseUseOfDecl(PD, MemberLoc))
2489 return ExprError();
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002490
Steve Naroff329ec222009-07-10 23:34:53 +00002491 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2492 MemberLoc, BaseExpr));
2493 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002494 // If that failed, look for an "implicit" property by seeing if the nullary
2495 // selector is implemented.
2496
2497 // FIXME: The logic for looking up nullary and unary selectors should be
2498 // shared with the code in ActOnInstanceMessage.
2499
2500 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002501 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002502
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002503 // If this reference is in an @implementation, check for 'private' methods.
2504 if (!Getter)
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002505 Getter = FindMethodInNestedImplementations(IFace, Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002506
Steve Naroff04151f32008-10-22 19:16:27 +00002507 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002508 if (!Getter)
2509 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002510 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002511 // Check if we can reference this property.
2512 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2513 return ExprError();
Steve Naroffdede0c92009-03-11 13:48:17 +00002514 }
2515 // If we found a getter then this may be a valid dot-reference, we
2516 // will look for the matching setter, in case it is needed.
2517 Selector SetterSel =
2518 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2519 PP.getSelectorTable(), &Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002520 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002521 if (!Setter) {
2522 // If this reference is in an @implementation, also check for 'private'
2523 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002524 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002525 }
2526 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002527 if (!Setter)
2528 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002529
Steve Naroffdede0c92009-03-11 13:48:17 +00002530 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2531 return ExprError();
2532
2533 if (Getter || Setter) {
2534 QualType PType;
2535
2536 if (Getter)
2537 PType = Getter->getResultType();
2538 else {
2539 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2540 E = Setter->param_end(); PI != E; ++PI)
2541 PType = (*PI)->getType();
2542 }
2543 // FIXME: we must check that the setter has property type.
2544 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2545 Setter, MemberLoc, BaseExpr));
2546 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002547 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2548 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00002549 }
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002550
Steve Naroff29d293b2009-07-24 17:54:45 +00002551 // Handle the following exceptional case (*Obj).isa.
2552 if (OpKind == tok::period &&
2553 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Steve Naroffbbe4f962009-07-29 14:06:03 +00002554 Member.isStr("isa"))
Steve Naroff29d293b2009-07-24 17:54:45 +00002555 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2556 Context.getObjCIdType()));
2557
Chris Lattnera57cf472008-07-21 04:28:12 +00002558 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00002559 if (BaseType->isExtVectorType()) {
Chris Lattnera57cf472008-07-21 04:28:12 +00002560 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2561 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00002562 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002563 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
Steve Naroff774e4152009-01-21 00:14:39 +00002564 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00002565 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002566
Douglas Gregor762da552009-03-27 06:00:30 +00002567 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2568 << BaseType << BaseExpr->getSourceRange();
2569
2570 // If the user is trying to apply -> or . to a function or function
2571 // pointer, it's probably because they forgot parentheses to call
2572 // the function. Suggest the addition of those parentheses.
2573 if (BaseType == Context.OverloadTy ||
2574 BaseType->isFunctionType() ||
2575 (BaseType->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002576 BaseType->getAs<PointerType>()->isFunctionType())) {
Douglas Gregor762da552009-03-27 06:00:30 +00002577 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2578 Diag(Loc, diag::note_member_reference_needs_call)
2579 << CodeModificationHint::CreateInsertion(Loc, "()");
2580 }
2581
2582 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00002583}
2584
Douglas Gregor3257fb52008-12-22 05:46:06 +00002585/// ConvertArgumentsForCall - Converts the arguments specified in
2586/// Args/NumArgs to the parameter types of the function FDecl with
2587/// function prototype Proto. Call is the call expression itself, and
2588/// Fn is the function expression. For a C++ member function, this
2589/// routine does not attempt to convert the object argument. Returns
2590/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00002591bool
2592Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002593 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002594 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002595 Expr **Args, unsigned NumArgs,
2596 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00002597 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00002598 // assignment, to the types of the corresponding parameter, ...
2599 unsigned NumArgsInProto = Proto->getNumArgs();
2600 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002601 bool Invalid = false;
2602
Douglas Gregor3257fb52008-12-22 05:46:06 +00002603 // If too few arguments are available (and we don't have default
2604 // arguments for the remaining parameters), don't make the call.
2605 if (NumArgs < NumArgsInProto) {
2606 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2607 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2608 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2609 // Use default arguments for missing arguments
2610 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00002611 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002612 }
2613
2614 // If too many are passed and not variadic, error on the extras and drop
2615 // them.
2616 if (NumArgs > NumArgsInProto) {
2617 if (!Proto->isVariadic()) {
2618 Diag(Args[NumArgsInProto]->getLocStart(),
2619 diag::err_typecheck_call_too_many_args)
2620 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2621 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2622 Args[NumArgs-1]->getLocEnd());
2623 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002624 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002625 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002626 }
2627 NumArgsToCheck = NumArgsInProto;
2628 }
Mike Stump9afab102009-02-19 03:04:26 +00002629
Douglas Gregor3257fb52008-12-22 05:46:06 +00002630 // Continue to check argument types (even if we have too few/many args).
2631 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2632 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00002633
Douglas Gregor3257fb52008-12-22 05:46:06 +00002634 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002635 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002636 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002637
Eli Friedman83dec9e2009-03-22 22:00:50 +00002638 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2639 ProtoArgType,
2640 diag::err_call_incomplete_argument,
2641 Arg->getSourceRange()))
2642 return true;
2643
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002644 // Pass the argument.
2645 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2646 return true;
Anders Carlssona116e6e2009-06-12 16:51:40 +00002647 } else {
2648 if (FDecl->getParamDecl(i)->hasUnparsedDefaultArg()) {
2649 Diag (Call->getSourceRange().getBegin(),
2650 diag::err_use_of_default_argument_to_function_declared_later) <<
2651 FDecl << cast<CXXRecordDecl>(FDecl->getDeclContext())->getDeclName();
2652 Diag(UnparsedDefaultArgLocs[FDecl->getParamDecl(i)],
2653 diag::note_default_argument_declared_here);
Anders Carlsson37bb2bd2009-06-16 03:37:31 +00002654 } else {
2655 Expr *DefaultExpr = FDecl->getParamDecl(i)->getDefaultArg();
2656
2657 // If the default expression creates temporaries, we need to
2658 // push them to the current stack of expression temporaries so they'll
2659 // be properly destroyed.
2660 if (CXXExprWithTemporaries *E
2661 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
2662 assert(!E->shouldDestroyTemporaries() &&
2663 "Can't destroy temporaries in a default argument expr!");
2664 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2665 ExprTemporaries.push_back(E->getTemporary(I));
2666 }
Anders Carlssona116e6e2009-06-12 16:51:40 +00002667 }
Anders Carlsson37bb2bd2009-06-16 03:37:31 +00002668
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002669 // We already type-checked the argument, so we know it works.
Anders Carlsson3d752db2009-08-14 18:30:22 +00002670 Arg = CXXDefaultArgExpr::Create(Context, FDecl->getParamDecl(i));
Anders Carlssona116e6e2009-06-12 16:51:40 +00002671 }
2672
Douglas Gregor3257fb52008-12-22 05:46:06 +00002673 QualType ArgType = Arg->getType();
Mike Stump9afab102009-02-19 03:04:26 +00002674
Douglas Gregor3257fb52008-12-22 05:46:06 +00002675 Call->setArg(i, Arg);
2676 }
Mike Stump9afab102009-02-19 03:04:26 +00002677
Douglas Gregor3257fb52008-12-22 05:46:06 +00002678 // If this is a variadic call, handle args passed through "...".
2679 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002680 VariadicCallType CallType = VariadicFunction;
2681 if (Fn->getType()->isBlockPointerType())
2682 CallType = VariadicBlock; // Block
2683 else if (isa<MemberExpr>(Fn))
2684 CallType = VariadicMethod;
2685
Douglas Gregor3257fb52008-12-22 05:46:06 +00002686 // Promote the arguments (C99 6.5.2.2p7).
2687 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2688 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00002689 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002690 Call->setArg(i, Arg);
2691 }
2692 }
2693
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002694 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002695}
2696
Steve Naroff87d58b42007-09-16 03:34:24 +00002697/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002698/// This provides the location of the left/right parens and a list of comma
2699/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002700Action::OwningExprResult
2701Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2702 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002703 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002704 unsigned NumArgs = args.size();
Nate Begemane85f43d2009-08-10 23:49:36 +00002705
2706 // Since this might be a postfix expression, get rid of ParenListExprs.
2707 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
2708
Anders Carlssonc154a722009-05-01 19:30:39 +00002709 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl8b769972009-01-19 00:08:26 +00002710 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002711 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002712 FunctionDecl *FDecl = NULL;
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002713 NamedDecl *NDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002714 DeclarationName UnqualifiedName;
Nate Begemane85f43d2009-08-10 23:49:36 +00002715
Douglas Gregor3257fb52008-12-22 05:46:06 +00002716 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002717 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002718 // in which case we won't do any semantic analysis now.
Mike Stumpe127ae32009-05-16 07:39:55 +00002719 // FIXME: Will need to cache the results of name lookup (including ADL) in
2720 // Fn.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002721 bool Dependent = false;
2722 if (Fn->isTypeDependent())
2723 Dependent = true;
2724 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2725 Dependent = true;
2726
2727 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002728 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002729 Context.DependentTy, RParenLoc));
2730
2731 // Determine whether this is a call to an object (C++ [over.call.object]).
2732 if (Fn->getType()->isRecordType())
2733 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2734 CommaLocs, RParenLoc));
2735
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002736 // Determine whether this is a call to a member function.
Douglas Gregorb60eb752009-06-25 22:08:12 +00002737 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2738 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2739 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2740 isa<CXXMethodDecl>(MemDecl) ||
2741 (isa<FunctionTemplateDecl>(MemDecl) &&
2742 isa<CXXMethodDecl>(
2743 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redl8b769972009-01-19 00:08:26 +00002744 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2745 CommaLocs, RParenLoc));
Douglas Gregorb60eb752009-06-25 22:08:12 +00002746 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00002747 }
2748
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002749 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002750 // Also, in C++, keep track of whether we should perform argument-dependent
2751 // lookup and whether there were any explicitly-specified template arguments.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002752 Expr *FnExpr = Fn;
2753 bool ADL = true;
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002754 bool HasExplicitTemplateArgs = 0;
2755 const TemplateArgument *ExplicitTemplateArgs = 0;
2756 unsigned NumExplicitTemplateArgs = 0;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002757 while (true) {
2758 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2759 FnExpr = IcExpr->getSubExpr();
2760 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002761 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002762 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002763 ADL = false;
2764 FnExpr = PExpr->getSubExpr();
2765 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002766 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002767 == UnaryOperator::AddrOf) {
2768 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor28857752009-06-30 22:34:41 +00002769 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002770 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2771 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
Douglas Gregor28857752009-06-30 22:34:41 +00002772 NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl());
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002773 break;
Mike Stump9afab102009-02-19 03:04:26 +00002774 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002775 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2776 UnqualifiedName = DepName->getName();
2777 break;
Douglas Gregor28857752009-06-30 22:34:41 +00002778 } else if (TemplateIdRefExpr *TemplateIdRef
2779 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2780 NDecl = TemplateIdRef->getTemplateName().getAsTemplateDecl();
Douglas Gregor6631cb42009-07-29 18:26:50 +00002781 if (!NDecl)
2782 NDecl = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002783 HasExplicitTemplateArgs = true;
2784 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2785 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2786
2787 // C++ [temp.arg.explicit]p6:
2788 // [Note: For simple function names, argument dependent lookup (3.4.2)
2789 // applies even when the function name is not visible within the
2790 // scope of the call. This is because the call still has the syntactic
2791 // form of a function call (3.4.1). But when a function template with
2792 // explicit template arguments is used, the call does not have the
2793 // correct syntactic form unless there is a function template with
2794 // that name visible at the point of the call. If no such name is
2795 // visible, the call is not syntactically well-formed and
2796 // argument-dependent lookup does not apply. If some such name is
2797 // visible, argument dependent lookup applies and additional function
2798 // templates may be found in other namespaces.
2799 //
2800 // The summary of this paragraph is that, if we get to this point and the
2801 // template-id was not a qualified name, then argument-dependent lookup
2802 // is still possible.
2803 if (TemplateIdRef->getQualifier())
2804 ADL = false;
Douglas Gregor28857752009-06-30 22:34:41 +00002805 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002806 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002807 // Any kind of name that does not refer to a declaration (or
2808 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2809 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002810 break;
2811 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002812 }
Mike Stump9afab102009-02-19 03:04:26 +00002813
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002814 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregorb60eb752009-06-25 22:08:12 +00002815 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregor28857752009-06-30 22:34:41 +00002816 if (NDecl) {
2817 FDecl = dyn_cast<FunctionDecl>(NDecl);
2818 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
Douglas Gregorb60eb752009-06-25 22:08:12 +00002819 FDecl = FunctionTemplate->getTemplatedDecl();
2820 else
Douglas Gregor28857752009-06-30 22:34:41 +00002821 FDecl = dyn_cast<FunctionDecl>(NDecl);
2822 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002823 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002824
Douglas Gregorb60eb752009-06-25 22:08:12 +00002825 if (Ovl || FunctionTemplate ||
2826 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002827 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002828 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002829 ADL = false;
2830
Douglas Gregorfcb19192009-02-11 23:02:49 +00002831 // We don't perform ADL in C.
2832 if (!getLangOptions().CPlusPlus)
2833 ADL = false;
2834
Douglas Gregorb60eb752009-06-25 22:08:12 +00002835 if (Ovl || FunctionTemplate || ADL) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002836 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
2837 HasExplicitTemplateArgs,
2838 ExplicitTemplateArgs,
2839 NumExplicitTemplateArgs,
2840 LParenLoc, Args, NumArgs, CommaLocs,
2841 RParenLoc, ADL);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002842 if (!FDecl)
2843 return ExprError();
2844
2845 // Update Fn to refer to the actual function selected.
2846 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002847 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor28857752009-06-30 22:34:41 +00002848 = dyn_cast<QualifiedDeclRefExpr>(FnExpr))
Douglas Gregor1e589cc2009-03-26 23:50:42 +00002849 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2850 QDRExpr->getLocation(),
2851 false, false,
2852 QDRExpr->getQualifierRange(),
2853 QDRExpr->getQualifier());
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002854 else
Mike Stump9afab102009-02-19 03:04:26 +00002855 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002856 Fn->getSourceRange().getBegin());
2857 Fn->Destroy(Context);
2858 Fn = NewFn;
2859 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002860 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002861
2862 // Promote the function operand.
2863 UsualUnaryConversions(Fn);
2864
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002865 // Make the call expr early, before semantic checks. This guarantees cleanup
2866 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002867 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2868 Args, NumArgs,
2869 Context.BoolTy,
2870 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002871
Steve Naroffd6163f32008-09-05 22:11:13 +00002872 const FunctionType *FuncT;
2873 if (!Fn->getType()->isBlockPointerType()) {
2874 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2875 // have type pointer to function".
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002876 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffd6163f32008-09-05 22:11:13 +00002877 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002878 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2879 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002880 FuncT = PT->getPointeeType()->getAsFunctionType();
2881 } else { // This is a block call.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002882 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
Steve Naroffd6163f32008-09-05 22:11:13 +00002883 getAsFunctionType();
2884 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002885 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002886 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2887 << Fn->getType() << Fn->getSourceRange());
2888
Eli Friedman83dec9e2009-03-22 22:00:50 +00002889 // Check for a valid return type
2890 if (!FuncT->getResultType()->isVoidType() &&
2891 RequireCompleteType(Fn->getSourceRange().getBegin(),
2892 FuncT->getResultType(),
2893 diag::err_call_incomplete_return,
2894 TheCall->getSourceRange()))
2895 return ExprError();
2896
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002897 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002898 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002899
Douglas Gregor4fa58902009-02-26 23:50:07 +00002900 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002901 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002902 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002903 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002904 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002905 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002906
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002907 if (FDecl) {
2908 // Check if we have too few/too many template arguments, based
2909 // on our knowledge of the function definition.
2910 const FunctionDecl *Def = 0;
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00002911 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanf7ed7812009-06-01 09:24:59 +00002912 const FunctionProtoType *Proto =
2913 Def->getType()->getAsFunctionProtoType();
2914 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2915 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2916 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2917 }
2918 }
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002919 }
2920
Steve Naroffdb65e052007-08-28 23:30:39 +00002921 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002922 for (unsigned i = 0; i != NumArgs; i++) {
2923 Expr *Arg = Args[i];
2924 DefaultArgumentPromotion(Arg);
Eli Friedman83dec9e2009-03-22 22:00:50 +00002925 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2926 Arg->getType(),
2927 diag::err_call_incomplete_argument,
2928 Arg->getSourceRange()))
2929 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002930 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002931 }
Chris Lattner4b009652007-07-25 00:24:17 +00002932 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002933
Douglas Gregor3257fb52008-12-22 05:46:06 +00002934 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2935 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002936 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2937 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002938
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002939 // Check for sentinels
2940 if (NDecl)
2941 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Anders Carlsson7fb13802009-08-16 01:56:34 +00002942
Chris Lattner2e64c072007-08-10 20:18:51 +00002943 // Do special checking on direct calls to functions.
Anders Carlsson7fb13802009-08-16 01:56:34 +00002944 if (FDecl) {
2945 if (CheckFunctionCall(FDecl, TheCall.get()))
2946 return ExprError();
2947
2948 if (unsigned BuiltinID = FDecl->getBuiltinID(Context))
2949 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
2950 } else if (NDecl) {
2951 if (CheckBlockCall(NDecl, TheCall.get()))
2952 return ExprError();
2953 }
Chris Lattner2e64c072007-08-10 20:18:51 +00002954
Anders Carlsson54ad8a02009-08-16 03:06:32 +00002955 return MaybeBindToTemporary(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002956}
2957
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002958Action::OwningExprResult
2959Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2960 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002961 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002962 QualType literalType = QualType::getFromOpaquePtr(Ty);
2963 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002964 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002965 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002966
Eli Friedman8c2173d2008-05-20 05:22:08 +00002967 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002968 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002969 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2970 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregored71c542009-05-21 23:48:18 +00002971 } else if (!literalType->isDependentType() &&
2972 RequireCompleteType(LParenLoc, literalType,
2973 diag::err_typecheck_decl_incomplete_type,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002974 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002975 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002976
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002977 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002978 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002979 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002980
Chris Lattnere5cb5862008-12-04 23:50:19 +00002981 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002982 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002983 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002984 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002985 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002986 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002987 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002988 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002989}
2990
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002991Action::OwningExprResult
2992Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002993 SourceLocation RBraceLoc) {
2994 unsigned NumInit = initlist.size();
2995 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002996
Steve Naroff0acc9c92007-09-15 18:49:24 +00002997 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002998 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002999
Mike Stump9afab102009-02-19 03:04:26 +00003000 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00003001 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00003002 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003003 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00003004}
3005
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003006/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlc358b622009-07-29 13:50:23 +00003007bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Anders Carlsson9583fa72009-08-07 22:21:05 +00003008 CastExpr::CastKind& Kind, bool FunctionalStyle) {
Sebastian Redl0e35d042009-07-25 15:41:38 +00003009 if (getLangOptions().CPlusPlus)
Anders Carlsson9583fa72009-08-07 22:21:05 +00003010 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle);
Sebastian Redl0e35d042009-07-25 15:41:38 +00003011
Eli Friedman01e0f652009-08-15 19:02:19 +00003012 DefaultFunctionArrayConversion(castExpr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003013
3014 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3015 // type needs to be scalar.
3016 if (castType->isVoidType()) {
3017 // Cast to void allows any expr type.
3018 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003019 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
3020 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
3021 (castType->isStructureType() || castType->isUnionType())) {
3022 // GCC struct/union extension: allow cast to self.
Eli Friedman2b128322009-03-23 00:24:07 +00003023 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003024 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3025 << castType << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00003026 Kind = CastExpr::CK_NoOp;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003027 } else if (castType->isUnionType()) {
3028 // GCC cast to union extension
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003029 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003030 RecordDecl::field_iterator Field, FieldEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003031 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003032 Field != FieldEnd; ++Field) {
3033 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
3034 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
3035 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3036 << castExpr->getSourceRange();
3037 break;
3038 }
3039 }
3040 if (Field == FieldEnd)
3041 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3042 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00003043 Kind = CastExpr::CK_ToUnion;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003044 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003045 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00003046 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003047 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003048 }
Mike Stump9afab102009-02-19 03:04:26 +00003049 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003050 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003051 return Diag(castExpr->getLocStart(),
3052 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003053 << castExpr->getType() << castExpr->getSourceRange();
Nate Begemanbd42e022009-06-26 00:50:28 +00003054 } else if (castType->isExtVectorType()) {
3055 if (CheckExtVectorCast(TyR, castType, castExpr->getType()))
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003056 return true;
3057 } else if (castType->isVectorType()) {
3058 if (CheckVectorCast(TyR, castType, castExpr->getType()))
3059 return true;
Nate Begemanbd42e022009-06-26 00:50:28 +00003060 } else if (castExpr->getType()->isVectorType()) {
3061 if (CheckVectorCast(TyR, castExpr->getType(), castType))
3062 return true;
Steve Naroffff6c8022009-03-04 15:11:40 +00003063 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroff49fd7ad2009-04-08 23:52:26 +00003064 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Eli Friedman970e56c2009-05-01 02:23:58 +00003065 } else if (!castType->isArithmeticType()) {
3066 QualType castExprType = castExpr->getType();
3067 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3068 return Diag(castExpr->getLocStart(),
3069 diag::err_cast_pointer_from_non_pointer_int)
3070 << castExprType << castExpr->getSourceRange();
3071 } else if (!castExpr->getType()->isArithmeticType()) {
3072 if (!castType->isIntegralType() && castType->isArithmeticType())
3073 return Diag(castExpr->getLocStart(),
3074 diag::err_cast_pointer_to_non_pointer_int)
3075 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003076 }
Fariborz Jahanian4862e872009-05-22 21:42:52 +00003077 if (isa<ObjCSelectorExpr>(castExpr))
3078 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003079 return false;
3080}
3081
Chris Lattnerd1f26b32007-12-20 00:44:32 +00003082bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003083 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00003084
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003085 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003086 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003087 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00003088 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003089 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00003090 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003091 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003092 } else
3093 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00003094 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003095 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00003096
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003097 return false;
3098}
3099
Nate Begemanbd42e022009-06-26 00:50:28 +00003100bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) {
3101 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
3102
Nate Begeman9e063702009-06-27 22:05:55 +00003103 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3104 // an ExtVectorType.
Nate Begemanbd42e022009-06-26 00:50:28 +00003105 if (SrcTy->isVectorType()) {
3106 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3107 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3108 << DestTy << SrcTy << R;
3109 return false;
3110 }
3111
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003112 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanbd42e022009-06-26 00:50:28 +00003113 // conversion will take place first from scalar to elt type, and then
3114 // splat from elt type to vector.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003115 if (SrcTy->isPointerType())
3116 return Diag(R.getBegin(),
3117 diag::err_invalid_conversion_between_vector_and_scalar)
3118 << DestTy << SrcTy << R;
Nate Begemanbd42e022009-06-26 00:50:28 +00003119 return false;
3120}
3121
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003122Action::OwningExprResult
Nate Begemane85f43d2009-08-10 23:49:36 +00003123Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003124 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlsson9583fa72009-08-07 22:21:05 +00003125 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3126
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003127 assert((Ty != 0) && (Op.get() != 0) &&
3128 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00003129
Nate Begemane85f43d2009-08-10 23:49:36 +00003130 Expr *castExpr = (Expr *)Op.get();
Chris Lattner4b009652007-07-25 00:24:17 +00003131 QualType castType = QualType::getFromOpaquePtr(Ty);
Nate Begemane85f43d2009-08-10 23:49:36 +00003132
3133 // If the Expr being casted is a ParenListExpr, handle it specially.
3134 if (isa<ParenListExpr>(castExpr))
3135 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Chris Lattner4b009652007-07-25 00:24:17 +00003136
Anders Carlsson9583fa72009-08-07 22:21:05 +00003137 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
3138 Kind))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003139 return ExprError();
Nate Begemane85f43d2009-08-10 23:49:36 +00003140
3141 Op.release();
Sebastian Redl0e35d042009-07-25 15:41:38 +00003142 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Anders Carlsson9583fa72009-08-07 22:21:05 +00003143 Kind, castExpr, castType,
3144 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00003145}
3146
Nate Begemane85f43d2009-08-10 23:49:36 +00003147/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3148/// of comma binary operators.
3149Action::OwningExprResult
3150Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3151 Expr *expr = EA.takeAs<Expr>();
3152 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3153 if (!E)
3154 return Owned(expr);
3155
3156 OwningExprResult Result(*this, E->getExpr(0));
3157
3158 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3159 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3160 Owned(E->getExpr(i)));
3161
3162 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3163}
3164
3165Action::OwningExprResult
3166Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3167 SourceLocation RParenLoc, ExprArg Op,
3168 QualType Ty) {
3169 ParenListExpr *PE = (ParenListExpr *)Op.get();
3170
3171 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
3172 // then handle it as such.
3173 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3174 if (PE->getNumExprs() == 0) {
3175 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3176 return ExprError();
3177 }
3178
3179 llvm::SmallVector<Expr *, 8> initExprs;
3180 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3181 initExprs.push_back(PE->getExpr(i));
3182
3183 // FIXME: This means that pretty-printing the final AST will produce curly
3184 // braces instead of the original commas.
3185 Op.release();
3186 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
3187 initExprs.size(), RParenLoc);
3188 E->setType(Ty);
3189 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
3190 Owned(E));
3191 } else {
3192 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
3193 // sequence of BinOp comma operators.
3194 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3195 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3196 }
3197}
3198
3199Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3200 SourceLocation R,
3201 MultiExprArg Val) {
3202 unsigned nexprs = Val.size();
3203 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3204 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3205 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3206 return Owned(expr);
3207}
3208
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003209/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3210/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00003211/// C99 6.5.15
3212QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3213 SourceLocation QuestionLoc) {
Sebastian Redlbd261962009-04-16 17:51:27 +00003214 // C++ is sufficiently different to merit its own checker.
3215 if (getLangOptions().CPlusPlus)
3216 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3217
Chris Lattnere2897262009-02-18 04:28:32 +00003218 UsualUnaryConversions(Cond);
3219 UsualUnaryConversions(LHS);
3220 UsualUnaryConversions(RHS);
3221 QualType CondTy = Cond->getType();
3222 QualType LHSTy = LHS->getType();
3223 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003224
3225 // first, check the condition.
Sebastian Redlbd261962009-04-16 17:51:27 +00003226 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3227 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3228 << CondTy;
3229 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003230 }
Mike Stump9afab102009-02-19 03:04:26 +00003231
Chris Lattner992ae932008-01-06 22:42:25 +00003232 // Now check the two expressions.
Nate Begemane85f43d2009-08-10 23:49:36 +00003233 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3234 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003235
Chris Lattner992ae932008-01-06 22:42:25 +00003236 // If both operands have arithmetic type, do the usual arithmetic conversions
3237 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00003238 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3239 UsualArithmeticConversions(LHS, RHS);
3240 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003241 }
Mike Stump9afab102009-02-19 03:04:26 +00003242
Chris Lattner992ae932008-01-06 22:42:25 +00003243 // If both operands are the same structure or union type, the result is that
3244 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003245 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3246 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner98a425c2007-11-26 01:40:58 +00003247 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003248 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00003249 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00003250 return LHSTy.getUnqualifiedType();
Eli Friedman2b128322009-03-23 00:24:07 +00003251 // FIXME: Type of conditional expression must be complete in C mode.
Chris Lattner4b009652007-07-25 00:24:17 +00003252 }
Mike Stump9afab102009-02-19 03:04:26 +00003253
Chris Lattner992ae932008-01-06 22:42:25 +00003254 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00003255 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00003256 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3257 if (!LHSTy->isVoidType())
3258 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3259 << RHS->getSourceRange();
3260 if (!RHSTy->isVoidType())
3261 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3262 << LHS->getSourceRange();
3263 ImpCastExprToType(LHS, Context.VoidTy);
3264 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00003265 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00003266 }
Steve Naroff12ebf272008-01-08 01:11:38 +00003267 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3268 // the type of the other operand."
Steve Naroff79ae19a2009-07-14 18:25:06 +00003269 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003270 RHS->isNullPointerConstant(Context)) {
3271 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
3272 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003273 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00003274 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003275 LHS->isNullPointerConstant(Context)) {
3276 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
3277 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003278 }
David Chisnall44663db2009-08-17 16:35:33 +00003279 // Handle things like Class and struct objc_class*. Here we case the result
3280 // to the pseudo-builtin, because that will be implicitly cast back to the
3281 // redefinition type if an attempt is made to access its fields.
3282 if (LHSTy->isObjCClassType() &&
3283 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3284 ImpCastExprToType(RHS, LHSTy);
3285 return LHSTy;
3286 }
3287 if (RHSTy->isObjCClassType() &&
3288 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3289 ImpCastExprToType(LHS, RHSTy);
3290 return RHSTy;
3291 }
3292 // And the same for struct objc_object* / id
3293 if (LHSTy->isObjCIdType() &&
3294 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3295 ImpCastExprToType(RHS, LHSTy);
3296 return LHSTy;
3297 }
3298 if (RHSTy->isObjCIdType() &&
3299 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3300 ImpCastExprToType(LHS, RHSTy);
3301 return RHSTy;
3302 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003303 // Handle block pointer types.
3304 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3305 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3306 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3307 QualType destType = Context.getPointerType(Context.VoidTy);
3308 ImpCastExprToType(LHS, destType);
3309 ImpCastExprToType(RHS, destType);
3310 return destType;
3311 }
3312 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3313 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3314 return QualType();
Mike Stumpe97a8542009-05-07 03:14:14 +00003315 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003316 // We have 2 block pointer types.
3317 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3318 // Two identical block pointer types are always compatible.
Mike Stumpe97a8542009-05-07 03:14:14 +00003319 return LHSTy;
3320 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003321 // The block pointer types aren't identical, continue checking.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003322 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3323 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003324
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003325 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3326 rhptee.getUnqualifiedType())) {
Mike Stumpe97a8542009-05-07 03:14:14 +00003327 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3328 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3329 // In this situation, we assume void* type. No especially good
3330 // reason, but this is what gcc does, and we do have to pick
3331 // to get a consistent AST.
3332 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3333 ImpCastExprToType(LHS, incompatTy);
3334 ImpCastExprToType(RHS, incompatTy);
3335 return incompatTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003336 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003337 // The block pointer types are compatible.
3338 ImpCastExprToType(LHS, LHSTy);
3339 ImpCastExprToType(RHS, LHSTy);
Steve Naroff6ba22682009-04-08 17:05:15 +00003340 return LHSTy;
3341 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003342 // Check constraints for Objective-C object pointers types.
Steve Naroff329ec222009-07-10 23:34:53 +00003343 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003344
3345 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3346 // Two identical object pointer types are always compatible.
3347 return LHSTy;
3348 }
Steve Naroff329ec222009-07-10 23:34:53 +00003349 const ObjCObjectPointerType *LHSOPT = LHSTy->getAsObjCObjectPointerType();
3350 const ObjCObjectPointerType *RHSOPT = RHSTy->getAsObjCObjectPointerType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003351 QualType compositeType = LHSTy;
3352
3353 // If both operands are interfaces and either operand can be
3354 // assigned to the other, use that type as the composite
3355 // type. This allows
3356 // xxx ? (A*) a : (B*) b
3357 // where B is a subclass of A.
3358 //
3359 // Additionally, as for assignment, if either type is 'id'
3360 // allow silent coercion. Finally, if the types are
3361 // incompatible then make sure to use 'id' as the composite
3362 // type so the result is acceptable for sending messages to.
3363
3364 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3365 // It could return the composite type.
Steve Naroff329ec222009-07-10 23:34:53 +00003366 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003367 compositeType = LHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003368 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003369 compositeType = RHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003370 } else if ((LHSTy->isObjCQualifiedIdType() ||
3371 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff99eb86b2009-07-23 01:01:38 +00003372 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Steve Naroff329ec222009-07-10 23:34:53 +00003373 // Need to handle "id<xx>" explicitly.
3374 // GCC allows qualified id and any Objective-C type to devolve to
3375 // id. Currently localizing to here until clear this should be
3376 // part of ObjCQualifiedIdTypesAreCompatible.
3377 compositeType = Context.getObjCIdType();
3378 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003379 compositeType = Context.getObjCIdType();
3380 } else {
3381 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3382 << LHSTy << RHSTy
3383 << LHS->getSourceRange() << RHS->getSourceRange();
3384 QualType incompatTy = Context.getObjCIdType();
3385 ImpCastExprToType(LHS, incompatTy);
3386 ImpCastExprToType(RHS, incompatTy);
3387 return incompatTy;
3388 }
3389 // The object pointer types are compatible.
3390 ImpCastExprToType(LHS, compositeType);
3391 ImpCastExprToType(RHS, compositeType);
3392 return compositeType;
3393 }
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003394 // Check Objective-C object pointer types and 'void *'
3395 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003396 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003397 QualType rhptee = RHSTy->getAsObjCObjectPointerType()->getPointeeType();
3398 QualType destPointee = lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3399 QualType destType = Context.getPointerType(destPointee);
3400 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3401 ImpCastExprToType(RHS, destType); // promote to void*
3402 return destType;
3403 }
3404 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
3405 QualType lhptee = LHSTy->getAsObjCObjectPointerType()->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003406 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003407 QualType destPointee = rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3408 QualType destType = Context.getPointerType(destPointee);
3409 ImpCastExprToType(RHS, destType); // add qualifiers if necessary
3410 ImpCastExprToType(LHS, destType); // promote to void*
3411 return destType;
3412 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003413 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3414 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3415 // get the "pointed to" types
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003416 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3417 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003418
3419 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3420 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3421 // Figure out necessary qualifiers (C99 6.5.15p6)
3422 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3423 QualType destType = Context.getPointerType(destPointee);
3424 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3425 ImpCastExprToType(RHS, destType); // promote to void*
3426 return destType;
3427 }
3428 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3429 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3430 QualType destType = Context.getPointerType(destPointee);
3431 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3432 ImpCastExprToType(RHS, destType); // promote to void*
3433 return destType;
3434 }
3435
3436 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3437 // Two identical pointer types are always compatible.
3438 return LHSTy;
3439 }
3440 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3441 rhptee.getUnqualifiedType())) {
3442 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3443 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3444 // In this situation, we assume void* type. No especially good
3445 // reason, but this is what gcc does, and we do have to pick
3446 // to get a consistent AST.
3447 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3448 ImpCastExprToType(LHS, incompatTy);
3449 ImpCastExprToType(RHS, incompatTy);
3450 return incompatTy;
3451 }
3452 // The pointer types are compatible.
3453 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3454 // differently qualified versions of compatible types, the result type is
3455 // a pointer to an appropriately qualified version of the *composite*
3456 // type.
3457 // FIXME: Need to calculate the composite type.
3458 // FIXME: Need to add qualifiers
3459 ImpCastExprToType(LHS, LHSTy);
3460 ImpCastExprToType(RHS, LHSTy);
3461 return LHSTy;
3462 }
3463
3464 // GCC compatibility: soften pointer/integer mismatch.
3465 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3466 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3467 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3468 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3469 return RHSTy;
3470 }
3471 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3472 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3473 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3474 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3475 return LHSTy;
3476 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00003477
Chris Lattner992ae932008-01-06 22:42:25 +00003478 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00003479 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3480 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003481 return QualType();
3482}
3483
Steve Naroff87d58b42007-09-16 03:34:24 +00003484/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00003485/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003486Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3487 SourceLocation ColonLoc,
3488 ExprArg Cond, ExprArg LHS,
3489 ExprArg RHS) {
3490 Expr *CondExpr = (Expr *) Cond.get();
3491 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00003492
3493 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3494 // was the condition.
3495 bool isLHSNull = LHSExpr == 0;
3496 if (isLHSNull)
3497 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003498
3499 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00003500 RHSExpr, QuestionLoc);
3501 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003502 return ExprError();
3503
3504 Cond.release();
3505 LHS.release();
3506 RHS.release();
Mike Stump9afab102009-02-19 03:04:26 +00003507 return Owned(new (Context) ConditionalOperator(CondExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00003508 isLHSNull ? 0 : LHSExpr,
3509 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00003510}
3511
Chris Lattner4b009652007-07-25 00:24:17 +00003512// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00003513// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00003514// routine is it effectively iqnores the qualifiers on the top level pointee.
3515// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3516// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00003517Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003518Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3519 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003520
David Chisnall44663db2009-08-17 16:35:33 +00003521 if ((lhsType->isObjCClassType() &&
3522 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3523 (rhsType->isObjCClassType() &&
3524 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3525 return Compatible;
3526 }
3527
Chris Lattner4b009652007-07-25 00:24:17 +00003528 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003529 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3530 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003531
Chris Lattner4b009652007-07-25 00:24:17 +00003532 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003533 lhptee = Context.getCanonicalType(lhptee);
3534 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00003535
Chris Lattner005ed752008-01-04 18:04:52 +00003536 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003537
3538 // C99 6.5.16.1p1: This following citation is common to constraints
3539 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3540 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00003541 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003542 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00003543 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00003544
Mike Stump9afab102009-02-19 03:04:26 +00003545 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3546 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00003547 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00003548 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003549 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003550 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00003551
Chris Lattner4ca3d772008-01-03 22:56:36 +00003552 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003553 assert(rhptee->isFunctionType());
3554 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003555 }
Mike Stump9afab102009-02-19 03:04:26 +00003556
Chris Lattner4ca3d772008-01-03 22:56:36 +00003557 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003558 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003559 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003560
3561 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003562 assert(lhptee->isFunctionType());
3563 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003564 }
Mike Stump9afab102009-02-19 03:04:26 +00003565 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00003566 // unqualified versions of compatible types, ...
Eli Friedman6ca28cb2009-03-22 23:59:44 +00003567 lhptee = lhptee.getUnqualifiedType();
3568 rhptee = rhptee.getUnqualifiedType();
3569 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3570 // Check if the pointee types are compatible ignoring the sign.
3571 // We explicitly check for char so that we catch "char" vs
3572 // "unsigned char" on systems where "char" is unsigned.
3573 if (lhptee->isCharType()) {
3574 lhptee = Context.UnsignedCharTy;
3575 } else if (lhptee->isSignedIntegerType()) {
3576 lhptee = Context.getCorrespondingUnsignedType(lhptee);
3577 }
3578 if (rhptee->isCharType()) {
3579 rhptee = Context.UnsignedCharTy;
3580 } else if (rhptee->isSignedIntegerType()) {
3581 rhptee = Context.getCorrespondingUnsignedType(rhptee);
3582 }
3583 if (lhptee == rhptee) {
3584 // Types are compatible ignoring the sign. Qualifier incompatibility
3585 // takes priority over sign incompatibility because the sign
3586 // warning can be disabled.
3587 if (ConvTy != Compatible)
3588 return ConvTy;
3589 return IncompatiblePointerSign;
3590 }
3591 // General pointer incompatibility takes priority over qualifiers.
3592 return IncompatiblePointer;
3593 }
Chris Lattner005ed752008-01-04 18:04:52 +00003594 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003595}
3596
Steve Naroff3454b6c2008-09-04 15:10:53 +00003597/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3598/// block pointer types are compatible or whether a block and normal pointer
3599/// are compatible. It is more restrict than comparing two function pointer
3600// types.
Mike Stump9afab102009-02-19 03:04:26 +00003601Sema::AssignConvertType
3602Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00003603 QualType rhsType) {
3604 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003605
Steve Naroff3454b6c2008-09-04 15:10:53 +00003606 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003607 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3608 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003609
Steve Naroff3454b6c2008-09-04 15:10:53 +00003610 // make sure we operate on the canonical type
3611 lhptee = Context.getCanonicalType(lhptee);
3612 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00003613
Steve Naroff3454b6c2008-09-04 15:10:53 +00003614 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003615
Steve Naroff3454b6c2008-09-04 15:10:53 +00003616 // For blocks we enforce that qualifiers are identical.
3617 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3618 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00003619
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00003620 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00003621 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003622 return ConvTy;
3623}
3624
Mike Stump9afab102009-02-19 03:04:26 +00003625/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3626/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00003627/// pointers. Here are some objectionable examples that GCC considers warnings:
3628///
3629/// int a, *pint;
3630/// short *pshort;
3631/// struct foo *pfoo;
3632///
3633/// pint = pshort; // warning: assignment from incompatible pointer type
3634/// a = pint; // warning: assignment makes integer from pointer without a cast
3635/// pint = a; // warning: assignment makes pointer from integer without a cast
3636/// pint = pfoo; // warning: assignment from incompatible pointer type
3637///
3638/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00003639/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00003640///
Chris Lattner005ed752008-01-04 18:04:52 +00003641Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003642Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00003643 // Get canonical types. We're not formatting these types, just comparing
3644 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003645 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3646 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00003647
3648 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00003649 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00003650
David Chisnall44663db2009-08-17 16:35:33 +00003651 if ((lhsType->isObjCClassType() &&
3652 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3653 (rhsType->isObjCClassType() &&
3654 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3655 return Compatible;
3656 }
3657
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003658 // If the left-hand side is a reference type, then we are in a
3659 // (rare!) case where we've allowed the use of references in C,
3660 // e.g., as a parameter type in a built-in function. In this case,
3661 // just make sure that the type referenced is compatible with the
3662 // right-hand side type. The caller is responsible for adjusting
3663 // lhsType so that the resulting expression does not have reference
3664 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003665 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003666 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00003667 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003668 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003669 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003670 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3671 // to the same ExtVector type.
3672 if (lhsType->isExtVectorType()) {
3673 if (rhsType->isExtVectorType())
3674 return lhsType == rhsType ? Compatible : Incompatible;
3675 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3676 return Compatible;
3677 }
3678
Nate Begemanc5f0f652008-07-14 18:02:46 +00003679 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003680 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00003681 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00003682 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003683 if (getLangOptions().LaxVectorConversions &&
3684 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003685 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00003686 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003687 }
3688 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00003689 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003690
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003691 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00003692 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003693
Chris Lattner390564e2008-04-07 06:49:41 +00003694 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003695 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003696 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003697
Chris Lattner390564e2008-04-07 06:49:41 +00003698 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003699 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003700
Steve Naroff8194a542009-07-20 17:56:53 +00003701 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003702 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003703 if (lhsType->isVoidPointerType()) // an exception to the rule.
3704 return Compatible;
3705 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003706 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003707 if (rhsType->getAs<BlockPointerType>()) {
3708 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003709 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00003710
3711 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003712 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003713 return Compatible;
3714 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003715 return Incompatible;
3716 }
3717
3718 if (isa<BlockPointerType>(lhsType)) {
3719 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00003720 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00003721
Steve Naroffa982c712008-09-29 18:10:17 +00003722 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003723 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003724 return Compatible;
3725
Steve Naroff3454b6c2008-09-04 15:10:53 +00003726 if (rhsType->isBlockPointerType())
3727 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003728
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003729 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff3454b6c2008-09-04 15:10:53 +00003730 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003731 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003732 }
Chris Lattner1853da22008-01-04 23:18:45 +00003733 return Incompatible;
3734 }
3735
Steve Naroff329ec222009-07-10 23:34:53 +00003736 if (isa<ObjCObjectPointerType>(lhsType)) {
3737 if (rhsType->isIntegerType())
3738 return IntToPointer;
Steve Naroff8194a542009-07-20 17:56:53 +00003739
3740 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003741 if (isa<PointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003742 if (rhsType->isVoidPointerType()) // an exception to the rule.
3743 return Compatible;
3744 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003745 }
3746 if (rhsType->isObjCObjectPointerType()) {
Steve Naroff7bffd372009-07-15 18:40:39 +00003747 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3748 return Compatible;
Steve Naroff8194a542009-07-20 17:56:53 +00003749 if (Context.typesAreCompatible(lhsType, rhsType))
3750 return Compatible;
Steve Naroff99eb86b2009-07-23 01:01:38 +00003751 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3752 return IncompatibleObjCQualifiedId;
Steve Naroff8194a542009-07-20 17:56:53 +00003753 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003754 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003755 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff329ec222009-07-10 23:34:53 +00003756 if (RHSPT->getPointeeType()->isVoidType())
3757 return Compatible;
3758 }
3759 // Treat block pointers as objects.
3760 if (rhsType->isBlockPointerType())
3761 return Compatible;
3762 return Incompatible;
3763 }
Chris Lattner390564e2008-04-07 06:49:41 +00003764 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003765 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00003766 if (lhsType == Context.BoolTy)
3767 return Compatible;
3768
3769 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003770 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00003771
Mike Stump9afab102009-02-19 03:04:26 +00003772 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003773 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003774
3775 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003776 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003777 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003778 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003779 }
Steve Naroff329ec222009-07-10 23:34:53 +00003780 if (isa<ObjCObjectPointerType>(rhsType)) {
3781 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3782 if (lhsType == Context.BoolTy)
3783 return Compatible;
3784
3785 if (lhsType->isIntegerType())
3786 return PointerToInt;
3787
Steve Naroff8194a542009-07-20 17:56:53 +00003788 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003789 if (isa<PointerType>(lhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003790 if (lhsType->isVoidPointerType()) // an exception to the rule.
3791 return Compatible;
3792 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003793 }
3794 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003795 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff329ec222009-07-10 23:34:53 +00003796 return Compatible;
3797 return Incompatible;
3798 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003799
Chris Lattner1853da22008-01-04 23:18:45 +00003800 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00003801 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003802 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00003803 }
3804 return Incompatible;
3805}
3806
Douglas Gregor144b06c2009-04-29 22:16:16 +00003807/// \brief Constructs a transparent union from an expression that is
3808/// used to initialize the transparent union.
3809static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3810 QualType UnionType, FieldDecl *Field) {
3811 // Build an initializer list that designates the appropriate member
3812 // of the transparent union.
3813 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3814 &E, 1,
3815 SourceLocation());
3816 Initializer->setType(UnionType);
3817 Initializer->setInitializedFieldInUnion(Field);
3818
3819 // Build a compound literal constructing a value of the transparent
3820 // union type from this initializer list.
3821 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3822 false);
3823}
3824
3825Sema::AssignConvertType
3826Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3827 QualType FromType = rExpr->getType();
3828
3829 // If the ArgType is a Union type, we want to handle a potential
3830 // transparent_union GCC extension.
3831 const RecordType *UT = ArgType->getAsUnionType();
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003832 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor144b06c2009-04-29 22:16:16 +00003833 return Incompatible;
3834
3835 // The field to initialize within the transparent union.
3836 RecordDecl *UD = UT->getDecl();
3837 FieldDecl *InitField = 0;
3838 // It's compatible if the expression matches any of the fields.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003839 for (RecordDecl::field_iterator it = UD->field_begin(),
3840 itend = UD->field_end();
Douglas Gregor144b06c2009-04-29 22:16:16 +00003841 it != itend; ++it) {
3842 if (it->getType()->isPointerType()) {
3843 // If the transparent union contains a pointer type, we allow:
3844 // 1) void pointer
3845 // 2) null pointer constant
3846 if (FromType->isPointerType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003847 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor144b06c2009-04-29 22:16:16 +00003848 ImpCastExprToType(rExpr, it->getType());
3849 InitField = *it;
3850 break;
3851 }
3852
3853 if (rExpr->isNullPointerConstant(Context)) {
3854 ImpCastExprToType(rExpr, it->getType());
3855 InitField = *it;
3856 break;
3857 }
3858 }
3859
3860 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3861 == Compatible) {
3862 InitField = *it;
3863 break;
3864 }
3865 }
3866
3867 if (!InitField)
3868 return Incompatible;
3869
3870 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3871 return Compatible;
3872}
3873
Chris Lattner005ed752008-01-04 18:04:52 +00003874Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003875Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003876 if (getLangOptions().CPlusPlus) {
3877 if (!lhsType->isRecordType()) {
3878 // C++ 5.17p3: If the left operand is not of class type, the
3879 // expression is implicitly converted (C++ 4) to the
3880 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00003881 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3882 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003883 return Incompatible;
Chris Lattner79e9a422009-04-12 09:02:39 +00003884 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003885 }
3886
3887 // FIXME: Currently, we fall through and treat C++ classes like C
3888 // structures.
3889 }
3890
Steve Naroffcdee22d2007-11-27 17:58:44 +00003891 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3892 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00003893 if ((lhsType->isPointerType() ||
Steve Naroff329ec222009-07-10 23:34:53 +00003894 lhsType->isObjCObjectPointerType() ||
Mike Stump9afab102009-02-19 03:04:26 +00003895 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00003896 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003897 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00003898 return Compatible;
3899 }
Mike Stump9afab102009-02-19 03:04:26 +00003900
Chris Lattner5f505bf2007-10-16 02:55:40 +00003901 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00003902 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00003903 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00003904 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00003905 //
Mike Stump9afab102009-02-19 03:04:26 +00003906 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00003907 if (!lhsType->isReferenceType())
3908 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00003909
Chris Lattner005ed752008-01-04 18:04:52 +00003910 Sema::AssignConvertType result =
3911 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00003912
Steve Naroff0f32f432007-08-24 22:33:52 +00003913 // C99 6.5.16.1p2: The value of the right operand is converted to the
3914 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003915 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3916 // so that we can use references in built-in functions even in C.
3917 // The getNonReferenceType() call makes sure that the resulting expression
3918 // does not have reference type.
Douglas Gregor144b06c2009-04-29 22:16:16 +00003919 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003920 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00003921 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00003922}
3923
Chris Lattner1eafdea2008-11-18 01:30:42 +00003924QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003925 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003926 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003927 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00003928 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003929}
3930
Mike Stump9afab102009-02-19 03:04:26 +00003931inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00003932 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00003933 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00003934 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003935 QualType lhsType =
3936 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3937 QualType rhsType =
3938 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00003939
Nate Begemanc5f0f652008-07-14 18:02:46 +00003940 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00003941 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00003942 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00003943
Nate Begemanc5f0f652008-07-14 18:02:46 +00003944 // Handle the case of a vector & extvector type of the same size and element
3945 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00003946 if (getLangOptions().LaxVectorConversions) {
3947 // FIXME: Should we warn here?
3948 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003949 if (const VectorType *RV = rhsType->getAsVectorType())
3950 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00003951 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003952 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00003953 }
3954 }
3955 }
Mike Stump9afab102009-02-19 03:04:26 +00003956
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003957 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
3958 // swap back (so that we don't reverse the inputs to a subtract, for instance.
3959 bool swapped = false;
3960 if (rhsType->isExtVectorType()) {
3961 swapped = true;
3962 std::swap(rex, lex);
3963 std::swap(rhsType, lhsType);
3964 }
3965
Nate Begemanf1695892009-06-28 19:12:57 +00003966 // Handle the case of an ext vector and scalar.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003967 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) {
3968 QualType EltTy = LV->getElementType();
3969 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
3970 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00003971 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003972 if (swapped) std::swap(rex, lex);
3973 return lhsType;
3974 }
3975 }
3976 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
3977 rhsType->isRealFloatingType()) {
3978 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00003979 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003980 if (swapped) std::swap(rex, lex);
3981 return lhsType;
3982 }
Nate Begemanec2d1062007-12-30 02:59:45 +00003983 }
3984 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003985
Nate Begemanf1695892009-06-28 19:12:57 +00003986 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner70b93d82008-11-18 22:52:51 +00003987 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003988 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003989 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003990 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00003991}
3992
Chris Lattner4b009652007-07-25 00:24:17 +00003993inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003994 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003995{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00003996 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003997 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003998
Steve Naroff8f708362007-08-24 19:07:16 +00003999 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004000
Chris Lattner4b009652007-07-25 00:24:17 +00004001 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00004002 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004003 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004004}
4005
4006inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004007 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004008{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00004009 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4010 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4011 return CheckVectorOperands(Loc, lex, rex);
4012 return InvalidOperands(Loc, lex, rex);
4013 }
Chris Lattner4b009652007-07-25 00:24:17 +00004014
Steve Naroff8f708362007-08-24 19:07:16 +00004015 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004016
Chris Lattner4b009652007-07-25 00:24:17 +00004017 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00004018 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004019 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004020}
4021
4022inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Eli Friedman3cd92882009-03-28 01:22:36 +00004023 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
Chris Lattner4b009652007-07-25 00:24:17 +00004024{
Eli Friedman3cd92882009-03-28 01:22:36 +00004025 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4026 QualType compType = CheckVectorOperands(Loc, lex, rex);
4027 if (CompLHSTy) *CompLHSTy = compType;
4028 return compType;
4029 }
Chris Lattner4b009652007-07-25 00:24:17 +00004030
Eli Friedman3cd92882009-03-28 01:22:36 +00004031 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004032
Chris Lattner4b009652007-07-25 00:24:17 +00004033 // handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00004034 if (lex->getType()->isArithmeticType() &&
4035 rex->getType()->isArithmeticType()) {
4036 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00004037 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00004038 }
Chris Lattner4b009652007-07-25 00:24:17 +00004039
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004040 // Put any potential pointer into PExp
4041 Expr* PExp = lex, *IExp = rex;
Steve Naroff79ae19a2009-07-14 18:25:06 +00004042 if (IExp->getType()->isAnyPointerType())
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004043 std::swap(PExp, IExp);
4044
Steve Naroff79ae19a2009-07-14 18:25:06 +00004045 if (PExp->getType()->isAnyPointerType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00004046
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004047 if (IExp->getType()->isIntegerType()) {
Steve Naroff18b38122009-07-13 21:20:41 +00004048 QualType PointeeTy = PExp->getType()->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00004049
Chris Lattner184f92d2009-04-24 23:50:08 +00004050 // Check for arithmetic on pointers to incomplete types.
4051 if (PointeeTy->isVoidType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00004052 if (getLangOptions().CPlusPlus) {
4053 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner8ba580c2008-11-19 05:08:23 +00004054 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004055 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004056 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004057
4058 // GNU extension: arithmetic on pointer to void
4059 Diag(Loc, diag::ext_gnu_void_ptr)
4060 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner184f92d2009-04-24 23:50:08 +00004061 } else if (PointeeTy->isFunctionType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00004062 if (getLangOptions().CPlusPlus) {
4063 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4064 << lex->getType() << lex->getSourceRange();
4065 return QualType();
4066 }
4067
4068 // GNU extension: arithmetic on pointer to function
4069 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4070 << lex->getType() << lex->getSourceRange();
Steve Naroff3fc227b2009-07-13 21:32:29 +00004071 } else {
Steve Naroff18b38122009-07-13 21:20:41 +00004072 // Check if we require a complete type.
4073 if (((PExp->getType()->isPointerType() &&
Steve Naroff3fc227b2009-07-13 21:32:29 +00004074 !PExp->getType()->isDependentType()) ||
Steve Naroff18b38122009-07-13 21:20:41 +00004075 PExp->getType()->isObjCObjectPointerType()) &&
4076 RequireCompleteType(Loc, PointeeTy,
4077 diag::err_typecheck_arithmetic_incomplete_type,
4078 PExp->getSourceRange(), SourceRange(),
4079 PExp->getType()))
4080 return QualType();
4081 }
Chris Lattner184f92d2009-04-24 23:50:08 +00004082 // Diagnose bad cases where we step over interface counts.
4083 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4084 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4085 << PointeeTy << PExp->getSourceRange();
4086 return QualType();
4087 }
4088
Eli Friedman3cd92882009-03-28 01:22:36 +00004089 if (CompLHSTy) {
4090 QualType LHSTy = lex->getType();
4091 if (LHSTy->isPromotableIntegerType())
4092 LHSTy = Context.IntTy;
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004093 else {
4094 QualType T = isPromotableBitField(lex, Context);
4095 if (!T.isNull())
4096 LHSTy = T;
4097 }
4098
Eli Friedman3cd92882009-03-28 01:22:36 +00004099 *CompLHSTy = LHSTy;
4100 }
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004101 return PExp->getType();
4102 }
4103 }
4104
Chris Lattner1eafdea2008-11-18 01:30:42 +00004105 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004106}
4107
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004108// C99 6.5.6
4109QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman3cd92882009-03-28 01:22:36 +00004110 SourceLocation Loc, QualType* CompLHSTy) {
4111 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4112 QualType compType = CheckVectorOperands(Loc, lex, rex);
4113 if (CompLHSTy) *CompLHSTy = compType;
4114 return compType;
4115 }
Mike Stump9afab102009-02-19 03:04:26 +00004116
Eli Friedman3cd92882009-03-28 01:22:36 +00004117 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump9afab102009-02-19 03:04:26 +00004118
Chris Lattnerf6da2912007-12-09 21:53:25 +00004119 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00004120
Chris Lattnerf6da2912007-12-09 21:53:25 +00004121 // Handle the common case first (both operands are arithmetic).
Mike Stumpea3d74e2009-05-07 18:43:07 +00004122 if (lex->getType()->isArithmeticType()
4123 && rex->getType()->isArithmeticType()) {
Eli Friedman3cd92882009-03-28 01:22:36 +00004124 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00004125 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00004126 }
Steve Naroff329ec222009-07-10 23:34:53 +00004127
Chris Lattnerf6da2912007-12-09 21:53:25 +00004128 // Either ptr - int or ptr - ptr.
Steve Naroff79ae19a2009-07-14 18:25:06 +00004129 if (lex->getType()->isAnyPointerType()) {
Steve Naroff7982a642009-07-13 17:19:15 +00004130 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004131
Douglas Gregor05e28f62009-03-24 19:52:54 +00004132 // The LHS must be an completely-defined object type.
Douglas Gregorb3193242009-01-23 00:36:41 +00004133
Douglas Gregor05e28f62009-03-24 19:52:54 +00004134 bool ComplainAboutVoid = false;
4135 Expr *ComplainAboutFunc = 0;
4136 if (lpointee->isVoidType()) {
4137 if (getLangOptions().CPlusPlus) {
4138 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4139 << lex->getSourceRange() << rex->getSourceRange();
4140 return QualType();
4141 }
4142
4143 // GNU C extension: arithmetic on pointer to void
4144 ComplainAboutVoid = true;
4145 } else if (lpointee->isFunctionType()) {
4146 if (getLangOptions().CPlusPlus) {
4147 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004148 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004149 return QualType();
4150 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004151
4152 // GNU C extension: arithmetic on pointer to function
4153 ComplainAboutFunc = lex;
4154 } else if (!lpointee->isDependentType() &&
4155 RequireCompleteType(Loc, lpointee,
4156 diag::err_typecheck_sub_ptr_object,
4157 lex->getSourceRange(),
4158 SourceRange(),
4159 lex->getType()))
4160 return QualType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004161
Chris Lattner184f92d2009-04-24 23:50:08 +00004162 // Diagnose bad cases where we step over interface counts.
4163 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4164 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4165 << lpointee << lex->getSourceRange();
4166 return QualType();
4167 }
4168
Chris Lattnerf6da2912007-12-09 21:53:25 +00004169 // The result type of a pointer-int computation is the pointer type.
Douglas Gregor05e28f62009-03-24 19:52:54 +00004170 if (rex->getType()->isIntegerType()) {
4171 if (ComplainAboutVoid)
4172 Diag(Loc, diag::ext_gnu_void_ptr)
4173 << lex->getSourceRange() << rex->getSourceRange();
4174 if (ComplainAboutFunc)
4175 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4176 << ComplainAboutFunc->getType()
4177 << ComplainAboutFunc->getSourceRange();
4178
Eli Friedman3cd92882009-03-28 01:22:36 +00004179 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004180 return lex->getType();
Douglas Gregor05e28f62009-03-24 19:52:54 +00004181 }
Mike Stump9afab102009-02-19 03:04:26 +00004182
Chris Lattnerf6da2912007-12-09 21:53:25 +00004183 // Handle pointer-pointer subtractions.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004184 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman50727042008-02-08 01:19:44 +00004185 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004186
Douglas Gregor05e28f62009-03-24 19:52:54 +00004187 // RHS must be a completely-type object type.
4188 // Handle the GNU void* extension.
4189 if (rpointee->isVoidType()) {
4190 if (getLangOptions().CPlusPlus) {
4191 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4192 << lex->getSourceRange() << rex->getSourceRange();
4193 return QualType();
4194 }
Mike Stump9afab102009-02-19 03:04:26 +00004195
Douglas Gregor05e28f62009-03-24 19:52:54 +00004196 ComplainAboutVoid = true;
4197 } else if (rpointee->isFunctionType()) {
4198 if (getLangOptions().CPlusPlus) {
4199 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004200 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004201 return QualType();
4202 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004203
4204 // GNU extension: arithmetic on pointer to function
4205 if (!ComplainAboutFunc)
4206 ComplainAboutFunc = rex;
4207 } else if (!rpointee->isDependentType() &&
4208 RequireCompleteType(Loc, rpointee,
4209 diag::err_typecheck_sub_ptr_object,
4210 rex->getSourceRange(),
4211 SourceRange(),
4212 rex->getType()))
4213 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004214
Eli Friedman143ddc92009-05-16 13:54:38 +00004215 if (getLangOptions().CPlusPlus) {
4216 // Pointee types must be the same: C++ [expr.add]
4217 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4218 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4219 << lex->getType() << rex->getType()
4220 << lex->getSourceRange() << rex->getSourceRange();
4221 return QualType();
4222 }
4223 } else {
4224 // Pointee types must be compatible C99 6.5.6p3
4225 if (!Context.typesAreCompatible(
4226 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4227 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4228 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4229 << lex->getType() << rex->getType()
4230 << lex->getSourceRange() << rex->getSourceRange();
4231 return QualType();
4232 }
Chris Lattnerf6da2912007-12-09 21:53:25 +00004233 }
Mike Stump9afab102009-02-19 03:04:26 +00004234
Douglas Gregor05e28f62009-03-24 19:52:54 +00004235 if (ComplainAboutVoid)
4236 Diag(Loc, diag::ext_gnu_void_ptr)
4237 << lex->getSourceRange() << rex->getSourceRange();
4238 if (ComplainAboutFunc)
4239 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4240 << ComplainAboutFunc->getType()
4241 << ComplainAboutFunc->getSourceRange();
Eli Friedman3cd92882009-03-28 01:22:36 +00004242
4243 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004244 return Context.getPointerDiffType();
4245 }
4246 }
Mike Stump9afab102009-02-19 03:04:26 +00004247
Chris Lattner1eafdea2008-11-18 01:30:42 +00004248 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004249}
4250
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004251// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00004252QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004253 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00004254 // C99 6.5.7p2: Each of the operands shall have integer type.
4255 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004256 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00004257
Chris Lattner2c8bff72007-12-12 05:47:28 +00004258 // Shifts don't perform usual arithmetic conversions, they just do integer
4259 // promotions on each operand. C99 6.5.7p3
Eli Friedman3cd92882009-03-28 01:22:36 +00004260 QualType LHSTy;
4261 if (lex->getType()->isPromotableIntegerType())
4262 LHSTy = Context.IntTy;
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004263 else {
4264 LHSTy = isPromotableBitField(lex, Context);
4265 if (LHSTy.isNull())
4266 LHSTy = lex->getType();
4267 }
Chris Lattnerbb19bc42007-12-13 07:28:16 +00004268 if (!isCompAssign)
Eli Friedman3cd92882009-03-28 01:22:36 +00004269 ImpCastExprToType(lex, LHSTy);
4270
Chris Lattner2c8bff72007-12-12 05:47:28 +00004271 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004272
Ryan Flynnf109fff2009-08-07 16:20:20 +00004273 // Sanity-check shift operands
4274 llvm::APSInt Right;
4275 // Check right/shifter operand
4276 if (rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynna5e76932009-08-08 19:18:23 +00004277 if (Right.isNegative())
Ryan Flynnf109fff2009-08-07 16:20:20 +00004278 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4279 else {
4280 llvm::APInt LeftBits(Right.getBitWidth(),
4281 Context.getTypeSize(lex->getType()));
4282 if (Right.uge(LeftBits))
4283 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4284 }
4285 }
4286
Chris Lattner2c8bff72007-12-12 05:47:28 +00004287 // "The type of the result is that of the promoted left operand."
Eli Friedman3cd92882009-03-28 01:22:36 +00004288 return LHSTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004289}
4290
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004291// C99 6.5.8, C++ [expr.rel]
Chris Lattner1eafdea2008-11-18 01:30:42 +00004292QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor1f12c352009-04-06 18:45:53 +00004293 unsigned OpaqueOpc, bool isRelational) {
4294 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4295
Nate Begemanc5f0f652008-07-14 18:02:46 +00004296 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004297 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00004298
Chris Lattner254f3bc2007-08-26 01:18:55 +00004299 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00004300 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4301 UsualArithmeticConversions(lex, rex);
4302 else {
4303 UsualUnaryConversions(lex);
4304 UsualUnaryConversions(rex);
4305 }
Chris Lattner4b009652007-07-25 00:24:17 +00004306 QualType lType = lex->getType();
4307 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004308
Mike Stumpea3d74e2009-05-07 18:43:07 +00004309 if (!lType->isFloatingType()
4310 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004311 // For non-floating point types, check for self-comparisons of the form
4312 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4313 // often indicate logic errors in the program.
Ted Kremenek264b5cb2009-03-20 19:57:37 +00004314 // NOTE: Don't warn about comparisons of enum constants. These can arise
4315 // from macro expansions, and are usually quite deliberate.
Chris Lattner4e479f92009-03-08 19:39:53 +00004316 Expr *LHSStripped = lex->IgnoreParens();
4317 Expr *RHSStripped = rex->IgnoreParens();
4318 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4319 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekf042dc62009-03-20 18:35:45 +00004320 if (DRL->getDecl() == DRR->getDecl() &&
4321 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump9afab102009-02-19 03:04:26 +00004322 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner4e479f92009-03-08 19:39:53 +00004323
4324 if (isa<CastExpr>(LHSStripped))
4325 LHSStripped = LHSStripped->IgnoreParenCasts();
4326 if (isa<CastExpr>(RHSStripped))
4327 RHSStripped = RHSStripped->IgnoreParenCasts();
4328
4329 // Warn about comparisons against a string constant (unless the other
4330 // operand is null), the user probably wants strcmp.
Douglas Gregor1f12c352009-04-06 18:45:53 +00004331 Expr *literalString = 0;
4332 Expr *literalStringStripped = 0;
Chris Lattner4e479f92009-03-08 19:39:53 +00004333 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00004334 !RHSStripped->isNullPointerConstant(Context)) {
4335 literalString = lex;
4336 literalStringStripped = LHSStripped;
Mike Stump90fc78e2009-08-04 21:02:39 +00004337 } else if ((isa<StringLiteral>(RHSStripped) ||
4338 isa<ObjCEncodeExpr>(RHSStripped)) &&
4339 !LHSStripped->isNullPointerConstant(Context)) {
Douglas Gregor1f12c352009-04-06 18:45:53 +00004340 literalString = rex;
4341 literalStringStripped = RHSStripped;
4342 }
4343
4344 if (literalString) {
4345 std::string resultComparison;
4346 switch (Opc) {
4347 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4348 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4349 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4350 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4351 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4352 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4353 default: assert(false && "Invalid comparison operator");
4354 }
4355 Diag(Loc, diag::warn_stringcompare)
4356 << isa<ObjCEncodeExpr>(literalStringStripped)
4357 << literalString->getSourceRange()
Douglas Gregor3faaa812009-04-01 23:51:29 +00004358 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4359 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4360 "strcmp(")
4361 << CodeModificationHint::CreateInsertion(
4362 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor1f12c352009-04-06 18:45:53 +00004363 resultComparison);
4364 }
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00004365 }
Mike Stump9afab102009-02-19 03:04:26 +00004366
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004367 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner4e479f92009-03-08 19:39:53 +00004368 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004369
Chris Lattner254f3bc2007-08-26 01:18:55 +00004370 if (isRelational) {
4371 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004372 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004373 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00004374 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00004375 if (lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004376 assert(rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004377 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00004378 }
Mike Stump9afab102009-02-19 03:04:26 +00004379
Chris Lattner254f3bc2007-08-26 01:18:55 +00004380 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004381 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004382 }
Mike Stump9afab102009-02-19 03:04:26 +00004383
Chris Lattner22be8422007-08-26 01:10:14 +00004384 bool LHSIsNull = lex->isNullPointerConstant(Context);
4385 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00004386
Chris Lattner254f3bc2007-08-26 01:18:55 +00004387 // All of the following pointer related warnings are GCC extensions, except
4388 // when handling null pointer constants. One day, we can consider making them
4389 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00004390 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00004391 QualType LCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004392 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00004393 QualType RCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004394 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00004395
Douglas Gregor4da47382009-07-06 20:14:23 +00004396 if (isRelational) {
4397 if (lType->isFunctionPointerType() || rType->isFunctionPointerType()) {
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004398 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4399 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4400 }
Douglas Gregor4da47382009-07-06 20:14:23 +00004401 if (LCanPointeeTy->isVoidType() != RCanPointeeTy->isVoidType()) {
4402 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4403 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4404 }
4405 } else {
4406 if (lType->isFunctionPointerType() != rType->isFunctionPointerType()) {
4407 if (!LHSIsNull && !RHSIsNull)
4408 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4409 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4410 }
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004411 }
Douglas Gregor4da47382009-07-06 20:14:23 +00004412
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004413 // Simple check: if the pointee types are identical, we're done.
4414 if (LCanPointeeTy == RCanPointeeTy)
4415 return ResultTy;
4416
4417 if (getLangOptions().CPlusPlus) {
4418 // C++ [expr.rel]p2:
4419 // [...] Pointer conversions (4.10) and qualification
4420 // conversions (4.4) are performed on pointer operands (or on
4421 // a pointer operand and a null pointer constant) to bring
4422 // them to their composite pointer type. [...]
4423 //
4424 // C++ [expr.eq]p2 uses the same notion for (in)equality
4425 // comparisons of pointers.
Douglas Gregorcf651d22009-05-05 04:50:50 +00004426 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004427 if (T.isNull()) {
4428 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4429 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4430 return QualType();
4431 }
4432
4433 ImpCastExprToType(lex, T);
4434 ImpCastExprToType(rex, T);
4435 return ResultTy;
4436 }
4437
Steve Naroff3b435622007-11-13 14:57:38 +00004438 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00004439 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
4440 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Steve Naroff329ec222009-07-10 23:34:53 +00004441 RCanPointeeTy.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004442 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004443 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004444 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004445 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004446 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004447 }
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004448 // C++ allows comparison of pointers with null pointer constants.
4449 if (getLangOptions().CPlusPlus) {
4450 if (lType->isPointerType() && RHSIsNull) {
4451 ImpCastExprToType(rex, lType);
4452 return ResultTy;
4453 }
4454 if (rType->isPointerType() && LHSIsNull) {
4455 ImpCastExprToType(lex, rType);
4456 return ResultTy;
4457 }
4458 // And comparison of nullptr_t with itself.
4459 if (lType->isNullPtrType() && rType->isNullPtrType())
4460 return ResultTy;
4461 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00004462 // Handle block pointer types.
Mike Stumpe97a8542009-05-07 03:14:14 +00004463 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004464 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4465 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004466
Steve Naroff3454b6c2008-09-04 15:10:53 +00004467 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00004468 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004469 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004470 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00004471 }
4472 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004473 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004474 }
Steve Narofff85d66c2008-09-28 01:11:11 +00004475 // Allow block pointers to be compared with null pointer constants.
Mike Stumpe97a8542009-05-07 03:14:14 +00004476 if (!isRelational
4477 && ((lType->isBlockPointerType() && rType->isPointerType())
4478 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Narofff85d66c2008-09-28 01:11:11 +00004479 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004480 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004481 ->getPointeeType()->isVoidType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004482 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004483 ->getPointeeType()->isVoidType())))
4484 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4485 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00004486 }
4487 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004488 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00004489 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00004490
Steve Naroff329ec222009-07-10 23:34:53 +00004491 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00004492 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004493 const PointerType *LPT = lType->getAs<PointerType>();
4494 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump9afab102009-02-19 03:04:26 +00004495 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004496 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004497 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004498 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004499
Steve Naroff030fcda2008-11-17 19:49:16 +00004500 if (!LPtrToVoid && !RPtrToVoid &&
4501 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004502 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004503 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00004504 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00004505 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004506 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00004507 }
Steve Naroff329ec222009-07-10 23:34:53 +00004508 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
4509 if (!Context.areComparableObjCPointerTypes(lType, rType)) {
4510 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4511 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4512 }
Steve Naroff936c4362008-06-03 14:04:54 +00004513 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004514 return ResultTy;
Steve Naroff936c4362008-06-03 14:04:54 +00004515 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00004516 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004517 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004518 if (isRelational)
4519 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_pointer_integer)
4520 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4521 else if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00004522 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004523 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00004524 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004525 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004526 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004527 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004528 if (isRelational)
4529 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_pointer_integer)
4530 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4531 else if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00004532 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004533 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00004534 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004535 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004536 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00004537 // Handle block pointers.
Mike Stumpea3d74e2009-05-07 18:43:07 +00004538 if (!isRelational && RHSIsNull
4539 && lType->isBlockPointerType() && rType->isIntegerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004540 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004541 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004542 }
Mike Stumpea3d74e2009-05-07 18:43:07 +00004543 if (!isRelational && LHSIsNull
4544 && lType->isIntegerType() && rType->isBlockPointerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004545 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004546 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004547 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00004548 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004549}
4550
Nate Begemanc5f0f652008-07-14 18:02:46 +00004551/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00004552/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004553/// like a scalar comparison, a vector comparison produces a vector of integer
4554/// types.
4555QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00004556 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004557 bool isRelational) {
4558 // Check to make sure we're operating on vectors of the same type and width,
4559 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004560 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004561 if (vType.isNull())
4562 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00004563
Nate Begemanc5f0f652008-07-14 18:02:46 +00004564 QualType lType = lex->getType();
4565 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004566
Nate Begemanc5f0f652008-07-14 18:02:46 +00004567 // For non-floating point types, check for self-comparisons of the form
4568 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4569 // often indicate logic errors in the program.
4570 if (!lType->isFloatingType()) {
4571 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4572 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4573 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00004574 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004575 }
Mike Stump9afab102009-02-19 03:04:26 +00004576
Nate Begemanc5f0f652008-07-14 18:02:46 +00004577 // Check for comparisons of floating point operands using != and ==.
4578 if (!isRelational && lType->isFloatingType()) {
4579 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004580 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004581 }
Mike Stump9afab102009-02-19 03:04:26 +00004582
Nate Begemanc5f0f652008-07-14 18:02:46 +00004583 // Return the type for the comparison, which is the same as vector type for
4584 // integer vectors, or an integer type of identical size and number of
4585 // elements for floating point vectors.
4586 if (lType->isIntegerType())
4587 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00004588
Nate Begemanc5f0f652008-07-14 18:02:46 +00004589 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00004590 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00004591 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00004592 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner10687e32009-03-31 07:46:52 +00004593 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begemand6d2f772009-01-18 03:20:47 +00004594 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4595
Mike Stump9afab102009-02-19 03:04:26 +00004596 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00004597 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00004598 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4599}
4600
Chris Lattner4b009652007-07-25 00:24:17 +00004601inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004602 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004603{
4604 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004605 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004606
Steve Naroff8f708362007-08-24 19:07:16 +00004607 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004608
Chris Lattner4b009652007-07-25 00:24:17 +00004609 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00004610 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004611 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004612}
4613
4614inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00004615 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00004616{
4617 UsualUnaryConversions(lex);
4618 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004619
Eli Friedmanbea3f842008-05-13 20:16:47 +00004620 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00004621 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004622 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004623}
4624
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004625/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4626/// is a read-only property; return true if so. A readonly property expression
4627/// depends on various declarations and thus must be treated specially.
4628///
Mike Stump9afab102009-02-19 03:04:26 +00004629static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004630{
4631 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4632 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4633 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4634 QualType BaseType = PropExpr->getBase()->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00004635 if (const ObjCObjectPointerType *OPT =
4636 BaseType->getAsObjCInterfacePointerType())
4637 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4638 if (S.isPropertyReadonly(PDecl, IFace))
4639 return true;
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004640 }
4641 }
4642 return false;
4643}
4644
Chris Lattner4c2642c2008-11-18 01:22:49 +00004645/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4646/// emit an error and return true. If so, return false.
4647static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004648 SourceLocation OrigLoc = Loc;
4649 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4650 &Loc);
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004651 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4652 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004653 if (IsLV == Expr::MLV_Valid)
4654 return false;
Mike Stump9afab102009-02-19 03:04:26 +00004655
Chris Lattner4c2642c2008-11-18 01:22:49 +00004656 unsigned Diag = 0;
4657 bool NeedType = false;
4658 switch (IsLV) { // C99 6.5.16p2
4659 default: assert(0 && "Unknown result from isModifiableLvalue!");
4660 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00004661 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004662 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4663 NeedType = true;
4664 break;
Mike Stump9afab102009-02-19 03:04:26 +00004665 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004666 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4667 NeedType = true;
4668 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00004669 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004670 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4671 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004672 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004673 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4674 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004675 case Expr::MLV_IncompleteType:
4676 case Expr::MLV_IncompleteVoidType:
Douglas Gregorc84d8932009-03-09 16:13:40 +00004677 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004678 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
4679 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00004680 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004681 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4682 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00004683 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004684 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4685 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00004686 case Expr::MLV_ReadonlyProperty:
4687 Diag = diag::error_readonly_property_assignment;
4688 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00004689 case Expr::MLV_NoSetterProperty:
4690 Diag = diag::error_nosetter_property_assignment;
4691 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004692 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00004693
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004694 SourceRange Assign;
4695 if (Loc != OrigLoc)
4696 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner4c2642c2008-11-18 01:22:49 +00004697 if (NeedType)
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004698 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004699 else
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004700 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004701 return true;
4702}
4703
4704
4705
4706// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00004707QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4708 SourceLocation Loc,
4709 QualType CompoundType) {
4710 // Verify that LHS is a modifiable lvalue, and emit error if not.
4711 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00004712 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00004713
4714 QualType LHSType = LHS->getType();
4715 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00004716
Chris Lattner005ed752008-01-04 18:04:52 +00004717 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004718 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00004719 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004720 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004721 // Special case of NSObject attributes on c-style pointer types.
4722 if (ConvTy == IncompatiblePointer &&
4723 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004724 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004725 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004726 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004727 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00004728
Chris Lattner34c85082008-08-21 18:04:13 +00004729 // If the RHS is a unary plus or minus, check to see if they = and + are
4730 // right next to each other. If so, the user may have typo'd "x =+ 4"
4731 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004732 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00004733 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4734 RHSCheck = ICE->getSubExpr();
4735 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4736 if ((UO->getOpcode() == UnaryOperator::Plus ||
4737 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00004738 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00004739 // Only if the two operators are exactly adjacent.
Chris Lattner55a17242009-03-08 06:51:10 +00004740 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4741 // And there is a space or other character before the subexpr of the
4742 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnerf1e5d4a2009-03-09 07:11:10 +00004743 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4744 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004745 Diag(Loc, diag::warn_not_compound_assign)
4746 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4747 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner55a17242009-03-08 06:51:10 +00004748 }
Chris Lattner34c85082008-08-21 18:04:13 +00004749 }
4750 } else {
4751 // Compound assignment "x += y"
Eli Friedmanb653af42009-05-16 05:56:02 +00004752 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00004753 }
Chris Lattner005ed752008-01-04 18:04:52 +00004754
Chris Lattner1eafdea2008-11-18 01:30:42 +00004755 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4756 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00004757 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004758
Chris Lattner4b009652007-07-25 00:24:17 +00004759 // C99 6.5.16p3: The type of an assignment expression is the type of the
4760 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00004761 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00004762 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4763 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004764 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004765 // operand.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004766 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00004767}
4768
Chris Lattner1eafdea2008-11-18 01:30:42 +00004769// C99 6.5.17
4770QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00004771 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004772 DefaultFunctionArrayConversion(RHS);
Eli Friedman2b128322009-03-23 00:24:07 +00004773
4774 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4775 // incomplete in C++).
4776
Chris Lattner1eafdea2008-11-18 01:30:42 +00004777 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00004778}
4779
4780/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4781/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004782QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4783 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004784 if (Op->isTypeDependent())
4785 return Context.DependentTy;
4786
Chris Lattnere65182c2008-11-21 07:05:48 +00004787 QualType ResType = Op->getType();
4788 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004789
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004790 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4791 // Decrement of bool is not allowed.
4792 if (!isInc) {
4793 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4794 return QualType();
4795 }
4796 // Increment of bool sets it to true, but is deprecated.
4797 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4798 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00004799 // OK!
Steve Naroff79ae19a2009-07-14 18:25:06 +00004800 } else if (ResType->isAnyPointerType()) {
4801 QualType PointeeTy = ResType->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00004802
Chris Lattnere65182c2008-11-21 07:05:48 +00004803 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff329ec222009-07-10 23:34:53 +00004804 if (PointeeTy->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004805 if (getLangOptions().CPlusPlus) {
4806 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4807 << Op->getSourceRange();
4808 return QualType();
4809 }
4810
4811 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00004812 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004813 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004814 if (getLangOptions().CPlusPlus) {
4815 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4816 << Op->getType() << Op->getSourceRange();
4817 return QualType();
4818 }
4819
4820 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004821 << ResType << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004822 } else if (RequireCompleteType(OpLoc, PointeeTy,
Douglas Gregorcde3a2d2009-03-24 20:13:58 +00004823 diag::err_typecheck_arithmetic_incomplete_type,
4824 Op->getSourceRange(), SourceRange(),
4825 ResType))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004826 return QualType();
Fariborz Jahanian4738ac52009-07-16 17:59:14 +00004827 // Diagnose bad cases where we step over interface counts.
4828 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4829 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
4830 << PointeeTy << Op->getSourceRange();
4831 return QualType();
4832 }
Chris Lattnere65182c2008-11-21 07:05:48 +00004833 } else if (ResType->isComplexType()) {
4834 // C99 does not support ++/-- on complex types, we allow as an extension.
4835 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004836 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004837 } else {
4838 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004839 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004840 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00004841 }
Mike Stump9afab102009-02-19 03:04:26 +00004842 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00004843 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00004844 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00004845 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00004846 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00004847}
4848
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004849/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00004850/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004851/// where the declaration is needed for type checking. We only need to
4852/// handle cases when the expression references a function designator
4853/// or is an lvalue. Here are some examples:
4854/// - &(x) => x
4855/// - &*****f => f for f a function designator.
4856/// - &s.xx => s
4857/// - &s.zz[1].yy -> s, if zz is an array
4858/// - *(x + 1) -> x, if x is an array
4859/// - &"123"[2] -> 0
4860/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00004861static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00004862 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00004863 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00004864 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004865 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00004866 case Stmt::MemberExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004867 // If this is an arrow operator, the address is an offset from
4868 // the base's value, so the object the base refers to is
4869 // irrelevant.
Chris Lattner48d7f382008-04-02 04:24:33 +00004870 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00004871 return 0;
Eli Friedman93ecce22009-04-20 08:23:18 +00004872 // Otherwise, the expression refers to a part of the base
Chris Lattner48d7f382008-04-02 04:24:33 +00004873 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004874 case Stmt::ArraySubscriptExprClass: {
Mike Stumpe127ae32009-05-16 07:39:55 +00004875 // FIXME: This code shouldn't be necessary! We should catch the implicit
4876 // promotion of register arrays earlier.
Eli Friedman93ecce22009-04-20 08:23:18 +00004877 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4878 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4879 if (ICE->getSubExpr()->getType()->isArrayType())
4880 return getPrimaryDecl(ICE->getSubExpr());
4881 }
4882 return 0;
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004883 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004884 case Stmt::UnaryOperatorClass: {
4885 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00004886
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004887 switch(UO->getOpcode()) {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004888 case UnaryOperator::Real:
4889 case UnaryOperator::Imag:
4890 case UnaryOperator::Extension:
4891 return getPrimaryDecl(UO->getSubExpr());
4892 default:
4893 return 0;
4894 }
4895 }
Chris Lattner4b009652007-07-25 00:24:17 +00004896 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004897 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00004898 case Stmt::ImplicitCastExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004899 // If the result of an implicit cast is an l-value, we care about
4900 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner48d7f382008-04-02 04:24:33 +00004901 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00004902 default:
4903 return 0;
4904 }
4905}
4906
4907/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00004908/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00004909/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00004910/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00004911/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00004912/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00004913/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00004914QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman93ecce22009-04-20 08:23:18 +00004915 // Make sure to ignore parentheses in subsequent checks
4916 op = op->IgnoreParens();
4917
Douglas Gregore6be68a2008-12-17 22:52:20 +00004918 if (op->isTypeDependent())
4919 return Context.DependentTy;
4920
Steve Naroff9c6c3592008-01-13 17:10:08 +00004921 if (getLangOptions().C99) {
4922 // Implement C99-only parts of addressof rules.
4923 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
4924 if (uOp->getOpcode() == UnaryOperator::Deref)
4925 // Per C99 6.5.3.2, the address of a deref always returns a valid result
4926 // (assuming the deref expression is valid).
4927 return uOp->getSubExpr()->getType();
4928 }
4929 // Technically, there should be a check for array subscript
4930 // expressions here, but the result of one is always an lvalue anyway.
4931 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00004932 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00004933 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00004934
Eli Friedman14ab4c42009-05-16 23:27:50 +00004935 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
4936 // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004937 // The operand must be either an l-value or a function designator
Eli Friedman14ab4c42009-05-16 23:27:50 +00004938 if (!op->getType()->isFunctionType()) {
Chris Lattnera3249072007-11-16 17:46:48 +00004939 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00004940 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
4941 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004942 return QualType();
4943 }
Douglas Gregor531434b2009-05-02 02:18:30 +00004944 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004945 // The operand cannot be a bit-field
4946 Diag(OpLoc, diag::err_typecheck_address_of)
4947 << "bit-field" << op->getSourceRange();
Douglas Gregor82d44772008-12-20 23:49:58 +00004948 return QualType();
Nate Begemana9187ab2009-02-15 22:45:20 +00004949 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
4950 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman93ecce22009-04-20 08:23:18 +00004951 // The operand cannot be an element of a vector
Chris Lattner77d52da2008-11-20 06:06:08 +00004952 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00004953 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004954 return QualType();
Fariborz Jahanianb35984a2009-07-07 18:50:52 +00004955 } else if (isa<ObjCPropertyRefExpr>(op)) {
4956 // cannot take address of a property expression.
4957 Diag(OpLoc, diag::err_typecheck_address_of)
4958 << "property expression" << op->getSourceRange();
4959 return QualType();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004960 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00004961 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00004962 // with the register storage-class specifier.
4963 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
4964 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004965 Diag(OpLoc, diag::err_typecheck_address_of)
4966 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004967 return QualType();
4968 }
Douglas Gregor62f78762009-07-08 20:55:45 +00004969 } else if (isa<OverloadedFunctionDecl>(dcl) ||
4970 isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00004971 return Context.OverloadTy;
Anders Carlsson64371472009-07-08 21:45:58 +00004972 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor5b82d612008-12-10 21:26:49 +00004973 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00004974 // Could be a pointer to member, though, if there is an explicit
4975 // scope qualifier for the class.
4976 if (isa<QualifiedDeclRefExpr>(op)) {
4977 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson64371472009-07-08 21:45:58 +00004978 if (Ctx && Ctx->isRecord()) {
4979 if (FD->getType()->isReferenceType()) {
4980 Diag(OpLoc,
4981 diag::err_cannot_form_pointer_to_member_of_reference_type)
4982 << FD->getDeclName() << FD->getType();
4983 return QualType();
4984 }
4985
Sebastian Redl0c9da212009-02-03 20:19:35 +00004986 return Context.getMemberPointerType(op->getType(),
4987 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson64371472009-07-08 21:45:58 +00004988 }
Sebastian Redl0c9da212009-02-03 20:19:35 +00004989 }
Anders Carlssone9cc4c42009-05-16 21:43:42 +00004990 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopesdf239522008-12-16 22:58:26 +00004991 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00004992 // As above.
Anders Carlssone9cc4c42009-05-16 21:43:42 +00004993 if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
4994 return Context.getMemberPointerType(op->getType(),
4995 Context.getTypeDeclType(MD->getParent()).getTypePtr());
4996 } else if (!isa<FunctionDecl>(dcl))
Chris Lattner4b009652007-07-25 00:24:17 +00004997 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00004998 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00004999
Eli Friedman14ab4c42009-05-16 23:27:50 +00005000 if (lval == Expr::LV_IncompleteVoidType) {
5001 // Taking the address of a void variable is technically illegal, but we
5002 // allow it in cases which are otherwise valid.
5003 // Example: "extern void x; void* y = &x;".
5004 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5005 }
5006
Chris Lattner4b009652007-07-25 00:24:17 +00005007 // If the operand has type "type", the result has type "pointer to type".
5008 return Context.getPointerType(op->getType());
5009}
5010
Chris Lattnerda5c0872008-11-23 09:13:29 +00005011QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005012 if (Op->isTypeDependent())
5013 return Context.DependentTy;
5014
Chris Lattnerda5c0872008-11-23 09:13:29 +00005015 UsualUnaryConversions(Op);
5016 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00005017
Chris Lattnerda5c0872008-11-23 09:13:29 +00005018 // Note that per both C89 and C99, this is always legal, even if ptype is an
5019 // incomplete type or void. It would be possible to warn about dereferencing
5020 // a void pointer, but it's completely well-defined, and such a warning is
5021 // unlikely to catch any mistakes.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00005022 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff9c6c3592008-01-13 17:10:08 +00005023 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00005024
Steve Naroff329ec222009-07-10 23:34:53 +00005025 if (const ObjCObjectPointerType *OPT = Ty->getAsObjCObjectPointerType())
5026 return OPT->getPointeeType();
5027
Chris Lattner77d52da2008-11-20 06:06:08 +00005028 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00005029 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00005030 return QualType();
5031}
5032
5033static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5034 tok::TokenKind Kind) {
5035 BinaryOperator::Opcode Opc;
5036 switch (Kind) {
5037 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00005038 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5039 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00005040 case tok::star: Opc = BinaryOperator::Mul; break;
5041 case tok::slash: Opc = BinaryOperator::Div; break;
5042 case tok::percent: Opc = BinaryOperator::Rem; break;
5043 case tok::plus: Opc = BinaryOperator::Add; break;
5044 case tok::minus: Opc = BinaryOperator::Sub; break;
5045 case tok::lessless: Opc = BinaryOperator::Shl; break;
5046 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5047 case tok::lessequal: Opc = BinaryOperator::LE; break;
5048 case tok::less: Opc = BinaryOperator::LT; break;
5049 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5050 case tok::greater: Opc = BinaryOperator::GT; break;
5051 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5052 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5053 case tok::amp: Opc = BinaryOperator::And; break;
5054 case tok::caret: Opc = BinaryOperator::Xor; break;
5055 case tok::pipe: Opc = BinaryOperator::Or; break;
5056 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5057 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5058 case tok::equal: Opc = BinaryOperator::Assign; break;
5059 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5060 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5061 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5062 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5063 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5064 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5065 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5066 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5067 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5068 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5069 case tok::comma: Opc = BinaryOperator::Comma; break;
5070 }
5071 return Opc;
5072}
5073
5074static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5075 tok::TokenKind Kind) {
5076 UnaryOperator::Opcode Opc;
5077 switch (Kind) {
5078 default: assert(0 && "Unknown unary op!");
5079 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5080 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5081 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5082 case tok::star: Opc = UnaryOperator::Deref; break;
5083 case tok::plus: Opc = UnaryOperator::Plus; break;
5084 case tok::minus: Opc = UnaryOperator::Minus; break;
5085 case tok::tilde: Opc = UnaryOperator::Not; break;
5086 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00005087 case tok::kw___real: Opc = UnaryOperator::Real; break;
5088 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5089 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5090 }
5091 return Opc;
5092}
5093
Douglas Gregord7f915e2008-11-06 23:29:22 +00005094/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5095/// operator @p Opc at location @c TokLoc. This routine only supports
5096/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005097Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5098 unsigned Op,
5099 Expr *lhs, Expr *rhs) {
Eli Friedman3cd92882009-03-28 01:22:36 +00005100 QualType ResultTy; // Result type of the binary operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00005101 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman3cd92882009-03-28 01:22:36 +00005102 // The following two variables are used for compound assignment operators
5103 QualType CompLHSTy; // Type of LHS after promotions for computation
5104 QualType CompResultTy; // Type of computation result
Douglas Gregord7f915e2008-11-06 23:29:22 +00005105
5106 switch (Opc) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00005107 case BinaryOperator::Assign:
5108 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5109 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005110 case BinaryOperator::PtrMemD:
5111 case BinaryOperator::PtrMemI:
5112 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5113 Opc == BinaryOperator::PtrMemI);
5114 break;
5115 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005116 case BinaryOperator::Div:
5117 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5118 break;
5119 case BinaryOperator::Rem:
5120 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5121 break;
5122 case BinaryOperator::Add:
5123 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5124 break;
5125 case BinaryOperator::Sub:
5126 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5127 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005128 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005129 case BinaryOperator::Shr:
5130 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5131 break;
5132 case BinaryOperator::LE:
5133 case BinaryOperator::LT:
5134 case BinaryOperator::GE:
5135 case BinaryOperator::GT:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005136 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005137 break;
5138 case BinaryOperator::EQ:
5139 case BinaryOperator::NE:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005140 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005141 break;
5142 case BinaryOperator::And:
5143 case BinaryOperator::Xor:
5144 case BinaryOperator::Or:
5145 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5146 break;
5147 case BinaryOperator::LAnd:
5148 case BinaryOperator::LOr:
5149 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5150 break;
5151 case BinaryOperator::MulAssign:
5152 case BinaryOperator::DivAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005153 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5154 CompLHSTy = CompResultTy;
5155 if (!CompResultTy.isNull())
5156 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005157 break;
5158 case BinaryOperator::RemAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005159 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5160 CompLHSTy = CompResultTy;
5161 if (!CompResultTy.isNull())
5162 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005163 break;
5164 case BinaryOperator::AddAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005165 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5166 if (!CompResultTy.isNull())
5167 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005168 break;
5169 case BinaryOperator::SubAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005170 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5171 if (!CompResultTy.isNull())
5172 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005173 break;
5174 case BinaryOperator::ShlAssign:
5175 case BinaryOperator::ShrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005176 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5177 CompLHSTy = CompResultTy;
5178 if (!CompResultTy.isNull())
5179 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005180 break;
5181 case BinaryOperator::AndAssign:
5182 case BinaryOperator::XorAssign:
5183 case BinaryOperator::OrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005184 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5185 CompLHSTy = CompResultTy;
5186 if (!CompResultTy.isNull())
5187 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005188 break;
5189 case BinaryOperator::Comma:
5190 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5191 break;
5192 }
5193 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005194 return ExprError();
Eli Friedman3cd92882009-03-28 01:22:36 +00005195 if (CompResultTy.isNull())
Steve Naroff774e4152009-01-21 00:14:39 +00005196 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5197 else
5198 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman3cd92882009-03-28 01:22:36 +00005199 CompLHSTy, CompResultTy,
5200 OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00005201}
5202
Chris Lattner4b009652007-07-25 00:24:17 +00005203// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005204Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5205 tok::TokenKind Kind,
5206 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00005207 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005208 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Chris Lattner4b009652007-07-25 00:24:17 +00005209
Steve Naroff87d58b42007-09-16 03:34:24 +00005210 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5211 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00005212
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005213 if (getLangOptions().CPlusPlus &&
5214 (lhs->getType()->isOverloadableType() ||
5215 rhs->getType()->isOverloadableType())) {
5216 // Find all of the overloaded operators visible from this
5217 // point. We perform both an operator-name lookup from the local
5218 // scope and an argument-dependent lookup based on the types of
5219 // the arguments.
Douglas Gregor3fc092f2009-03-13 00:33:25 +00005220 FunctionSet Functions;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005221 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5222 if (OverOp != OO_None) {
5223 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5224 Functions);
5225 Expr *Args[2] = { lhs, rhs };
5226 DeclarationName OpName
5227 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5228 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregor70d26122008-11-12 17:17:38 +00005229 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005230
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005231 // Build the (potentially-overloaded, potentially-dependent)
5232 // binary operation.
5233 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005234 }
5235
Douglas Gregord7f915e2008-11-06 23:29:22 +00005236 // Build a built-in binary operation.
5237 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00005238}
5239
Douglas Gregorc78182d2009-03-13 23:49:33 +00005240Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
5241 unsigned OpcIn,
5242 ExprArg InputArg) {
5243 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005244
Mike Stumpe127ae32009-05-16 07:39:55 +00005245 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorc78182d2009-03-13 23:49:33 +00005246 Expr *Input = (Expr *)InputArg.get();
Chris Lattner4b009652007-07-25 00:24:17 +00005247 QualType resultType;
5248 switch (Opc) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00005249 case UnaryOperator::OffsetOf:
5250 assert(false && "Invalid unary operator");
5251 break;
5252
Chris Lattner4b009652007-07-25 00:24:17 +00005253 case UnaryOperator::PreInc:
5254 case UnaryOperator::PreDec:
Eli Friedman79341142009-07-22 22:25:00 +00005255 case UnaryOperator::PostInc:
5256 case UnaryOperator::PostDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00005257 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman79341142009-07-22 22:25:00 +00005258 Opc == UnaryOperator::PreInc ||
5259 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00005260 break;
Mike Stump9afab102009-02-19 03:04:26 +00005261 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00005262 resultType = CheckAddressOfOperand(Input, OpLoc);
5263 break;
Mike Stump9afab102009-02-19 03:04:26 +00005264 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00005265 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00005266 resultType = CheckIndirectionOperand(Input, OpLoc);
5267 break;
5268 case UnaryOperator::Plus:
5269 case UnaryOperator::Minus:
5270 UsualUnaryConversions(Input);
5271 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005272 if (resultType->isDependentType())
5273 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005274 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5275 break;
5276 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5277 resultType->isEnumeralType())
5278 break;
5279 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5280 Opc == UnaryOperator::Plus &&
5281 resultType->isPointerType())
5282 break;
5283
Sebastian Redl8b769972009-01-19 00:08:26 +00005284 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5285 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005286 case UnaryOperator::Not: // bitwise complement
5287 UsualUnaryConversions(Input);
5288 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005289 if (resultType->isDependentType())
5290 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00005291 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5292 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5293 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00005294 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00005295 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00005296 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00005297 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5298 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005299 break;
5300 case UnaryOperator::LNot: // logical negation
5301 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
5302 DefaultFunctionArrayConversion(Input);
5303 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005304 if (resultType->isDependentType())
5305 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005306 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00005307 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5308 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005309 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00005310 // In C++, it's bool. C++ 5.3.1p8
5311 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00005312 break;
Chris Lattner03931a72007-08-24 21:16:53 +00005313 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00005314 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00005315 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00005316 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005317 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00005318 resultType = Input->getType();
5319 break;
5320 }
5321 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00005322 return ExprError();
Douglas Gregorc78182d2009-03-13 23:49:33 +00005323
5324 InputArg.release();
Steve Naroff774e4152009-01-21 00:14:39 +00005325 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005326}
5327
Douglas Gregorc78182d2009-03-13 23:49:33 +00005328// Unary Operators. 'Tok' is the token for the operator.
5329Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5330 tok::TokenKind Op, ExprArg input) {
5331 Expr *Input = (Expr*)input.get();
5332 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5333
5334 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5335 // Find all of the overloaded operators visible from this
5336 // point. We perform both an operator-name lookup from the local
5337 // scope and an argument-dependent lookup based on the types of
5338 // the arguments.
5339 FunctionSet Functions;
5340 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5341 if (OverOp != OO_None) {
5342 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5343 Functions);
5344 DeclarationName OpName
5345 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5346 ArgumentDependentLookup(OpName, &Input, 1, Functions);
5347 }
5348
5349 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5350 }
5351
5352 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5353}
5354
Steve Naroff5cbb02f2007-09-16 14:56:35 +00005355/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005356Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5357 SourceLocation LabLoc,
5358 IdentifierInfo *LabelII) {
Chris Lattner4b009652007-07-25 00:24:17 +00005359 // Look up the record for this label identifier.
Chris Lattner2616d8c2009-04-18 20:01:55 +00005360 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00005361
Daniel Dunbar879788d2008-08-04 16:51:22 +00005362 // If we haven't seen this label yet, create a forward reference. It
5363 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffb88d81c2009-03-13 15:38:40 +00005364 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00005365 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00005366
Chris Lattner4b009652007-07-25 00:24:17 +00005367 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005368 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5369 Context.getPointerType(Context.VoidTy)));
Chris Lattner4b009652007-07-25 00:24:17 +00005370}
5371
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005372Sema::OwningExprResult
5373Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5374 SourceLocation RPLoc) { // "({..})"
5375 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner4b009652007-07-25 00:24:17 +00005376 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5377 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5378
Eli Friedmanbc941e12009-01-24 23:09:00 +00005379 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattneraa257592009-04-25 19:11:05 +00005380 if (isFileScope)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005381 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmanbc941e12009-01-24 23:09:00 +00005382
Chris Lattner4b009652007-07-25 00:24:17 +00005383 // FIXME: there are a variety of strange constraints to enforce here, for
5384 // example, it is not possible to goto into a stmt expression apparently.
5385 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00005386
Chris Lattner4b009652007-07-25 00:24:17 +00005387 // If there are sub stmts in the compound stmt, take the type of the last one
5388 // as the type of the stmtexpr.
5389 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00005390
Chris Lattner200964f2008-07-26 19:51:01 +00005391 if (!Compound->body_empty()) {
5392 Stmt *LastStmt = Compound->body_back();
5393 // If LastStmt is a label, skip down through into the body.
5394 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5395 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00005396
Chris Lattner200964f2008-07-26 19:51:01 +00005397 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00005398 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00005399 }
Mike Stump9afab102009-02-19 03:04:26 +00005400
Eli Friedman2b128322009-03-23 00:24:07 +00005401 // FIXME: Check that expression type is complete/non-abstract; statement
5402 // expressions are not lvalues.
5403
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005404 substmt.release();
5405 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005406}
Steve Naroff63bad2d2007-08-01 22:05:33 +00005407
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005408Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5409 SourceLocation BuiltinLoc,
5410 SourceLocation TypeLoc,
5411 TypeTy *argty,
5412 OffsetOfComponent *CompPtr,
5413 unsigned NumComponents,
5414 SourceLocation RPLoc) {
5415 // FIXME: This function leaks all expressions in the offset components on
5416 // error.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005417 QualType ArgTy = QualType::getFromOpaquePtr(argty);
5418 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00005419
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005420 bool Dependent = ArgTy->isDependentType();
5421
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005422 // We must have at least one component that refers to the type, and the first
5423 // one is known to be a field designator. Verify that the ArgTy represents
5424 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005425 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005426 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump9afab102009-02-19 03:04:26 +00005427
Eli Friedman2b128322009-03-23 00:24:07 +00005428 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5429 // with an incomplete type would be illegal.
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00005430
Eli Friedman342d9432009-02-27 06:44:11 +00005431 // Otherwise, create a null pointer as the base, and iteratively process
5432 // the offsetof designators.
5433 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5434 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005435 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman342d9432009-02-27 06:44:11 +00005436 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00005437
Chris Lattnerb37522e2007-08-31 21:49:13 +00005438 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5439 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00005440 // FIXME: This diagnostic isn't actually visible because the location is in
5441 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00005442 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00005443 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5444 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00005445
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005446 if (!Dependent) {
Eli Friedmanc24ae002009-05-03 21:22:18 +00005447 bool DidWarnAboutNonPOD = false;
Anders Carlsson68c926c2009-05-02 18:36:10 +00005448
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005449 // FIXME: Dependent case loses a lot of information here. And probably
5450 // leaks like a sieve.
5451 for (unsigned i = 0; i != NumComponents; ++i) {
5452 const OffsetOfComponent &OC = CompPtr[i];
5453 if (OC.isBrackets) {
5454 // Offset of an array sub-field. TODO: Should we allow vector elements?
5455 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5456 if (!AT) {
5457 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005458 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5459 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005460 }
5461
5462 // FIXME: C++: Verify that operator[] isn't overloaded.
5463
Eli Friedman342d9432009-02-27 06:44:11 +00005464 // Promote the array so it looks more like a normal array subscript
5465 // expression.
5466 DefaultFunctionArrayConversion(Res);
5467
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005468 // C99 6.5.2.1p1
5469 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005470 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005471 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005472 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner7264d212009-04-25 22:50:55 +00005473 diag::err_typecheck_subscript_not_integer)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005474 << Idx->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005475
5476 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5477 OC.LocEnd);
5478 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005479 }
Mike Stump9afab102009-02-19 03:04:26 +00005480
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00005481 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005482 if (!RC) {
5483 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005484 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5485 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005486 }
Chris Lattner2af6a802007-08-30 17:59:59 +00005487
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005488 // Get the decl corresponding to this.
5489 RecordDecl *RD = RC->getDecl();
Anders Carlsson356946e2009-05-01 23:20:30 +00005490 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson68c926c2009-05-02 18:36:10 +00005491 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonbbceaea2009-05-02 17:45:47 +00005492 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5493 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5494 << Res->getType());
Anders Carlsson68c926c2009-05-02 18:36:10 +00005495 DidWarnAboutNonPOD = true;
5496 }
Anders Carlsson356946e2009-05-01 23:20:30 +00005497 }
5498
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005499 FieldDecl *MemberDecl
5500 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
5501 LookupMemberName)
5502 .getAsDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005503 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005504 if (!MemberDecl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005505 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
5506 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump9afab102009-02-19 03:04:26 +00005507
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005508 // FIXME: C++: Verify that MemberDecl isn't a static field.
5509 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman35719da2009-04-26 20:50:44 +00005510 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonc154a722009-05-01 19:30:39 +00005511 Res = BuildAnonymousStructUnionMemberReference(
5512 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedman35719da2009-04-26 20:50:44 +00005513 } else {
5514 // MemberDecl->getType() doesn't get the right qualifiers, but it
5515 // doesn't matter here.
5516 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5517 MemberDecl->getType().getNonReferenceType());
5518 }
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005519 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005520 }
Mike Stump9afab102009-02-19 03:04:26 +00005521
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005522 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5523 Context.getSizeType(), BuiltinLoc));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005524}
5525
5526
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005527Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5528 TypeTy *arg1,TypeTy *arg2,
5529 SourceLocation RPLoc) {
Steve Naroff63bad2d2007-08-01 22:05:33 +00005530 QualType argT1 = QualType::getFromOpaquePtr(arg1);
5531 QualType argT2 = QualType::getFromOpaquePtr(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00005532
Steve Naroff63bad2d2007-08-01 22:05:33 +00005533 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00005534
Douglas Gregore6211502009-05-19 22:28:02 +00005535 if (getLangOptions().CPlusPlus) {
5536 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5537 << SourceRange(BuiltinLoc, RPLoc);
5538 return ExprError();
5539 }
5540
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005541 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5542 argT1, argT2, RPLoc));
Steve Naroff63bad2d2007-08-01 22:05:33 +00005543}
5544
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005545Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5546 ExprArg cond,
5547 ExprArg expr1, ExprArg expr2,
5548 SourceLocation RPLoc) {
5549 Expr *CondExpr = static_cast<Expr*>(cond.get());
5550 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5551 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump9afab102009-02-19 03:04:26 +00005552
Steve Naroff93c53012007-08-03 21:21:27 +00005553 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5554
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005555 QualType resType;
Douglas Gregordd4ae3f2009-05-19 22:43:30 +00005556 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005557 resType = Context.DependentTy;
5558 } else {
5559 // The conditional expression is required to be a constant expression.
5560 llvm::APSInt condEval(32);
5561 SourceLocation ExpLoc;
5562 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005563 return ExprError(Diag(ExpLoc,
5564 diag::err_typecheck_choose_expr_requires_constant)
5565 << CondExpr->getSourceRange());
Steve Naroff93c53012007-08-03 21:21:27 +00005566
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005567 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5568 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5569 }
5570
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005571 cond.release(); expr1.release(); expr2.release();
5572 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5573 resType, RPLoc));
Steve Naroff93c53012007-08-03 21:21:27 +00005574}
5575
Steve Naroff52a81c02008-09-03 18:15:37 +00005576//===----------------------------------------------------------------------===//
5577// Clang Extensions.
5578//===----------------------------------------------------------------------===//
5579
5580/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00005581void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005582 // Analyze block parameters.
5583 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00005584
Steve Naroff52a81c02008-09-03 18:15:37 +00005585 // Add BSI to CurBlock.
5586 BSI->PrevBlockInfo = CurBlock;
5587 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00005588
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005589 BSI->ReturnType = QualType();
Steve Naroff52a81c02008-09-03 18:15:37 +00005590 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00005591 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarc7ef2b92009-07-29 01:59:17 +00005592 BSI->hasPrototype = false;
Chris Lattnere7765e12009-04-19 05:28:12 +00005593 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5594 CurFunctionNeedsScopeChecking = false;
Mike Stump9afab102009-02-19 03:04:26 +00005595
Steve Naroff52059382008-10-10 01:28:17 +00005596 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00005597 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00005598}
5599
Mike Stumpc1fddff2009-02-04 22:31:32 +00005600void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpea3d74e2009-05-07 18:43:07 +00005601 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stumpc1fddff2009-02-04 22:31:32 +00005602
5603 if (ParamInfo.getNumTypeObjects() == 0
5604 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005605 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stumpc1fddff2009-02-04 22:31:32 +00005606 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5607
Mike Stump458287d2009-04-28 01:10:27 +00005608 if (T->isArrayType()) {
5609 Diag(ParamInfo.getSourceRange().getBegin(),
5610 diag::err_block_returns_array);
5611 return;
5612 }
5613
Mike Stumpc1fddff2009-02-04 22:31:32 +00005614 // The parameter list is optional, if there was none, assume ().
5615 if (!T->isFunctionType())
5616 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5617
5618 CurBlock->hasPrototype = true;
5619 CurBlock->isVariadic = false;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005620 // Check for a valid sentinel attribute on this block.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005621 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005622 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005623 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005624 // FIXME: remove the attribute.
5625 }
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005626 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
5627
5628 // Do not allow returning a objc interface by-value.
5629 if (RetTy->isObjCInterfaceType()) {
5630 Diag(ParamInfo.getSourceRange().getBegin(),
5631 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5632 return;
5633 }
Mike Stumpc1fddff2009-02-04 22:31:32 +00005634 return;
5635 }
5636
Steve Naroff52a81c02008-09-03 18:15:37 +00005637 // Analyze arguments to block.
5638 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5639 "Not a function declarator!");
5640 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00005641
Steve Naroff52059382008-10-10 01:28:17 +00005642 CurBlock->hasPrototype = FTI.hasPrototype;
5643 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00005644
Steve Naroff52a81c02008-09-03 18:15:37 +00005645 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5646 // no arguments, not a function that takes a single void argument.
5647 if (FTI.hasPrototype &&
5648 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner5261d0c2009-03-28 19:18:32 +00005649 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5650 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005651 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00005652 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00005653 } else if (FTI.hasPrototype) {
5654 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner5261d0c2009-03-28 19:18:32 +00005655 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff52059382008-10-10 01:28:17 +00005656 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00005657 }
Jay Foad9e6bef42009-05-21 09:52:38 +00005658 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005659 CurBlock->Params.size());
Fariborz Jahanian536f73d2009-05-19 17:08:59 +00005660 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005661 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff52059382008-10-10 01:28:17 +00005662 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5663 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5664 // If this has an identifier, add it to the scope stack.
5665 if ((*AI)->getIdentifier())
5666 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005667
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005668 // Check for a valid sentinel attribute on this block.
Douglas Gregor98da6ae2009-06-18 16:11:24 +00005669 if (!CurBlock->isVariadic &&
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005670 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005671 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005672 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005673 // FIXME: remove the attribute.
5674 }
5675
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005676 // Analyze the return type.
5677 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5678 QualType RetTy = T->getAsFunctionType()->getResultType();
5679
5680 // Do not allow returning a objc interface by-value.
5681 if (RetTy->isObjCInterfaceType()) {
5682 Diag(ParamInfo.getSourceRange().getBegin(),
5683 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5684 } else if (!RetTy->isDependentType())
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005685 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00005686}
5687
5688/// ActOnBlockError - If there is an error parsing a block, this callback
5689/// is invoked to pop the information about the block from the action impl.
5690void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5691 // Ensure that CurBlock is deleted.
5692 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00005693
Chris Lattnere7765e12009-04-19 05:28:12 +00005694 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5695
Steve Naroff52a81c02008-09-03 18:15:37 +00005696 // Pop off CurBlock, handle nested blocks.
Chris Lattnereb4d4a52009-04-21 22:38:46 +00005697 PopDeclContext();
Steve Naroff52a81c02008-09-03 18:15:37 +00005698 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff52a81c02008-09-03 18:15:37 +00005699 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff52a81c02008-09-03 18:15:37 +00005700}
5701
5702/// ActOnBlockStmtExpr - This is called when the body of a block statement
5703/// literal was successfully completed. ^(int x){...}
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005704Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5705 StmtArg body, Scope *CurScope) {
Chris Lattnerc14c7f02009-03-27 04:18:06 +00005706 // If blocks are disabled, emit an error.
5707 if (!LangOpts.Blocks)
5708 Diag(CaretLoc, diag::err_blocks_disable);
5709
Steve Naroff52a81c02008-09-03 18:15:37 +00005710 // Ensure that CurBlock is deleted.
5711 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff52a81c02008-09-03 18:15:37 +00005712
Steve Naroff52059382008-10-10 01:28:17 +00005713 PopDeclContext();
5714
Steve Naroff52a81c02008-09-03 18:15:37 +00005715 // Pop off CurBlock, handle nested blocks.
5716 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00005717
Steve Naroff52a81c02008-09-03 18:15:37 +00005718 QualType RetTy = Context.VoidTy;
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005719 if (!BSI->ReturnType.isNull())
5720 RetTy = BSI->ReturnType;
Mike Stump9afab102009-02-19 03:04:26 +00005721
Steve Naroff52a81c02008-09-03 18:15:37 +00005722 llvm::SmallVector<QualType, 8> ArgTypes;
5723 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5724 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00005725
Mike Stump8e288f42009-07-28 22:04:01 +00005726 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff52a81c02008-09-03 18:15:37 +00005727 QualType BlockTy;
5728 if (!BSI->hasPrototype)
Mike Stump8e288f42009-07-28 22:04:01 +00005729 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5730 NoReturn);
Steve Naroff52a81c02008-09-03 18:15:37 +00005731 else
Jay Foad9e6bef42009-05-21 09:52:38 +00005732 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump8e288f42009-07-28 22:04:01 +00005733 BSI->isVariadic, 0, false, false, 0, 0,
5734 NoReturn);
Mike Stump9afab102009-02-19 03:04:26 +00005735
Eli Friedman2b128322009-03-23 00:24:07 +00005736 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregor98189262009-06-19 23:52:42 +00005737 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff52a81c02008-09-03 18:15:37 +00005738 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00005739
Chris Lattnere7765e12009-04-19 05:28:12 +00005740 // If needed, diagnose invalid gotos and switches in the block.
5741 if (CurFunctionNeedsScopeChecking)
5742 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5743 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5744
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005745 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump8e288f42009-07-28 22:04:01 +00005746 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005747 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5748 BSI->hasBlockDeclRefExprs));
Steve Naroff52a81c02008-09-03 18:15:37 +00005749}
5750
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005751Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5752 ExprArg expr, TypeTy *type,
5753 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00005754 QualType T = QualType::getFromOpaquePtr(type);
Chris Lattnerda139482009-04-05 15:49:53 +00005755 Expr *E = static_cast<Expr*>(expr.get());
5756 Expr *OrigExpr = E;
5757
Anders Carlsson36760332007-10-15 20:28:48 +00005758 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005759
5760 // Get the va_list type
5761 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman6f6e8922009-05-16 12:46:54 +00005762 if (VaListType->isArrayType()) {
5763 // Deal with implicit array decay; for example, on x86-64,
5764 // va_list is an array, but it's supposed to decay to
5765 // a pointer for va_arg.
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005766 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman6f6e8922009-05-16 12:46:54 +00005767 // Make sure the input expression also decays appropriately.
5768 UsualUnaryConversions(E);
5769 } else {
5770 // Otherwise, the va_list argument must be an l-value because
5771 // it is modified by va_arg.
Douglas Gregor25990972009-05-19 23:10:31 +00005772 if (!E->isTypeDependent() &&
5773 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman6f6e8922009-05-16 12:46:54 +00005774 return ExprError();
5775 }
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005776
Douglas Gregor25990972009-05-19 23:10:31 +00005777 if (!E->isTypeDependent() &&
5778 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005779 return ExprError(Diag(E->getLocStart(),
5780 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerda139482009-04-05 15:49:53 +00005781 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner89a72c52009-04-05 00:59:53 +00005782 }
Mike Stump9afab102009-02-19 03:04:26 +00005783
Eli Friedman2b128322009-03-23 00:24:07 +00005784 // FIXME: Check that type is complete/non-abstract
Anders Carlsson36760332007-10-15 20:28:48 +00005785 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00005786
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005787 expr.release();
5788 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5789 RPLoc));
Anders Carlsson36760332007-10-15 20:28:48 +00005790}
5791
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005792Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregorad4b3792008-11-29 04:51:27 +00005793 // The type of __null will be int or long, depending on the size of
5794 // pointers on the target.
5795 QualType Ty;
5796 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5797 Ty = Context.IntTy;
5798 else
5799 Ty = Context.LongTy;
5800
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005801 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregorad4b3792008-11-29 04:51:27 +00005802}
5803
Chris Lattner005ed752008-01-04 18:04:52 +00005804bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5805 SourceLocation Loc,
5806 QualType DstType, QualType SrcType,
5807 Expr *SrcExpr, const char *Flavor) {
5808 // Decode the result (notice that AST's are still created for extensions).
5809 bool isInvalid = false;
5810 unsigned DiagKind;
5811 switch (ConvTy) {
5812 default: assert(0 && "Unknown conversion type");
5813 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005814 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00005815 DiagKind = diag::ext_typecheck_convert_pointer_int;
5816 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005817 case IntToPointer:
5818 DiagKind = diag::ext_typecheck_convert_int_pointer;
5819 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005820 case IncompatiblePointer:
5821 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5822 break;
Eli Friedman6ca28cb2009-03-22 23:59:44 +00005823 case IncompatiblePointerSign:
5824 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5825 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005826 case FunctionVoidPointer:
5827 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5828 break;
5829 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00005830 // If the qualifiers lost were because we were applying the
5831 // (deprecated) C++ conversion from a string literal to a char*
5832 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
5833 // Ideally, this check would be performed in
5834 // CheckPointerTypesForAssignment. However, that would require a
5835 // bit of refactoring (so that the second argument is an
5836 // expression, rather than a type), which should be done as part
5837 // of a larger effort to fix CheckPointerTypesForAssignment for
5838 // C++ semantics.
5839 if (getLangOptions().CPlusPlus &&
5840 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5841 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00005842 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5843 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005844 case IntToBlockPointer:
5845 DiagKind = diag::err_int_to_block_pointer;
5846 break;
5847 case IncompatibleBlockPointer:
Mike Stumpd331e752009-04-21 22:51:42 +00005848 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005849 break;
Steve Naroff19608432008-10-14 22:18:38 +00005850 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00005851 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00005852 // it can give a more specific diagnostic.
5853 DiagKind = diag::warn_incompatible_qualified_id;
5854 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00005855 case IncompatibleVectors:
5856 DiagKind = diag::warn_incompatible_vectors;
5857 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005858 case Incompatible:
5859 DiagKind = diag::err_typecheck_convert_incompatible;
5860 isInvalid = true;
5861 break;
5862 }
Mike Stump9afab102009-02-19 03:04:26 +00005863
Chris Lattner271d4c22008-11-24 05:29:24 +00005864 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5865 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00005866 return isInvalid;
5867}
Anders Carlssond5201b92008-11-30 19:50:32 +00005868
Chris Lattnereec8ae22009-04-25 21:59:05 +00005869bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmance329412009-04-25 22:26:58 +00005870 llvm::APSInt ICEResult;
5871 if (E->isIntegerConstantExpr(ICEResult, Context)) {
5872 if (Result)
5873 *Result = ICEResult;
5874 return false;
5875 }
5876
Anders Carlssond5201b92008-11-30 19:50:32 +00005877 Expr::EvalResult EvalResult;
5878
Mike Stump9afab102009-02-19 03:04:26 +00005879 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00005880 EvalResult.HasSideEffects) {
5881 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5882
5883 if (EvalResult.Diag) {
5884 // We only show the note if it's not the usual "invalid subexpression"
5885 // or if it's actually in a subexpression.
5886 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5887 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5888 Diag(EvalResult.DiagLoc, EvalResult.Diag);
5889 }
Mike Stump9afab102009-02-19 03:04:26 +00005890
Anders Carlssond5201b92008-11-30 19:50:32 +00005891 return true;
5892 }
5893
Eli Friedmance329412009-04-25 22:26:58 +00005894 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5895 E->getSourceRange();
Anders Carlssond5201b92008-11-30 19:50:32 +00005896
Eli Friedmance329412009-04-25 22:26:58 +00005897 if (EvalResult.Diag &&
5898 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5899 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump9afab102009-02-19 03:04:26 +00005900
Anders Carlssond5201b92008-11-30 19:50:32 +00005901 if (Result)
5902 *Result = EvalResult.Val.getInt();
5903 return false;
5904}
Douglas Gregor98189262009-06-19 23:52:42 +00005905
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005906Sema::ExpressionEvaluationContext
5907Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
5908 // Introduce a new set of potentially referenced declarations to the stack.
5909 if (NewContext == PotentiallyPotentiallyEvaluated)
5910 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
5911
5912 std::swap(ExprEvalContext, NewContext);
5913 return NewContext;
5914}
5915
5916void
5917Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
5918 ExpressionEvaluationContext NewContext) {
5919 ExprEvalContext = NewContext;
5920
5921 if (OldContext == PotentiallyPotentiallyEvaluated) {
5922 // Mark any remaining declarations in the current position of the stack
5923 // as "referenced". If they were not meant to be referenced, semantic
5924 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
5925 PotentiallyReferencedDecls RemainingDecls;
5926 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
5927 PotentiallyReferencedDeclStack.pop_back();
5928
5929 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
5930 IEnd = RemainingDecls.end();
5931 I != IEnd; ++I)
5932 MarkDeclarationReferenced(I->first, I->second);
5933 }
5934}
Douglas Gregor98189262009-06-19 23:52:42 +00005935
5936/// \brief Note that the given declaration was referenced in the source code.
5937///
5938/// This routine should be invoke whenever a given declaration is referenced
5939/// in the source code, and where that reference occurred. If this declaration
5940/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
5941/// C99 6.9p3), then the declaration will be marked as used.
5942///
5943/// \param Loc the location where the declaration was referenced.
5944///
5945/// \param D the declaration that has been referenced by the source code.
5946void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
5947 assert(D && "No declaration?");
5948
Douglas Gregorcad27f62009-06-22 23:06:13 +00005949 if (D->isUsed())
5950 return;
5951
Douglas Gregor98189262009-06-19 23:52:42 +00005952 // Mark a parameter declaration "used", regardless of whether we're in a
5953 // template or not.
5954 if (isa<ParmVarDecl>(D))
5955 D->setUsed(true);
5956
5957 // Do not mark anything as "used" within a dependent context; wait for
5958 // an instantiation.
5959 if (CurContext->isDependentContext())
5960 return;
5961
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005962 switch (ExprEvalContext) {
5963 case Unevaluated:
5964 // We are in an expression that is not potentially evaluated; do nothing.
5965 return;
5966
5967 case PotentiallyEvaluated:
5968 // We are in a potentially-evaluated expression, so this declaration is
5969 // "used"; handle this below.
5970 break;
5971
5972 case PotentiallyPotentiallyEvaluated:
5973 // We are in an expression that may be potentially evaluated; queue this
5974 // declaration reference until we know whether the expression is
5975 // potentially evaluated.
5976 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
5977 return;
5978 }
5979
Douglas Gregor98189262009-06-19 23:52:42 +00005980 // Note that this declaration has been used.
Fariborz Jahanian8915a3d2009-06-22 17:30:33 +00005981 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00005982 unsigned TypeQuals;
Fariborz Jahanian2f5a0a32009-06-22 20:37:23 +00005983 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
5984 if (!Constructor->isUsed())
5985 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump90fc78e2009-08-04 21:02:39 +00005986 } else if (Constructor->isImplicit() &&
5987 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00005988 if (!Constructor->isUsed())
5989 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
5990 }
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00005991 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
5992 if (Destructor->isImplicit() && !Destructor->isUsed())
5993 DefineImplicitDestructor(Loc, Destructor);
5994
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00005995 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
5996 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
5997 MethodDecl->getOverloadedOperator() == OO_Equal) {
5998 if (!MethodDecl->isUsed())
5999 DefineImplicitOverloadedAssign(Loc, MethodDecl);
6000 }
6001 }
Fariborz Jahanianb12bd432009-06-24 22:09:44 +00006002 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00006003 // Implicit instantiation of function templates and member functions of
6004 // class templates.
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00006005 if (!Function->getBody()) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00006006 // FIXME: distinguish between implicit instantiations of function
6007 // templates and explicit specializations (the latter don't get
6008 // instantiated, naturally).
6009 if (Function->getInstantiatedFromMemberFunction() ||
6010 Function->getPrimaryTemplate())
Douglas Gregordcdb3842009-06-30 17:20:14 +00006011 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregorcad27f62009-06-22 23:06:13 +00006012 }
6013
6014
Douglas Gregor98189262009-06-19 23:52:42 +00006015 // FIXME: keep track of references to static functions
Douglas Gregor98189262009-06-19 23:52:42 +00006016 Function->setUsed(true);
6017 return;
Douglas Gregorcad27f62009-06-22 23:06:13 +00006018 }
Douglas Gregor98189262009-06-19 23:52:42 +00006019
6020 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor181fe792009-07-24 20:34:43 +00006021 // Implicit instantiation of static data members of class templates.
6022 // FIXME: distinguish between implicit instantiations (which we need to
6023 // actually instantiate) and explicit specializations.
6024 if (Var->isStaticDataMember() &&
6025 Var->getInstantiatedFromStaticDataMember())
6026 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6027
Douglas Gregor98189262009-06-19 23:52:42 +00006028 // FIXME: keep track of references to static data?
Douglas Gregor181fe792009-07-24 20:34:43 +00006029
Douglas Gregor98189262009-06-19 23:52:42 +00006030 D->setUsed(true);
Douglas Gregor181fe792009-07-24 20:34:43 +00006031 return;
6032}
Douglas Gregor98189262009-06-19 23:52:42 +00006033}
6034