blob: 720217a9103af3184c732d8909cb6c8a0039fd38 [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"
Anders Carlssonb5247af2009-08-26 22:59:12 +000017#include "clang/AST/DeclTemplate.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000018#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000019#include "clang/AST/ExprObjC.h"
Anders Carlssonb5247af2009-08-26 22:59:12 +000020#include "clang/Basic/PartialDiagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Anders Carlssonb5247af2009-08-26 22:59:12 +000023#include "clang/Lex/LiteralSupport.h"
24#include "clang/Lex/Preprocessor.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000025#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000026#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000027#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000028using namespace clang;
29
David Chisnall44663db2009-08-17 16:35:33 +000030
Douglas Gregoraa57e862009-02-18 21:56:37 +000031/// \brief Determine whether the use of this declaration is valid, and
32/// emit any corresponding diagnostics.
33///
34/// This routine diagnoses various problems with referencing
35/// declarations that can occur when using a declaration. For example,
36/// it might warn if a deprecated or unavailable declaration is being
37/// used, or produce an error (and return true) if a C++0x deleted
38/// function is being used.
39///
40/// \returns true if there was an error (this declaration cannot be
41/// referenced), false otherwise.
42bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000043 // See if the decl is deprecated.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000044 if (D->getAttr<DeprecatedAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000045 // Implementing deprecated stuff requires referencing deprecated
46 // stuff. Don't warn if we are implementing a deprecated
47 // construct.
Chris Lattnerfb1bb822009-02-16 19:35:30 +000048 bool isSilenced = false;
49
50 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
51 // If this reference happens *in* a deprecated function or method, don't
52 // warn.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000053 isSilenced = ND->getAttr<DeprecatedAttr>();
Chris Lattnerfb1bb822009-02-16 19:35:30 +000054
55 // If this is an Objective-C method implementation, check to see if the
56 // method was deprecated on the declaration, not the definition.
57 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
58 // The semantic decl context of a ObjCMethodDecl is the
59 // ObjCImplementationDecl.
60 if (ObjCImplementationDecl *Impl
61 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
62
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +000063 MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
Chris Lattnerfb1bb822009-02-16 19:35:30 +000064 MD->isInstanceMethod());
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000065 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
Chris Lattnerfb1bb822009-02-16 19:35:30 +000066 }
67 }
68 }
69
70 if (!isSilenced)
Chris Lattner2cb744b2009-02-15 22:43:40 +000071 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
72 }
73
Douglas Gregoraa57e862009-02-18 21:56:37 +000074 // See if this is a deleted function.
Douglas Gregor6f8c3682009-02-24 04:26:15 +000075 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000076 if (FD->isDeleted()) {
77 Diag(Loc, diag::err_deleted_function_use);
78 Diag(D->getLocation(), diag::note_unavailable_here) << true;
79 return true;
80 }
Douglas Gregor6f8c3682009-02-24 04:26:15 +000081 }
Douglas Gregoraa57e862009-02-18 21:56:37 +000082
83 // See if the decl is unavailable
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000084 if (D->getAttr<UnavailableAttr>()) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000085 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
Douglas Gregoraa57e862009-02-18 21:56:37 +000086 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
87 }
88
Douglas Gregoraa57e862009-02-18 21:56:37 +000089 return false;
Chris Lattner2cb744b2009-02-15 22:43:40 +000090}
91
Fariborz Jahanian180f3412009-05-13 18:09:35 +000092/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
93/// (and other functions in future), which have been declared with sentinel
94/// attribute. It warns if call does not have the sentinel argument.
95///
96void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
97 Expr **Args, unsigned NumArgs)
98{
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000099 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000100 if (!attr)
101 return;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000102 int sentinelPos = attr->getSentinel();
103 int nullPos = attr->getNullPos();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000104
Mike Stumpe127ae32009-05-16 07:39:55 +0000105 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
106 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000107 unsigned int i = 0;
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000108 bool warnNotEnoughArgs = false;
109 int isMethod = 0;
110 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
111 // skip over named parameters.
112 ObjCMethodDecl::param_iterator P, E = MD->param_end();
113 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
114 if (nullPos)
115 --nullPos;
116 else
117 ++i;
118 }
119 warnNotEnoughArgs = (P != E || i >= NumArgs);
120 isMethod = 1;
Mike Stump90fc78e2009-08-04 21:02:39 +0000121 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000122 // skip over named parameters.
123 ObjCMethodDecl::param_iterator P, E = FD->param_end();
124 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
125 if (nullPos)
126 --nullPos;
127 else
128 ++i;
129 }
130 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump90fc78e2009-08-04 21:02:39 +0000131 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000132 // block or function pointer call.
133 QualType Ty = V->getType();
134 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
135 const FunctionType *FT = Ty->isFunctionPointerType()
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000136 ? Ty->getAs<PointerType>()->getPointeeType()->getAsFunctionType()
137 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAsFunctionType();
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000138 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
139 unsigned NumArgsInProto = Proto->getNumArgs();
140 unsigned k;
141 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
142 if (nullPos)
143 --nullPos;
144 else
145 ++i;
146 }
147 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
148 }
149 if (Ty->isBlockPointerType())
150 isMethod = 2;
Mike Stump90fc78e2009-08-04 21:02:39 +0000151 } else
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000152 return;
Mike Stump90fc78e2009-08-04 21:02:39 +0000153 } else
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000154 return;
155
156 if (warnNotEnoughArgs) {
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000157 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000158 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000159 return;
160 }
161 int sentinel = i;
162 while (sentinelPos > 0 && i < NumArgs-1) {
163 --sentinelPos;
164 ++i;
165 }
166 if (sentinelPos > 0) {
167 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000168 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000169 return;
170 }
171 while (i < NumArgs-1) {
172 ++i;
173 ++sentinel;
174 }
175 Expr *sentinelExpr = Args[sentinel];
176 if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() ||
177 !sentinelExpr->isNullPointerConstant(Context))) {
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000178 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000179 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000180 }
181 return;
Fariborz Jahanian180f3412009-05-13 18:09:35 +0000182}
183
Douglas Gregor3bb30002009-02-26 21:00:50 +0000184SourceRange Sema::getExprRange(ExprTy *E) const {
185 Expr *Ex = (Expr *)E;
186 return Ex? Ex->getSourceRange() : SourceRange();
187}
188
Chris Lattner299b8842008-07-25 21:10:04 +0000189//===----------------------------------------------------------------------===//
190// Standard Promotions and Conversions
191//===----------------------------------------------------------------------===//
192
Chris Lattner299b8842008-07-25 21:10:04 +0000193/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
194void Sema::DefaultFunctionArrayConversion(Expr *&E) {
195 QualType Ty = E->getType();
196 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
197
Chris Lattner299b8842008-07-25 21:10:04 +0000198 if (Ty->isFunctionType())
Anders Carlssonb6feaf32009-09-01 20:37:18 +0000199 ImpCastExprToType(E, Context.getPointerType(Ty),
200 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner2aa68822008-07-25 21:33:13 +0000201 else if (Ty->isArrayType()) {
202 // In C90 mode, arrays only promote to pointers if the array expression is
203 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
204 // type 'array of type' is converted to an expression that has type 'pointer
205 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
206 // that has type 'array of type' ...". The relevant change is "an lvalue"
207 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +0000208 //
209 // C++ 4.2p1:
210 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
211 // T" can be converted to an rvalue of type "pointer to T".
212 //
213 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
214 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson5c09af02009-08-07 23:48:20 +0000215 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
216 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner2aa68822008-07-25 21:33:13 +0000217 }
Chris Lattner299b8842008-07-25 21:10:04 +0000218}
219
220/// UsualUnaryConversions - Performs various conversions that are common to most
221/// operators (C99 6.3). The conversions of array and function types are
222/// sometimes surpressed. For example, the array->pointer conversion doesn't
223/// apply if the array is an argument to the sizeof or address (&) operators.
224/// In these instances, this routine should *not* be called.
225Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
226 QualType Ty = Expr->getType();
227 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
228
Douglas Gregor70b307e2009-05-01 20:41:21 +0000229 // C99 6.3.1.1p2:
230 //
231 // The following may be used in an expression wherever an int or
232 // unsigned int may be used:
233 // - an object or expression with an integer type whose integer
234 // conversion rank is less than or equal to the rank of int
235 // and unsigned int.
236 // - A bit-field of type _Bool, int, signed int, or unsigned int.
237 //
238 // If an int can represent all values of the original type, the
239 // value is converted to an int; otherwise, it is converted to an
240 // unsigned int. These are called the integer promotions. All
241 // other types are unchanged by the integer promotions.
Eli Friedman1931cc82009-08-20 04:21:42 +0000242 QualType PTy = Context.isPromotableBitField(Expr);
243 if (!PTy.isNull()) {
244 ImpCastExprToType(Expr, PTy);
245 return Expr;
246 }
Douglas Gregor70b307e2009-05-01 20:41:21 +0000247 if (Ty->isPromotableIntegerType()) {
Eli Friedman6ae7d112009-08-19 07:44:53 +0000248 QualType PT = Context.getPromotedIntegerType(Ty);
249 ImpCastExprToType(Expr, PT);
Douglas Gregor70b307e2009-05-01 20:41:21 +0000250 return Expr;
Eli Friedman1931cc82009-08-20 04:21:42 +0000251 }
252
Douglas Gregor70b307e2009-05-01 20:41:21 +0000253 DefaultFunctionArrayConversion(Expr);
Chris Lattner299b8842008-07-25 21:10:04 +0000254 return Expr;
255}
256
Chris Lattner9305c3d2008-07-25 22:25:12 +0000257/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
258/// do not have a prototype. Arguments that have type float are promoted to
259/// double. All other argument types are converted by UsualUnaryConversions().
260void Sema::DefaultArgumentPromotion(Expr *&Expr) {
261 QualType Ty = Expr->getType();
262 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
263
264 // If this is a 'float' (CVR qualified or typedef) promote to double.
265 if (const BuiltinType *BT = Ty->getAsBuiltinType())
266 if (BT->getKind() == BuiltinType::Float)
267 return ImpCastExprToType(Expr, Context.DoubleTy);
268
269 UsualUnaryConversions(Expr);
270}
271
Chris Lattner81f00ed2009-04-12 08:11:20 +0000272/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
273/// will warn if the resulting type is not a POD type, and rejects ObjC
274/// interfaces passed by value. This returns true if the argument type is
275/// completely illegal.
276bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000277 DefaultArgumentPromotion(Expr);
278
Chris Lattner81f00ed2009-04-12 08:11:20 +0000279 if (Expr->getType()->isObjCInterfaceType()) {
280 Diag(Expr->getLocStart(),
281 diag::err_cannot_pass_objc_interface_to_vararg)
282 << Expr->getType() << CT;
283 return true;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000284 }
Chris Lattner81f00ed2009-04-12 08:11:20 +0000285
286 if (!Expr->getType()->isPODType())
287 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
288 << Expr->getType() << CT;
289
290 return false;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000291}
292
293
Chris Lattner299b8842008-07-25 21:10:04 +0000294/// UsualArithmeticConversions - Performs various conversions that are common to
295/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
296/// routine returns the first non-arithmetic type found. The client is
297/// responsible for emitting appropriate error diagnostics.
298/// FIXME: verify the conversion rules for "complex int" are consistent with
299/// GCC.
300QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
301 bool isCompAssign) {
Eli Friedman3cd92882009-03-28 01:22:36 +0000302 if (!isCompAssign)
Chris Lattner299b8842008-07-25 21:10:04 +0000303 UsualUnaryConversions(lhsExpr);
Eli Friedman3cd92882009-03-28 01:22:36 +0000304
305 UsualUnaryConversions(rhsExpr);
Douglas Gregor70d26122008-11-12 17:17:38 +0000306
Chris Lattner299b8842008-07-25 21:10:04 +0000307 // For conversion purposes, we ignore any qualifiers.
308 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000309 QualType lhs =
310 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
311 QualType rhs =
312 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000313
314 // If both types are identical, no conversion is needed.
315 if (lhs == rhs)
316 return lhs;
317
318 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
319 // The caller can deal with this (e.g. pointer + int).
320 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
321 return lhs;
322
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000323 // Perform bitfield promotions.
Eli Friedman1931cc82009-08-20 04:21:42 +0000324 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000325 if (!LHSBitfieldPromoteTy.isNull())
326 lhs = LHSBitfieldPromoteTy;
Eli Friedman1931cc82009-08-20 04:21:42 +0000327 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000328 if (!RHSBitfieldPromoteTy.isNull())
329 rhs = RHSBitfieldPromoteTy;
330
Eli Friedman6ae7d112009-08-19 07:44:53 +0000331 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman3cd92882009-03-28 01:22:36 +0000332 if (!isCompAssign)
Douglas Gregor70d26122008-11-12 17:17:38 +0000333 ImpCastExprToType(lhsExpr, destType);
Eli Friedman3cd92882009-03-28 01:22:36 +0000334 ImpCastExprToType(rhsExpr, destType);
Douglas Gregor70d26122008-11-12 17:17:38 +0000335 return destType;
336}
337
Chris Lattner299b8842008-07-25 21:10:04 +0000338//===----------------------------------------------------------------------===//
339// Semantic Analysis for various Expression Types
340//===----------------------------------------------------------------------===//
341
342
Steve Naroff87d58b42007-09-16 03:34:24 +0000343/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000344/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
345/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
346/// multiple tokens. However, the common case is that StringToks points to one
347/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000348///
349Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000350Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000351 assert(NumStringToks && "Must have at least one string!");
352
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000353 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000354 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000355 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000356
357 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
358 for (unsigned i = 0; i != NumStringToks; ++i)
359 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000360
Chris Lattnera6dcce32008-02-11 00:02:17 +0000361 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000362 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000363 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000364
365 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
366 if (getLangOptions().CPlusPlus)
367 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000368
Chris Lattnera6dcce32008-02-11 00:02:17 +0000369 // Get an array type for the string, according to C99 6.4.5. This includes
370 // the nul terminator character as well as the string length for pascal
371 // strings.
372 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattner14032222009-02-26 23:01:51 +0000373 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000374 ArrayType::Normal, 0);
Chris Lattnerc3144742009-02-18 05:49:11 +0000375
Chris Lattner4b009652007-07-25 00:24:17 +0000376 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattneraa491192009-02-18 06:40:38 +0000377 return Owned(StringLiteral::Create(Context, Literal.GetString(),
378 Literal.GetStringLength(),
379 Literal.AnyWide, StrTy,
380 &StringTokLocs[0],
381 StringTokLocs.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000382}
383
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000384/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
385/// CurBlock to VD should cause it to be snapshotted (as we do for auto
386/// variables defined outside the block) or false if this is not needed (e.g.
387/// for values inside the block or for globals).
388///
Chris Lattner0b464252009-04-21 22:26:47 +0000389/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
390/// up-to-date.
391///
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000392static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
393 ValueDecl *VD) {
394 // If the value is defined inside the block, we couldn't snapshot it even if
395 // we wanted to.
396 if (CurBlock->TheDecl == VD->getDeclContext())
397 return false;
398
399 // If this is an enum constant or function, it is constant, don't snapshot.
400 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
401 return false;
402
403 // If this is a reference to an extern, static, or global variable, no need to
404 // snapshot it.
405 // FIXME: What about 'const' variables in C++?
406 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner0b464252009-04-21 22:26:47 +0000407 if (!Var->hasLocalStorage())
408 return false;
409
410 // Blocks that have these can't be constant.
411 CurBlock->hasBlockDeclRefExprs = true;
412
413 // If we have nested blocks, the decl may be declared in an outer block (in
414 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
415 // be defined outside all of the current blocks (in which case the blocks do
416 // all get the bit). Walk the nesting chain.
417 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
418 NextBlock = NextBlock->PrevBlockInfo) {
419 // If we found the defining block for the variable, don't mark the block as
420 // having a reference outside it.
421 if (NextBlock->TheDecl == VD->getDeclContext())
422 break;
423
424 // Otherwise, the DeclRef from the inner block causes the outer one to need
425 // a snapshot as well.
426 NextBlock->hasBlockDeclRefExprs = true;
427 }
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000428
429 return true;
430}
431
432
433
Steve Naroff0acc9c92007-09-15 18:49:24 +0000434/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000435/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000436/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000437/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000438/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000439Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
440 IdentifierInfo &II,
441 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000442 const CXXScopeSpec *SS,
443 bool isAddressOfOperand) {
444 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000445 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000446}
447
Douglas Gregor566782a2009-01-06 05:10:23 +0000448/// BuildDeclRefExpr - Build either a DeclRefExpr or a
449/// QualifiedDeclRefExpr based on whether or not SS is a
450/// nested-name-specifier.
Anders Carlsson4571d812009-06-24 00:10:43 +0000451Sema::OwningExprResult
Sebastian Redl0c9da212009-02-03 20:19:35 +0000452Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
453 bool TypeDependent, bool ValueDependent,
454 const CXXScopeSpec *SS) {
Anders Carlsson9bd48662009-06-26 19:16:07 +0000455 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
456 Diag(Loc,
457 diag::err_auto_variable_cannot_appear_in_own_initializer)
458 << D->getDeclName();
459 return ExprError();
460 }
Anders Carlsson4571d812009-06-24 00:10:43 +0000461
462 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
463 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
464 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
465 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
466 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
467 << D->getIdentifier() << FD->getDeclName();
468 Diag(D->getLocation(), diag::note_local_variable_declared_here)
469 << D->getIdentifier();
470 return ExprError();
471 }
472 }
473 }
474 }
475
Douglas Gregor98189262009-06-19 23:52:42 +0000476 MarkDeclarationReferenced(Loc, D);
Anders Carlsson4571d812009-06-24 00:10:43 +0000477
478 Expr *E;
Douglas Gregor7e508262009-03-19 03:51:16 +0000479 if (SS && !SS->isEmpty()) {
Anders Carlsson4571d812009-06-24 00:10:43 +0000480 E = new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
481 ValueDependent, SS->getRange(),
Douglas Gregor041e9292009-03-26 23:56:24 +0000482 static_cast<NestedNameSpecifier *>(SS->getScopeRep()));
Douglas Gregor7e508262009-03-19 03:51:16 +0000483 } else
Anders Carlsson4571d812009-06-24 00:10:43 +0000484 E = new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
485
486 return Owned(E);
Douglas Gregor566782a2009-01-06 05:10:23 +0000487}
488
Douglas Gregor723d3332009-01-07 00:43:41 +0000489/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
490/// variable corresponding to the anonymous union or struct whose type
491/// is Record.
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000492static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
493 RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000494 assert(Record->isAnonymousStructOrUnion() &&
495 "Record must be an anonymous struct or union!");
496
Mike Stumpe127ae32009-05-16 07:39:55 +0000497 // FIXME: Once Decls are directly linked together, this will be an O(1)
498 // operation rather than a slow walk through DeclContext's vector (which
499 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregor723d3332009-01-07 00:43:41 +0000500 DeclContext *Ctx = Record->getDeclContext();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000501 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
502 DEnd = Ctx->decls_end();
Douglas Gregor723d3332009-01-07 00:43:41 +0000503 D != DEnd; ++D) {
504 if (*D == Record) {
505 // The object for the anonymous struct/union directly
506 // follows its type in the list of declarations.
507 ++D;
508 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000509 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000510 return *D;
511 }
512 }
513
514 assert(false && "Missing object for anonymous record");
515 return 0;
516}
517
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000518/// \brief Given a field that represents a member of an anonymous
519/// struct/union, build the path from that field's context to the
520/// actual member.
521///
522/// Construct the sequence of field member references we'll have to
523/// perform to get to the field in the anonymous union/struct. The
524/// list of members is built from the field outward, so traverse it
525/// backwards to go from an object in the current context to the field
526/// we found.
527///
528/// \returns The variable from which the field access should begin,
529/// for an anonymous struct/union that is not a member of another
530/// class. Otherwise, returns NULL.
531VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
532 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000533 assert(Field->getDeclContext()->isRecord() &&
534 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
535 && "Field must be stored inside an anonymous struct or union");
536
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000537 Path.push_back(Field);
Douglas Gregor723d3332009-01-07 00:43:41 +0000538 VarDecl *BaseObject = 0;
539 DeclContext *Ctx = Field->getDeclContext();
540 do {
541 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000542 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000543 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000544 Path.push_back(AnonField);
Douglas Gregor723d3332009-01-07 00:43:41 +0000545 else {
546 BaseObject = cast<VarDecl>(AnonObject);
547 break;
548 }
549 Ctx = Ctx->getParent();
550 } while (Ctx->isRecord() &&
551 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000552
553 return BaseObject;
554}
555
556Sema::OwningExprResult
557Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
558 FieldDecl *Field,
559 Expr *BaseObjectExpr,
560 SourceLocation OpLoc) {
561 llvm::SmallVector<FieldDecl *, 4> AnonFields;
562 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
563 AnonFields);
564
Douglas Gregor723d3332009-01-07 00:43:41 +0000565 // Build the expression that refers to the base object, from
566 // which we will build a sequence of member references to each
567 // of the anonymous union objects and, eventually, the field we
568 // found via name lookup.
569 bool BaseObjectIsPointer = false;
570 unsigned ExtraQuals = 0;
571 if (BaseObject) {
572 // BaseObject is an anonymous struct/union variable (and is,
573 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000574 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregor98189262009-06-19 23:52:42 +0000575 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff774e4152009-01-21 00:14:39 +0000576 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump9afab102009-02-19 03:04:26 +0000577 SourceLocation());
Douglas Gregor723d3332009-01-07 00:43:41 +0000578 ExtraQuals
579 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
580 } else if (BaseObjectExpr) {
581 // The caller provided the base object expression. Determine
582 // whether its a pointer and whether it adds any qualifiers to the
583 // anonymous struct/union fields we're looking into.
584 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000585 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000586 BaseObjectIsPointer = true;
587 ObjectType = ObjectPtr->getPointeeType();
588 }
589 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
590 } else {
591 // We've found a member of an anonymous struct/union that is
592 // inside a non-anonymous struct/union, so in a well-formed
593 // program our base object expression is "this".
594 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
595 if (!MD->isStatic()) {
596 QualType AnonFieldType
597 = Context.getTagDeclType(
598 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
599 QualType ThisType = Context.getTagDeclType(MD->getParent());
600 if ((Context.getCanonicalType(AnonFieldType)
601 == Context.getCanonicalType(ThisType)) ||
602 IsDerivedFrom(ThisType, AnonFieldType)) {
603 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000604 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000605 MD->getThisType(Context));
Douglas Gregor723d3332009-01-07 00:43:41 +0000606 BaseObjectIsPointer = true;
607 }
608 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000609 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
610 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000611 }
612 ExtraQuals = MD->getTypeQualifiers();
613 }
614
615 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000616 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
617 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000618 }
619
620 // Build the implicit member references to the field of the
621 // anonymous struct/union.
622 Expr *Result = BaseObjectExpr;
Mon P Wang04d89cb2009-07-22 03:08:17 +0000623 unsigned BaseAddrSpace = BaseObjectExpr->getType().getAddressSpace();
Douglas Gregor723d3332009-01-07 00:43:41 +0000624 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
625 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
626 FI != FIEnd; ++FI) {
627 QualType MemberType = (*FI)->getType();
628 if (!(*FI)->isMutable()) {
629 unsigned combinedQualifiers
630 = MemberType.getCVRQualifiers() | ExtraQuals;
631 MemberType = MemberType.getQualifiedType(combinedQualifiers);
632 }
Mon P Wang04d89cb2009-07-22 03:08:17 +0000633 if (BaseAddrSpace != MemberType.getAddressSpace())
634 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor98189262009-06-19 23:52:42 +0000635 MarkDeclarationReferenced(Loc, *FI);
Douglas Gregore399ad42009-08-26 22:36:53 +0000636 // FIXME: Might this end up being a qualified name?
Steve Naroff774e4152009-01-21 00:14:39 +0000637 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
638 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000639 BaseObjectIsPointer = false;
640 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregor723d3332009-01-07 00:43:41 +0000641 }
642
Sebastian Redlcd883f72009-01-18 18:53:16 +0000643 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000644}
645
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000646/// ActOnDeclarationNameExpr - The parser has read some kind of name
647/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
648/// performs lookup on that name and returns an expression that refers
649/// to that name. This routine isn't directly called from the parser,
650/// because the parser doesn't know about DeclarationName. Rather,
651/// this routine is called by ActOnIdentifierExpr,
652/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
653/// which form the DeclarationName from the corresponding syntactic
654/// forms.
655///
656/// HasTrailingLParen indicates whether this identifier is used in a
657/// function call context. LookupCtx is only used for a C++
658/// qualified-id (foo::bar) to indicate the class or namespace that
659/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000660///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000661/// isAddressOfOperand means that this expression is the direct operand
662/// of an address-of operator. This matters because this is the only
663/// situation where a qualified name referencing a non-static member may
664/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000665Sema::OwningExprResult
666Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
667 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000668 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000669 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000670 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000671 if (SS && SS->isInvalid())
672 return ExprError();
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000673
674 // C++ [temp.dep.expr]p3:
675 // An id-expression is type-dependent if it contains:
676 // -- a nested-name-specifier that contains a class-name that
677 // names a dependent type.
Douglas Gregorf3a200f2009-05-29 14:49:33 +0000678 // FIXME: Member of the current instantiation.
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000679 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000680 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
681 Loc, SS->getRange(),
Anders Carlsson4e8d5692009-07-09 00:05:08 +0000682 static_cast<NestedNameSpecifier *>(SS->getScopeRep()),
683 isAddressOfOperand));
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000684 }
685
Douglas Gregor411889e2009-02-13 23:20:09 +0000686 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
687 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000688
Sebastian Redlcd883f72009-01-18 18:53:16 +0000689 if (Lookup.isAmbiguous()) {
690 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
691 SS && SS->isSet() ? SS->getRange()
692 : SourceRange());
693 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000694 }
695
696 NamedDecl *D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000697
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000698 // If this reference is in an Objective-C method, then ivar lookup happens as
699 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000700 IdentifierInfo *II = Name.getAsIdentifierInfo();
701 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000702 // There are two cases to handle here. 1) scoped lookup could have failed,
703 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000704 // found a decl, but that decl is outside the current instance method (i.e.
705 // a global variable). In these two cases, we do a lookup for an ivar with
706 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000707 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000708 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000709 ObjCInterfaceDecl *ClassDeclared;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000710 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000711 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000712 if (DiagnoseUseOfDecl(IV, Loc))
713 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000714
715 // If we're referencing an invalid decl, just return this as a silent
716 // error node. The error diagnostic was already emitted on the decl.
717 if (IV->isInvalidDecl())
718 return ExprError();
719
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000720 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
721 // If a class method attemps to use a free standing ivar, this is
722 // an error.
723 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
724 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
725 << IV->getDeclName());
726 // If a class method uses a global variable, even if an ivar with
727 // same name exists, use the global.
728 if (!IsClsMethod) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000729 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
730 ClassDeclared != IFace)
731 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Mike Stumpe127ae32009-05-16 07:39:55 +0000732 // FIXME: This should use a new expr for a direct reference, don't
733 // turn this into Self->ivar, just return a BareIVarExpr or something.
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000734 IdentifierInfo &II = Context.Idents.get("self");
Argiris Kirtzidis3bb49042009-07-18 08:49:37 +0000735 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, SourceLocation(),
736 II, false);
Douglas Gregor98189262009-06-19 23:52:42 +0000737 MarkDeclarationReferenced(Loc, IV);
Daniel Dunbarf5254bd2009-04-21 01:19:28 +0000738 return Owned(new (Context)
739 ObjCIvarRefExpr(IV, IV->getType(), Loc,
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000740 SelfExpr.takeAs<Expr>(), true, true));
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000741 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000742 }
Mike Stump90fc78e2009-08-04 21:02:39 +0000743 } else if (getCurMethodDecl()->isInstanceMethod()) {
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000744 // We should warn if a local variable hides an ivar.
745 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000746 ObjCInterfaceDecl *ClassDeclared;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000747 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000748 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
749 IFace == ClassDeclared)
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000750 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000751 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000752 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000753 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000754 if (D == 0 && II->isStr("super")) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000755 QualType T;
756
757 if (getCurMethodDecl()->isInstanceMethod())
Steve Naroff329ec222009-07-10 23:34:53 +0000758 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
759 getCurMethodDecl()->getClassInterface()));
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000760 else
761 T = Context.getObjCClassType();
Steve Naroff774e4152009-01-21 00:14:39 +0000762 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000763 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000764 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000765
Douglas Gregoraa57e862009-02-18 21:56:37 +0000766 // Determine whether this name might be a candidate for
767 // argument-dependent lookup.
768 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
769 HasTrailingLParen;
770
771 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000772 // We've seen something of the form
773 //
774 // identifier(
775 //
776 // and we did not find any entity by the name
777 // "identifier". However, this identifier is still subject to
778 // argument-dependent lookup, so keep track of the name.
779 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
780 Context.OverloadTy,
781 Loc));
782 }
783
Chris Lattner4b009652007-07-25 00:24:17 +0000784 if (D == 0) {
785 // Otherwise, this could be an implicitly declared function reference (legal
786 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000787 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000788 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000789 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000790 else {
791 // If this name wasn't predeclared and if this is not a function call,
792 // diagnose the problem.
Anders Carlsson4355a392009-08-30 00:54:35 +0000793 if (SS && !SS->isEmpty()) {
794 DiagnoseMissingMember(Loc, Name,
795 (NestedNameSpecifier *)SS->getScopeRep(),
796 SS->getRange());
797 return ExprError();
798 } else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000799 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000800 return ExprError(Diag(Loc, diag::err_undeclared_use)
801 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000802 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000803 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000804 }
805 }
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000806
807 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
808 // Warn about constructs like:
809 // if (void *X = foo()) { ... } else { X }.
810 // In the else block, the pointer is always false.
811
812 // FIXME: In a template instantiation, we don't have scope
813 // information to check this property.
814 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
815 Scope *CheckS = S;
816 while (CheckS) {
817 if (CheckS->isWithinElse() &&
818 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
819 if (Var->getType()->isBooleanType())
820 ExprError(Diag(Loc, diag::warn_value_always_false)
821 << Var->getDeclName());
822 else
823 ExprError(Diag(Loc, diag::warn_value_always_zero)
824 << Var->getDeclName());
825 break;
826 }
827
828 // Move up one more control parent to check again.
829 CheckS = CheckS->getControlParent();
830 if (CheckS)
831 CheckS = CheckS->getParent();
832 }
833 }
834 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
835 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
836 // C99 DR 316 says that, if a function type comes from a
837 // function definition (without a prototype), that type is only
838 // used for checking compatibility. Therefore, when referencing
839 // the function, we pretend that we don't have the full function
840 // type.
841 if (DiagnoseUseOfDecl(Func, Loc))
842 return ExprError();
Douglas Gregor723d3332009-01-07 00:43:41 +0000843
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000844 QualType T = Func->getType();
845 QualType NoProtoType = T;
846 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
847 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
848 return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
849 }
850 }
851
852 return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand);
853}
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000854/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanian843336e2009-07-29 19:40:11 +0000855bool
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000856Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
857 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
858 if (CXXRecordDecl *RD =
859 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
860 QualType DestType =
861 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000862 if (DestType->isDependentType() || From->getType()->isDependentType())
863 return false;
864 QualType FromRecordType = From->getType();
865 QualType DestRecordType = DestType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000866 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000867 DestType = Context.getPointerType(DestType);
868 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000869 }
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000870 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
871 CheckDerivedToBaseConversion(FromRecordType,
872 DestRecordType,
873 From->getSourceRange().getBegin(),
874 From->getSourceRange()))
875 return true;
Anders Carlsson85186942009-07-31 01:23:52 +0000876 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
877 /*isLvalue=*/true);
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000878 }
Fariborz Jahanian843336e2009-07-29 19:40:11 +0000879 return false;
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000880}
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000881
Douglas Gregorc1991bf2009-08-31 23:41:50 +0000882/// \brief Build a MemberExpr AST node.
Douglas Gregore399ad42009-08-26 22:36:53 +0000883static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
884 const CXXScopeSpec *SS, NamedDecl *Member,
885 SourceLocation Loc, QualType Ty) {
886 if (SS && SS->isSet())
Douglas Gregorc1991bf2009-08-31 23:41:50 +0000887 return MemberExpr::Create(C, Base, isArrow,
888 (NestedNameSpecifier *)SS->getScopeRep(),
Douglas Gregord33e3282009-09-01 00:37:14 +0000889 SS->getRange(), Member, Loc,
890 // FIXME: Explicit template argument lists
891 false, SourceLocation(), 0, 0, SourceLocation(),
892 Ty);
Douglas Gregore399ad42009-08-26 22:36:53 +0000893
894 return new (C) MemberExpr(Base, isArrow, Member, Loc, Ty);
895}
896
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000897/// \brief Complete semantic analysis for a reference to the given declaration.
898Sema::OwningExprResult
899Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
900 bool HasTrailingLParen,
901 const CXXScopeSpec *SS,
902 bool isAddressOfOperand) {
903 assert(D && "Cannot refer to a NULL declaration");
904 DeclarationName Name = D->getDeclName();
905
Sebastian Redl0c9da212009-02-03 20:19:35 +0000906 // If this is an expression of the form &Class::member, don't build an
907 // implicit member ref, because we want a pointer to the member in general,
908 // not any specific instance's member.
909 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000910 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor09be81b2009-02-04 17:27:36 +0000911 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000912 QualType DType;
913 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
914 DType = FD->getType().getNonReferenceType();
915 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
916 DType = Method->getType();
917 } else if (isa<OverloadedFunctionDecl>(D)) {
918 DType = Context.OverloadTy;
919 }
920 // Could be an inner type. That's diagnosed below, so ignore it here.
921 if (!DType.isNull()) {
922 // The pointer is type- and value-dependent if it points into something
923 // dependent.
Douglas Gregorf3a200f2009-05-29 14:49:33 +0000924 bool Dependent = DC->isDependentContext();
Anders Carlsson4571d812009-06-24 00:10:43 +0000925 return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
Sebastian Redl0c9da212009-02-03 20:19:35 +0000926 }
927 }
928 }
929
Douglas Gregor723d3332009-01-07 00:43:41 +0000930 // We may have found a field within an anonymous union or struct
931 // (C++ [class.union]).
932 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
933 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
934 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000935
Douglas Gregor3257fb52008-12-22 05:46:06 +0000936 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
937 if (!MD->isStatic()) {
938 // C++ [class.mfct.nonstatic]p2:
939 // [...] if name lookup (3.4.1) resolves the name in the
940 // id-expression to a nonstatic nontype member of class X or of
941 // a base class of X, the id-expression is transformed into a
942 // class member access expression (5.2.5) using (*this) (9.3.2)
943 // as the postfix-expression to the left of the '.' operator.
944 DeclContext *Ctx = 0;
945 QualType MemberType;
946 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
947 Ctx = FD->getDeclContext();
948 MemberType = FD->getType();
949
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000950 if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
Douglas Gregor3257fb52008-12-22 05:46:06 +0000951 MemberType = RefType->getPointeeType();
952 else if (!FD->isMutable()) {
953 unsigned combinedQualifiers
954 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
955 MemberType = MemberType.getQualifiedType(combinedQualifiers);
956 }
957 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
958 if (!Method->isStatic()) {
959 Ctx = Method->getParent();
960 MemberType = Method->getType();
961 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000962 } else if (FunctionTemplateDecl *FunTmpl
963 = dyn_cast<FunctionTemplateDecl>(D)) {
964 if (CXXMethodDecl *Method
965 = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())) {
966 if (!Method->isStatic()) {
967 Ctx = Method->getParent();
968 MemberType = Context.OverloadTy;
969 }
970 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000971 } else if (OverloadedFunctionDecl *Ovl
972 = dyn_cast<OverloadedFunctionDecl>(D)) {
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000973 // FIXME: We need an abstraction for iterating over one or more function
974 // templates or functions. This code is far too repetitive!
Douglas Gregor3257fb52008-12-22 05:46:06 +0000975 for (OverloadedFunctionDecl::function_iterator
976 Func = Ovl->function_begin(),
977 FuncEnd = Ovl->function_end();
978 Func != FuncEnd; ++Func) {
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000979 CXXMethodDecl *DMethod = 0;
980 if (FunctionTemplateDecl *FunTmpl
981 = dyn_cast<FunctionTemplateDecl>(*Func))
982 DMethod = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
983 else
984 DMethod = dyn_cast<CXXMethodDecl>(*Func);
985
986 if (DMethod && !DMethod->isStatic()) {
987 Ctx = DMethod->getDeclContext();
988 MemberType = Context.OverloadTy;
989 break;
990 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000991 }
992 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000993
994 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000995 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
996 QualType ThisType = Context.getTagDeclType(MD->getParent());
997 if ((Context.getCanonicalType(CtxType)
998 == Context.getCanonicalType(ThisType)) ||
999 IsDerivedFrom(ThisType, CtxType)) {
1000 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +00001001 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +00001002 MD->getThisType(Context));
Douglas Gregor98189262009-06-19 23:52:42 +00001003 MarkDeclarationReferenced(Loc, D);
Fariborz Jahanian843336e2009-07-29 19:40:11 +00001004 if (PerformObjectMemberConversion(This, D))
1005 return ExprError();
Anders Carlsson9fbe6872009-08-08 16:55:18 +00001006 if (DiagnoseUseOfDecl(D, Loc))
1007 return ExprError();
Douglas Gregore399ad42009-08-26 22:36:53 +00001008 return Owned(BuildMemberExpr(Context, This, true, SS, D,
1009 Loc, MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001010 }
1011 }
1012 }
1013 }
1014
Douglas Gregor8acb7272008-12-11 16:49:14 +00001015 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001016 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1017 if (MD->isStatic())
1018 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +00001019 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
1020 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001021 }
1022
Douglas Gregor3257fb52008-12-22 05:46:06 +00001023 // Any other ways we could have found the field in a well-formed
1024 // program would have been turned into implicit member expressions
1025 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001026 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
1027 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001028 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00001029
Chris Lattner4b009652007-07-25 00:24:17 +00001030 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001031 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +00001032 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001033 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001034 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001035 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +00001036
Steve Naroffd6163f32008-09-05 22:11:13 +00001037 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +00001038 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001039 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
1040 false, false, SS);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001041 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001042 return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
1043 false, false, SS);
Anders Carlsson89908542009-08-29 01:06:32 +00001044 else if (UnresolvedUsingDecl *UD = dyn_cast<UnresolvedUsingDecl>(D))
1045 return BuildDeclRefExpr(UD, Context.DependentTy, Loc,
1046 /*TypeDependent=*/true,
1047 /*ValueDependent=*/true, SS);
1048
Steve Naroffd6163f32008-09-05 22:11:13 +00001049 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001050
Douglas Gregoraa57e862009-02-18 21:56:37 +00001051 // Check whether this declaration can be used. Note that we suppress
1052 // this check when we're going to perform argument-dependent lookup
1053 // on this function name, because this might not be the function
1054 // that overload resolution actually selects.
Douglas Gregor6ef403d2009-06-30 15:47:41 +00001055 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
1056 HasTrailingLParen;
Douglas Gregoraa57e862009-02-18 21:56:37 +00001057 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1058 return ExprError();
1059
Steve Naroffd6163f32008-09-05 22:11:13 +00001060 // Only create DeclRefExpr's for valid Decl's.
1061 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001062 return ExprError();
1063
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001064 // If the identifier reference is inside a block, and it refers to a value
1065 // that is outside the block, create a BlockDeclRefExpr instead of a
1066 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1067 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +00001068 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001069 // We do not do this for things like enum constants, global variables, etc,
1070 // as they do not get snapshotted.
1071 //
1072 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregor98189262009-06-19 23:52:42 +00001073 MarkDeclarationReferenced(Loc, VD);
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001074 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff52059382008-10-10 01:28:17 +00001075 // The BlocksAttr indicates the variable is bound by-reference.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00001076 if (VD->getAttr<BlocksAttr>())
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001077 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001078 // This is to record that a 'const' was actually synthesize and added.
1079 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff52059382008-10-10 01:28:17 +00001080 // Variable will be bound by-copy, make it const within the closure.
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001081
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001082 ExprTy.addConst();
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001083 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
1084 constAdded));
Steve Naroff52059382008-10-10 01:28:17 +00001085 }
1086 // If this reference is not in a block or if the referenced variable is
1087 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001088
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001089 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +00001090 bool ValueDependent = false;
1091 if (getLangOptions().CPlusPlus) {
1092 // C++ [temp.dep.expr]p3:
1093 // An id-expression is type-dependent if it contains:
1094 // - an identifier that was declared with a dependent type,
1095 if (VD->getType()->isDependentType())
1096 TypeDependent = true;
1097 // - FIXME: a template-id that is dependent,
1098 // - a conversion-function-id that specifies a dependent type,
1099 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1100 Name.getCXXNameType()->isDependentType())
1101 TypeDependent = true;
1102 // - a nested-name-specifier that contains a class-name that
1103 // names a dependent type.
1104 else if (SS && !SS->isEmpty()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001105 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregora5d84612008-12-10 20:57:37 +00001106 DC; DC = DC->getParent()) {
1107 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +00001108 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +00001109 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1110 if (Context.getTypeDeclType(Record)->isDependentType()) {
1111 TypeDependent = true;
1112 break;
1113 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001114 }
1115 }
1116 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001117
Douglas Gregora5d84612008-12-10 20:57:37 +00001118 // C++ [temp.dep.constexpr]p2:
1119 //
1120 // An identifier is value-dependent if it is:
1121 // - a name declared with a dependent type,
1122 if (TypeDependent)
1123 ValueDependent = true;
1124 // - the name of a non-type template parameter,
1125 else if (isa<NonTypeTemplateParmDecl>(VD))
1126 ValueDependent = true;
1127 // - a constant with integral or enumeration type and is
1128 // initialized with an expression that is value-dependent
Eli Friedman1f7744a2009-06-11 01:11:20 +00001129 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
1130 if (Dcl->getType().getCVRQualifiers() == QualType::Const &&
1131 Dcl->getInit()) {
1132 ValueDependent = Dcl->getInit()->isValueDependent();
1133 }
1134 }
Douglas Gregora5d84612008-12-10 20:57:37 +00001135 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001136
Anders Carlsson4571d812009-06-24 00:10:43 +00001137 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1138 TypeDependent, ValueDependent, SS);
Chris Lattner4b009652007-07-25 00:24:17 +00001139}
1140
Sebastian Redlcd883f72009-01-18 18:53:16 +00001141Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1142 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +00001143 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001144
Chris Lattner4b009652007-07-25 00:24:17 +00001145 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001146 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +00001147 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1148 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1149 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001150 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001151
Chris Lattner7e637512008-01-12 08:14:25 +00001152 // Pre-defined identifiers are of type char[x], where x is the length of the
1153 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001154 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +00001155 if (FunctionDecl *FD = getCurFunctionDecl())
1156 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +00001157 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1158 Length = MD->getSynthesizedMethodSize();
1159 else {
1160 Diag(Loc, diag::ext_predef_outside_function);
1161 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1162 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1163 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001164
1165
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001166 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001167 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001168 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +00001169 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +00001170}
1171
Sebastian Redlcd883f72009-01-18 18:53:16 +00001172Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +00001173 llvm::SmallString<16> CharBuffer;
1174 CharBuffer.resize(Tok.getLength());
1175 const char *ThisTokBegin = &CharBuffer[0];
1176 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001177
Chris Lattner4b009652007-07-25 00:24:17 +00001178 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1179 Tok.getLocation(), PP);
1180 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001181 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001182
1183 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1184
Sebastian Redl75324932009-01-20 22:23:13 +00001185 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1186 Literal.isWide(),
1187 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001188}
1189
Sebastian Redlcd883f72009-01-18 18:53:16 +00001190Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1191 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001192 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1193 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001194 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001195 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001196 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001197 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001198 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001199
Chris Lattner4b009652007-07-25 00:24:17 +00001200 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001201 // Add padding so that NumericLiteralParser can overread by one character.
1202 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001203 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001204
Chris Lattner4b009652007-07-25 00:24:17 +00001205 // Get the spelling of the token, which eliminates trigraphs, etc.
1206 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001207
Chris Lattner4b009652007-07-25 00:24:17 +00001208 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1209 Tok.getLocation(), PP);
1210 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001211 return ExprError();
1212
Chris Lattner1de66eb2007-08-26 03:42:43 +00001213 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001214
Chris Lattner1de66eb2007-08-26 03:42:43 +00001215 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001216 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001217 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001218 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001219 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001220 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001221 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001222 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001223
1224 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1225
Ted Kremenekddedbe22007-11-29 00:56:49 +00001226 // isExact will be set by GetFloatValue().
1227 bool isExact = false;
Chris Lattnerff1bf1a2009-06-29 17:34:55 +00001228 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1229 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001230
Chris Lattner1de66eb2007-08-26 03:42:43 +00001231 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001232 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001233 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001234 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001235
Neil Booth7421e9c2007-08-29 22:00:19 +00001236 // long long is a C99 feature.
1237 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001238 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001239 Diag(Tok.getLocation(), diag::ext_longlong);
1240
Chris Lattner4b009652007-07-25 00:24:17 +00001241 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001242 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001243
Chris Lattner4b009652007-07-25 00:24:17 +00001244 if (Literal.GetIntegerValue(ResultVal)) {
1245 // If this value didn't fit into uintmax_t, warn and force to ull.
1246 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001247 Ty = Context.UnsignedLongLongTy;
1248 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001249 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001250 } else {
1251 // If this value fits into a ULL, try to figure out what else it fits into
1252 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001253
Chris Lattner4b009652007-07-25 00:24:17 +00001254 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1255 // be an unsigned int.
1256 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1257
1258 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001259 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001260 if (!Literal.isLong && !Literal.isLongLong) {
1261 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001262 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001263
Chris Lattner4b009652007-07-25 00:24:17 +00001264 // Does it fit in a unsigned int?
1265 if (ResultVal.isIntN(IntSize)) {
1266 // Does it fit in a signed int?
1267 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001268 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001269 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001270 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001271 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001272 }
Chris Lattner4b009652007-07-25 00:24:17 +00001273 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001274
Chris Lattner4b009652007-07-25 00:24:17 +00001275 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001276 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001277 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001278
Chris Lattner4b009652007-07-25 00:24:17 +00001279 // Does it fit in a unsigned long?
1280 if (ResultVal.isIntN(LongSize)) {
1281 // Does it fit in a signed long?
1282 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001283 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001284 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001285 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001286 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001287 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001288 }
1289
Chris Lattner4b009652007-07-25 00:24:17 +00001290 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001291 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001292 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001293
Chris Lattner4b009652007-07-25 00:24:17 +00001294 // Does it fit in a unsigned long long?
1295 if (ResultVal.isIntN(LongLongSize)) {
1296 // Does it fit in a signed long long?
1297 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001298 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001299 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001300 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001301 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001302 }
1303 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001304
Chris Lattner4b009652007-07-25 00:24:17 +00001305 // If we still couldn't decide a type, we probably have something that
1306 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001307 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001308 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001309 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001310 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001311 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001312
Chris Lattnere4068872008-05-09 05:59:00 +00001313 if (ResultVal.getBitWidth() != Width)
1314 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001315 }
Sebastian Redl75324932009-01-20 22:23:13 +00001316 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001317 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001318
Chris Lattner1de66eb2007-08-26 03:42:43 +00001319 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1320 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001321 Res = new (Context) ImaginaryLiteral(Res,
1322 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001323
1324 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001325}
1326
Sebastian Redlcd883f72009-01-18 18:53:16 +00001327Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1328 SourceLocation R, ExprArg Val) {
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001329 Expr *E = Val.takeAs<Expr>();
Chris Lattner48d7f382008-04-02 04:24:33 +00001330 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001331 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001332}
1333
1334/// The UsualUnaryConversions() function is *not* called by this routine.
1335/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001336bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001337 SourceLocation OpLoc,
1338 const SourceRange &ExprRange,
1339 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001340 if (exprType->isDependentType())
1341 return false;
1342
Chris Lattner4b009652007-07-25 00:24:17 +00001343 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001344 if (isa<FunctionType>(exprType)) {
Chris Lattner95933c12009-04-24 00:30:45 +00001345 // alignof(function) is allowed as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001346 if (isSizeof)
1347 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1348 return false;
1349 }
1350
Chris Lattner95933c12009-04-24 00:30:45 +00001351 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001352 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001353 Diag(OpLoc, diag::ext_sizeof_void_type)
1354 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001355 return false;
1356 }
Chris Lattnere1127c42009-04-21 19:55:16 +00001357
Chris Lattner95933c12009-04-24 00:30:45 +00001358 if (RequireCompleteType(OpLoc, exprType,
1359 isSizeof ? diag::err_sizeof_incomplete_type :
Anders Carlssona21e7872009-08-26 23:45:07 +00001360 PDiag(diag::err_alignof_incomplete_type)
1361 << ExprRange))
Chris Lattner95933c12009-04-24 00:30:45 +00001362 return true;
1363
1364 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianbf2b0952009-04-24 17:34:33 +00001365 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner95933c12009-04-24 00:30:45 +00001366 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnerf3ce8572009-04-24 22:30:50 +00001367 << exprType << isSizeof << ExprRange;
1368 return true;
Chris Lattnere1127c42009-04-21 19:55:16 +00001369 }
1370
Chris Lattner95933c12009-04-24 00:30:45 +00001371 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001372}
1373
Chris Lattner8d9f7962009-01-24 20:17:12 +00001374bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1375 const SourceRange &ExprRange) {
1376 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001377
Chris Lattner8d9f7962009-01-24 20:17:12 +00001378 // alignof decl is always ok.
1379 if (isa<DeclRefExpr>(E))
1380 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001381
1382 // Cannot know anything else if the expression is dependent.
1383 if (E->isTypeDependent())
1384 return false;
1385
Douglas Gregor531434b2009-05-02 02:18:30 +00001386 if (E->getBitField()) {
1387 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1388 return true;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001389 }
Douglas Gregor531434b2009-05-02 02:18:30 +00001390
1391 // Alignment of a field access is always okay, so long as it isn't a
1392 // bit-field.
1393 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump6eeaa782009-07-22 18:58:19 +00001394 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor531434b2009-05-02 02:18:30 +00001395 return false;
1396
Chris Lattner8d9f7962009-01-24 20:17:12 +00001397 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1398}
1399
Douglas Gregor396f1142009-03-13 21:01:28 +00001400/// \brief Build a sizeof or alignof expression given a type operand.
1401Action::OwningExprResult
1402Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1403 bool isSizeOf, SourceRange R) {
1404 if (T.isNull())
1405 return ExprError();
1406
1407 if (!T->isDependentType() &&
1408 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1409 return ExprError();
1410
1411 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1412 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1413 Context.getSizeType(), OpLoc,
1414 R.getEnd()));
1415}
1416
1417/// \brief Build a sizeof or alignof expression given an expression
1418/// operand.
1419Action::OwningExprResult
1420Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1421 bool isSizeOf, SourceRange R) {
1422 // Verify that the operand is valid.
1423 bool isInvalid = false;
1424 if (E->isTypeDependent()) {
1425 // Delay type-checking for type-dependent expressions.
1426 } else if (!isSizeOf) {
1427 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor531434b2009-05-02 02:18:30 +00001428 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor396f1142009-03-13 21:01:28 +00001429 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1430 isInvalid = true;
1431 } else {
1432 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1433 }
1434
1435 if (isInvalid)
1436 return ExprError();
1437
1438 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1439 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1440 Context.getSizeType(), OpLoc,
1441 R.getEnd()));
1442}
1443
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001444/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1445/// the same for @c alignof and @c __alignof
1446/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001447Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001448Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1449 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001450 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001451 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001452
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001453 if (isType) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00001454 // FIXME: Preserve type source info.
1455 QualType ArgTy = GetTypeFromParser(TyOrEx);
Douglas Gregor396f1142009-03-13 21:01:28 +00001456 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1457 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001458
Douglas Gregor396f1142009-03-13 21:01:28 +00001459 // Get the end location.
1460 Expr *ArgEx = (Expr *)TyOrEx;
1461 Action::OwningExprResult Result
1462 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1463
1464 if (Result.isInvalid())
1465 DeleteExpr(ArgEx);
1466
1467 return move(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001468}
1469
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001470QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001471 if (V->isTypeDependent())
1472 return Context.DependentTy;
Chris Lattner03931a72007-08-24 21:16:53 +00001473
Chris Lattnera16e42d2007-08-26 05:39:26 +00001474 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001475 if (const ComplexType *CT = V->getType()->getAsComplexType())
1476 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001477
1478 // Otherwise they pass through real integer and floating point types here.
1479 if (V->getType()->isArithmeticType())
1480 return V->getType();
1481
1482 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001483 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1484 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001485 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001486}
1487
1488
Chris Lattner4b009652007-07-25 00:24:17 +00001489
Sebastian Redl8b769972009-01-19 00:08:26 +00001490Action::OwningExprResult
1491Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1492 tok::TokenKind Kind, ExprArg Input) {
Nate Begemane85f43d2009-08-10 23:49:36 +00001493 // Since this might be a postfix expression, get rid of ParenListExprs.
1494 Input = MaybeConvertParenListExprToParenExpr(S, move(Input));
Sebastian Redl8b769972009-01-19 00:08:26 +00001495 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001496
Chris Lattner4b009652007-07-25 00:24:17 +00001497 UnaryOperator::Opcode Opc;
1498 switch (Kind) {
1499 default: assert(0 && "Unknown unary op!");
1500 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1501 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1502 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001503
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001504 if (getLangOptions().CPlusPlus &&
1505 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1506 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001507 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001508 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1509
1510 // C++ [over.inc]p1:
1511 //
1512 // [...] If the function is a member function with one
1513 // parameter (which shall be of type int) or a non-member
1514 // function with two parameters (the second of which shall be
1515 // of type int), it defines the postfix increment operator ++
1516 // for objects of that type. When the postfix increment is
1517 // called as a result of using the ++ operator, the int
1518 // argument will have value zero.
1519 Expr *Args[2] = {
1520 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001521 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1522 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001523 };
1524
1525 // Build the candidate set for overloading
1526 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001527 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001528
1529 // Perform overload resolution.
1530 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001531 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001532 case OR_Success: {
1533 // We found a built-in operator or an overloaded operator.
1534 FunctionDecl *FnDecl = Best->Function;
1535
1536 if (FnDecl) {
1537 // We matched an overloaded operator. Build a call to that
1538 // operator.
1539
1540 // Convert the arguments.
1541 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1542 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001543 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001544 } else {
1545 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001546 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001547 FnDecl->getParamDecl(0)->getType(),
1548 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001549 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001550 }
1551
1552 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001553 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001554 = FnDecl->getType()->getAsFunctionType()->getResultType();
1555 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001556
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001557 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001558 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001559 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001560 UsualUnaryConversions(FnExpr);
1561
Sebastian Redl8b769972009-01-19 00:08:26 +00001562 Input.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001563 Args[0] = Arg;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001564 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1565 Args, 2, ResultTy,
1566 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001567 } else {
1568 // We matched a built-in operator. Convert the arguments, then
1569 // break out so that we will build the appropriate built-in
1570 // operator node.
1571 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1572 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001573 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001574
1575 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001576 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001577 }
1578
1579 case OR_No_Viable_Function:
1580 // No viable function; fall through to handling this as a
1581 // built-in operator, which will produce an error message for us.
1582 break;
1583
1584 case OR_Ambiguous:
1585 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1586 << UnaryOperator::getOpcodeStr(Opc)
1587 << Arg->getSourceRange();
1588 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001589 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001590
1591 case OR_Deleted:
1592 Diag(OpLoc, diag::err_ovl_deleted_oper)
1593 << Best->Function->isDeleted()
1594 << UnaryOperator::getOpcodeStr(Opc)
1595 << Arg->getSourceRange();
1596 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1597 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001598 }
1599
1600 // Either we found no viable overloaded operator or we matched a
1601 // built-in operator. In either case, fall through to trying to
1602 // build a built-in operation.
1603 }
1604
Eli Friedman94d30952009-07-22 23:24:42 +00001605 Input.release();
1606 Input = Arg;
Eli Friedman79341142009-07-22 22:25:00 +00001607 return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
Chris Lattner4b009652007-07-25 00:24:17 +00001608}
1609
Sebastian Redl8b769972009-01-19 00:08:26 +00001610Action::OwningExprResult
1611Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1612 ExprArg Idx, SourceLocation RLoc) {
Nate Begemane85f43d2009-08-10 23:49:36 +00001613 // Since this might be a postfix expression, get rid of ParenListExprs.
1614 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1615
Sebastian Redl8b769972009-01-19 00:08:26 +00001616 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1617 *RHSExp = static_cast<Expr*>(Idx.get());
Nate Begemane85f43d2009-08-10 23:49:36 +00001618
Douglas Gregor80723c52008-11-19 17:17:41 +00001619 if (getLangOptions().CPlusPlus &&
Douglas Gregorde72f3e2009-05-19 00:01:19 +00001620 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1621 Base.release();
1622 Idx.release();
1623 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1624 Context.DependentTy, RLoc));
1625 }
1626
1627 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001628 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001629 LHSExp->getType()->isEnumeralType() ||
1630 RHSExp->getType()->isRecordType() ||
1631 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001632 // Add the appropriate overloaded operators (C++ [over.match.oper])
1633 // to the candidate set.
1634 OverloadCandidateSet CandidateSet;
1635 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001636 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1637 SourceRange(LLoc, RLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001638
Douglas Gregor80723c52008-11-19 17:17:41 +00001639 // Perform overload resolution.
1640 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001641 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001642 case OR_Success: {
1643 // We found a built-in operator or an overloaded operator.
1644 FunctionDecl *FnDecl = Best->Function;
1645
1646 if (FnDecl) {
1647 // We matched an overloaded operator. Build a call to that
1648 // operator.
1649
1650 // Convert the arguments.
1651 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1652 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1653 PerformCopyInitialization(RHSExp,
1654 FnDecl->getParamDecl(0)->getType(),
1655 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001656 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001657 } else {
1658 // Convert the arguments.
1659 if (PerformCopyInitialization(LHSExp,
1660 FnDecl->getParamDecl(0)->getType(),
1661 "passing") ||
1662 PerformCopyInitialization(RHSExp,
1663 FnDecl->getParamDecl(1)->getType(),
1664 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001665 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001666 }
1667
1668 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001669 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001670 = FnDecl->getType()->getAsFunctionType()->getResultType();
1671 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001672
Douglas Gregor80723c52008-11-19 17:17:41 +00001673 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001674 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1675 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001676 UsualUnaryConversions(FnExpr);
1677
Sebastian Redl8b769972009-01-19 00:08:26 +00001678 Base.release();
1679 Idx.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001680 Args[0] = LHSExp;
1681 Args[1] = RHSExp;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001682 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1683 FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001684 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001685 } else {
1686 // We matched a built-in operator. Convert the arguments, then
1687 // break out so that we will build the appropriate built-in
1688 // operator node.
1689 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1690 "passing") ||
1691 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1692 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001693 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001694
1695 break;
1696 }
1697 }
1698
1699 case OR_No_Viable_Function:
1700 // No viable function; fall through to handling this as a
1701 // built-in operator, which will produce an error message for us.
1702 break;
1703
1704 case OR_Ambiguous:
1705 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1706 << "[]"
1707 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1708 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001709 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001710
1711 case OR_Deleted:
1712 Diag(LLoc, diag::err_ovl_deleted_oper)
1713 << Best->Function->isDeleted()
1714 << "[]"
1715 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1716 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1717 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001718 }
1719
1720 // Either we found no viable overloaded operator or we matched a
1721 // built-in operator. In either case, fall through to trying to
1722 // build a built-in operation.
1723 }
1724
Chris Lattner4b009652007-07-25 00:24:17 +00001725 // Perform default conversions.
1726 DefaultFunctionArrayConversion(LHSExp);
1727 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001728
Chris Lattner4b009652007-07-25 00:24:17 +00001729 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1730
1731 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001732 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001733 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001734 // and index from the expression types.
1735 Expr *BaseExpr, *IndexExpr;
1736 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001737 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1738 BaseExpr = LHSExp;
1739 IndexExpr = RHSExp;
1740 ResultType = Context.DependentTy;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001741 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001742 BaseExpr = LHSExp;
1743 IndexExpr = RHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001744 ResultType = PTy->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001745 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001746 // Handle the uncommon case of "123[Ptr]".
1747 BaseExpr = RHSExp;
1748 IndexExpr = LHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001749 ResultType = PTy->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00001750 } else if (const ObjCObjectPointerType *PTy =
1751 LHSTy->getAsObjCObjectPointerType()) {
1752 BaseExpr = LHSExp;
1753 IndexExpr = RHSExp;
1754 ResultType = PTy->getPointeeType();
1755 } else if (const ObjCObjectPointerType *PTy =
1756 RHSTy->getAsObjCObjectPointerType()) {
1757 // Handle the uncommon case of "123[Ptr]".
1758 BaseExpr = RHSExp;
1759 IndexExpr = LHSExp;
1760 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001761 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1762 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001763 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001764
Chris Lattner4b009652007-07-25 00:24:17 +00001765 // FIXME: need to deal with const...
1766 ResultType = VTy->getElementType();
Eli Friedmand4614072009-04-25 23:46:54 +00001767 } else if (LHSTy->isArrayType()) {
1768 // If we see an array that wasn't promoted by
1769 // DefaultFunctionArrayConversion, it must be an array that
1770 // wasn't promoted because of the C90 rule that doesn't
1771 // allow promoting non-lvalue arrays. Warn, then
1772 // force the promotion here.
1773 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1774 LHSExp->getSourceRange();
1775 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1776 LHSTy = LHSExp->getType();
1777
1778 BaseExpr = LHSExp;
1779 IndexExpr = RHSExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001780 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmand4614072009-04-25 23:46:54 +00001781 } else if (RHSTy->isArrayType()) {
1782 // Same as previous, except for 123[f().a] case
1783 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1784 RHSExp->getSourceRange();
1785 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1786 RHSTy = RHSExp->getType();
1787
1788 BaseExpr = RHSExp;
1789 IndexExpr = LHSExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001790 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001791 } else {
Chris Lattner7264d212009-04-25 22:50:55 +00001792 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1793 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00001794 }
Chris Lattner4b009652007-07-25 00:24:17 +00001795 // C99 6.5.2.1p1
Nate Begemane85f43d2009-08-10 23:49:36 +00001796 if (!(IndexExpr->getType()->isIntegerType() &&
1797 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner7264d212009-04-25 22:50:55 +00001798 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1799 << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001800
Douglas Gregor05e28f62009-03-24 19:52:54 +00001801 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1802 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1803 // type. Note that Functions are not objects, and that (in C99 parlance)
1804 // incomplete types are not object types.
1805 if (ResultType->isFunctionType()) {
1806 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1807 << ResultType << BaseExpr->getSourceRange();
1808 return ExprError();
1809 }
Chris Lattner95933c12009-04-24 00:30:45 +00001810
Douglas Gregor05e28f62009-03-24 19:52:54 +00001811 if (!ResultType->isDependentType() &&
Anders Carlssona21e7872009-08-26 23:45:07 +00001812 RequireCompleteType(LLoc, ResultType,
1813 PDiag(diag::err_subscript_incomplete_type)
1814 << BaseExpr->getSourceRange()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00001815 return ExprError();
Chris Lattner95933c12009-04-24 00:30:45 +00001816
1817 // Diagnose bad cases where we step over interface counts.
1818 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1819 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1820 << ResultType << BaseExpr->getSourceRange();
1821 return ExprError();
1822 }
1823
Sebastian Redl8b769972009-01-19 00:08:26 +00001824 Base.release();
1825 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001826 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001827 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001828}
1829
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001830QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001831CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001832 const IdentifierInfo *CompName,
1833 SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001834 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001835
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001836 // The vector accessor can't exceed the number of elements.
Anders Carlsson9935ab92009-08-26 18:25:21 +00001837 const char *compStr = CompName->getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001838
Mike Stump9afab102009-02-19 03:04:26 +00001839 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001840 // special names that indicate a subset of exactly half the elements are
1841 // to be selected.
1842 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001843
Nate Begeman1486b502009-01-18 01:47:54 +00001844 // This flag determines whether or not CompName has an 's' char prefix,
1845 // indicating that it is a string of hex values to be used as vector indices.
Nate Begemane2ed6f72009-06-25 21:06:09 +00001846 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001847
1848 // Check that we've found one of the special components, or that the component
1849 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001850 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001851 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1852 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001853 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001854 do
1855 compStr++;
1856 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001857 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001858 do
1859 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001860 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001861 }
Nate Begeman1486b502009-01-18 01:47:54 +00001862
Mike Stump9afab102009-02-19 03:04:26 +00001863 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001864 // We didn't get to the end of the string. This means the component names
1865 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001866 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1867 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001868 return QualType();
1869 }
Mike Stump9afab102009-02-19 03:04:26 +00001870
Nate Begeman1486b502009-01-18 01:47:54 +00001871 // Ensure no component accessor exceeds the width of the vector type it
1872 // operates on.
1873 if (!HalvingSwizzle) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00001874 compStr = CompName->getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001875
1876 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001877 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001878
1879 while (*compStr) {
1880 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1881 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1882 << baseType << SourceRange(CompLoc);
1883 return QualType();
1884 }
1885 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001886 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001887
Nate Begeman1486b502009-01-18 01:47:54 +00001888 // If this is a halving swizzle, verify that the base type has an even
1889 // number of elements.
1890 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001891 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001892 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001893 return QualType();
1894 }
Mike Stump9afab102009-02-19 03:04:26 +00001895
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001896 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001897 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001898 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001899 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001900 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001901 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlsson9935ab92009-08-26 18:25:21 +00001902 : CompName->getLength();
Nate Begeman1486b502009-01-18 01:47:54 +00001903 if (HexSwizzle)
1904 CompSize--;
1905
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001906 if (CompSize == 1)
1907 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001908
Nate Begemanaf6ed502008-04-18 23:10:10 +00001909 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001910 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001911 // diagostics look bad. We want extended vector types to appear built-in.
1912 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1913 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1914 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001915 }
1916 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001917}
1918
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001919static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001920 IdentifierInfo *Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001921 const Selector &Sel,
1922 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001923
Anders Carlsson9935ab92009-08-26 18:25:21 +00001924 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001925 return PD;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001926 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001927 return OMD;
1928
1929 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1930 E = PDecl->protocol_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001931 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
1932 Context))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001933 return D;
1934 }
1935 return 0;
1936}
1937
Steve Naroffc75c1a82009-06-17 22:40:22 +00001938static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001939 IdentifierInfo *Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001940 const Selector &Sel,
1941 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001942 // Check protocols on qualified interfaces.
1943 Decl *GDecl = 0;
Steve Naroffc75c1a82009-06-17 22:40:22 +00001944 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001945 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00001946 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001947 GDecl = PD;
1948 break;
1949 }
1950 // Also must look for a getter name which uses property syntax.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001951 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001952 GDecl = OMD;
1953 break;
1954 }
1955 }
1956 if (!GDecl) {
Steve Naroffc75c1a82009-06-17 22:40:22 +00001957 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001958 E = QIdTy->qual_end(); I != E; ++I) {
1959 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001960 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001961 if (GDecl)
1962 return GDecl;
1963 }
1964 }
1965 return GDecl;
1966}
Chris Lattner2cb744b2009-02-15 22:43:40 +00001967
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001968/// FindMethodInNestedImplementations - Look up a method in current and
1969/// all base class implementations.
1970///
1971ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
1972 const ObjCInterfaceDecl *IFace,
1973 const Selector &Sel) {
1974 ObjCMethodDecl *Method = 0;
Argiris Kirtzidisb1c4ee52009-07-21 00:06:04 +00001975 if (ObjCImplementationDecl *ImpDecl = IFace->getImplementation())
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001976 Method = ImpDecl->getInstanceMethod(Sel);
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001977
1978 if (!Method && IFace->getSuperClass())
1979 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
1980 return Method;
1981}
Douglas Gregore399ad42009-08-26 22:36:53 +00001982
Anders Carlsson9935ab92009-08-26 18:25:21 +00001983Action::OwningExprResult
1984Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
Sebastian Redl8b769972009-01-19 00:08:26 +00001985 tok::TokenKind OpKind, SourceLocation MemberLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001986 DeclarationName MemberName,
Douglas Gregord33e3282009-09-01 00:37:14 +00001987 bool HasExplicitTemplateArgs,
1988 SourceLocation LAngleLoc,
1989 const TemplateArgument *ExplicitTemplateArgs,
1990 unsigned NumExplicitTemplateArgs,
1991 SourceLocation RAngleLoc,
Douglas Gregorbc2fb7f2009-09-03 21:38:09 +00001992 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS,
1993 NamedDecl *FirstQualifierInScope) {
Douglas Gregorda61ad22009-08-06 03:17:00 +00001994 if (SS && SS->isInvalid())
1995 return ExprError();
1996
Nate Begemane85f43d2009-08-10 23:49:36 +00001997 // Since this might be a postfix expression, get rid of ParenListExprs.
1998 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1999
Anders Carlssonc154a722009-05-01 19:30:39 +00002000 Expr *BaseExpr = Base.takeAs<Expr>();
Steve Naroff2cb66382007-07-26 03:11:44 +00002001 assert(BaseExpr && "no record expression");
Nate Begemane85f43d2009-08-10 23:49:36 +00002002
Steve Naroff137e11d2007-12-16 21:42:28 +00002003 // Perform default conversions.
2004 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00002005
Steve Naroff2cb66382007-07-26 03:11:44 +00002006 QualType BaseType = BaseExpr->getType();
David Chisnall44663db2009-08-17 16:35:33 +00002007 // If this is an Objective-C pseudo-builtin and a definition is provided then
2008 // use that.
2009 if (BaseType->isObjCIdType()) {
2010 // We have an 'id' type. Rather than fall through, we check if this
2011 // is a reference to 'isa'.
2012 if (BaseType != Context.ObjCIdRedefinitionType) {
2013 BaseType = Context.ObjCIdRedefinitionType;
2014 ImpCastExprToType(BaseExpr, BaseType);
2015 }
2016 } else if (BaseType->isObjCClassType() &&
Douglas Gregorcfa0a632009-08-31 21:16:32 +00002017 BaseType != Context.ObjCClassRedefinitionType) {
David Chisnall44663db2009-08-17 16:35:33 +00002018 BaseType = Context.ObjCClassRedefinitionType;
2019 ImpCastExprToType(BaseExpr, BaseType);
2020 }
Steve Naroff2cb66382007-07-26 03:11:44 +00002021 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00002022
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002023 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2024 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00002025 if (OpKind == tok::arrow) {
Douglas Gregorbc2fb7f2009-09-03 21:38:09 +00002026 if (BaseType->isDependentType()) {
2027 NestedNameSpecifier *Qualifier = 0;
2028 if (SS) {
2029 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2030 if (!FirstQualifierInScope)
2031 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2032 }
2033
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002034 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2035 BaseExpr, true,
Douglas Gregor0f927cf2009-09-03 16:14:30 +00002036 OpLoc,
Douglas Gregorbc2fb7f2009-09-03 21:38:09 +00002037 Qualifier,
Douglas Gregor0f927cf2009-09-03 16:14:30 +00002038 SS? SS->getRange() : SourceRange(),
Douglas Gregorbc2fb7f2009-09-03 21:38:09 +00002039 FirstQualifierInScope,
Anders Carlsson9935ab92009-08-26 18:25:21 +00002040 MemberName,
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002041 MemberLoc));
Douglas Gregorbc2fb7f2009-09-03 21:38:09 +00002042 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002043 else if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff2cb66382007-07-26 03:11:44 +00002044 BaseType = PT->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00002045 else if (BaseType->isObjCObjectPointerType())
2046 ;
Steve Naroff2cb66382007-07-26 03:11:44 +00002047 else
Sebastian Redl8b769972009-01-19 00:08:26 +00002048 return ExprError(Diag(MemberLoc,
2049 diag::err_typecheck_member_reference_arrow)
2050 << BaseType << BaseExpr->getSourceRange());
Anders Carlsson72d3c662009-05-15 23:10:19 +00002051 } else {
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002052 if (BaseType->isDependentType()) {
2053 // Require that the base type isn't a pointer type
2054 // (so we'll report an error for)
2055 // T* t;
2056 // t.f;
2057 //
2058 // In Obj-C++, however, the above expression is valid, since it could be
2059 // accessing the 'f' property if T is an Obj-C interface. The extra check
2060 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002061 const PointerType *PT = BaseType->getAs<PointerType>();
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002062
2063 if (!PT || (getLangOptions().ObjC1 &&
Douglas Gregorbc2fb7f2009-09-03 21:38:09 +00002064 !PT->getPointeeType()->isRecordType())) {
2065 NestedNameSpecifier *Qualifier = 0;
2066 if (SS) {
2067 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2068 if (!FirstQualifierInScope)
2069 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2070 }
2071
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002072 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2073 BaseExpr, false,
2074 OpLoc,
Douglas Gregorbc2fb7f2009-09-03 21:38:09 +00002075 Qualifier,
Douglas Gregor0f927cf2009-09-03 16:14:30 +00002076 SS? SS->getRange() : SourceRange(),
Douglas Gregorbc2fb7f2009-09-03 21:38:09 +00002077 FirstQualifierInScope,
Anders Carlsson9935ab92009-08-26 18:25:21 +00002078 MemberName,
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002079 MemberLoc));
Douglas Gregorbc2fb7f2009-09-03 21:38:09 +00002080 }
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002081 }
Chris Lattner4b009652007-07-25 00:24:17 +00002082 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002083
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002084 // Handle field access to simple records. This also handles access to fields
2085 // of the ObjC 'id' struct.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002086 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00002087 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorc84d8932009-03-09 16:13:40 +00002088 if (RequireCompleteType(OpLoc, BaseType,
Anders Carlssona21e7872009-08-26 23:45:07 +00002089 PDiag(diag::err_typecheck_incomplete_tag)
2090 << BaseExpr->getSourceRange()))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002091 return ExprError();
2092
Douglas Gregorda61ad22009-08-06 03:17:00 +00002093 DeclContext *DC = RDecl;
2094 if (SS && SS->isSet()) {
2095 // If the member name was a qualified-id, look into the
2096 // nested-name-specifier.
2097 DC = computeDeclContext(*SS, false);
2098
2099 // FIXME: If DC is not computable, we should build a
2100 // CXXUnresolvedMemberExpr.
2101 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2102 }
2103
Steve Naroff2cb66382007-07-26 03:11:44 +00002104 // The record definition is complete, now make sure the member is valid.
Sebastian Redl8b769972009-01-19 00:08:26 +00002105 LookupResult Result
Anders Carlsson9935ab92009-08-26 18:25:21 +00002106 = LookupQualifiedName(DC, MemberName, LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002107
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002108 if (!Result)
Anders Carlsson4355a392009-08-30 00:54:35 +00002109 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member_deprecated)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002110 << MemberName << BaseExpr->getSourceRange());
Chris Lattner84ad8332009-03-31 08:18:48 +00002111 if (Result.isAmbiguous()) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002112 DiagnoseAmbiguousLookup(Result, MemberName, MemberLoc,
2113 BaseExpr->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00002114 return ExprError();
Chris Lattner84ad8332009-03-31 08:18:48 +00002115 }
2116
Douglas Gregor0f927cf2009-09-03 16:14:30 +00002117 if (SS && SS->isSet()) {
2118 QualType BaseTypeCanon
2119 = Context.getCanonicalType(BaseType).getUnqualifiedType();
2120 QualType MemberTypeCanon
2121 = Context.getCanonicalType(
2122 Context.getTypeDeclType(
2123 dyn_cast<TypeDecl>(Result.getAsDecl()->getDeclContext())));
2124
2125 if (BaseTypeCanon != MemberTypeCanon &&
2126 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2127 return ExprError(Diag(SS->getBeginLoc(),
2128 diag::err_not_direct_base_or_virtual)
2129 << MemberTypeCanon << BaseTypeCanon);
2130 }
2131
Chris Lattner84ad8332009-03-31 08:18:48 +00002132 NamedDecl *MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002133
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002134 // If the decl being referenced had an error, return an error for this
2135 // sub-expr without emitting another error, in order to avoid cascading
2136 // error cases.
2137 if (MemberDecl->isInvalidDecl())
2138 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002139
Douglas Gregoraa57e862009-02-18 21:56:37 +00002140 // Check the use of this field
2141 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2142 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002143
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002144 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00002145 // We may have found a field within an anonymous union or struct
2146 // (C++ [class.union]).
2147 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00002148 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00002149 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00002150
Douglas Gregor82d44772008-12-20 23:49:58 +00002151 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002152 QualType MemberType = FD->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002153 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
Douglas Gregor82d44772008-12-20 23:49:58 +00002154 MemberType = Ref->getPointeeType();
2155 else {
Mon P Wang04d89cb2009-07-22 03:08:17 +00002156 unsigned BaseAddrSpace = BaseType.getAddressSpace();
Douglas Gregor82d44772008-12-20 23:49:58 +00002157 unsigned combinedQualifiers =
2158 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002159 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00002160 combinedQualifiers &= ~QualType::Const;
2161 MemberType = MemberType.getQualifiedType(combinedQualifiers);
Mon P Wang04d89cb2009-07-22 03:08:17 +00002162 if (BaseAddrSpace != MemberType.getAddressSpace())
2163 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor82d44772008-12-20 23:49:58 +00002164 }
Eli Friedman76b49832008-02-06 22:48:16 +00002165
Douglas Gregorcad27f62009-06-22 23:06:13 +00002166 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanian843336e2009-07-29 19:40:11 +00002167 if (PerformObjectMemberConversion(BaseExpr, FD))
2168 return ExprError();
Douglas Gregore399ad42009-08-26 22:36:53 +00002169 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2170 FD, MemberLoc, MemberType));
Chris Lattner84ad8332009-03-31 08:18:48 +00002171 }
2172
Douglas Gregorcad27f62009-06-22 23:06:13 +00002173 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2174 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002175 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2176 Var, MemberLoc,
2177 Var->getType().getNonReferenceType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002178 }
2179 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2180 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002181 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2182 MemberFn, MemberLoc,
2183 MemberFn->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002184 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002185 if (FunctionTemplateDecl *FunTmpl
2186 = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2187 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregord33e3282009-09-01 00:37:14 +00002188
2189 if (HasExplicitTemplateArgs)
2190 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2191 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
2192 SS? SS->getRange() : SourceRange(),
2193 FunTmpl, MemberLoc, true,
2194 LAngleLoc, ExplicitTemplateArgs,
2195 NumExplicitTemplateArgs, RAngleLoc,
2196 Context.OverloadTy));
2197
Douglas Gregore399ad42009-08-26 22:36:53 +00002198 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2199 FunTmpl, MemberLoc,
2200 Context.OverloadTy));
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002201 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002202 if (OverloadedFunctionDecl *Ovl
Douglas Gregord33e3282009-09-01 00:37:14 +00002203 = dyn_cast<OverloadedFunctionDecl>(MemberDecl)) {
2204 if (HasExplicitTemplateArgs)
2205 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2206 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
2207 SS? SS->getRange() : SourceRange(),
2208 Ovl, MemberLoc, true,
2209 LAngleLoc, ExplicitTemplateArgs,
2210 NumExplicitTemplateArgs, RAngleLoc,
2211 Context.OverloadTy));
2212
Douglas Gregore399ad42009-08-26 22:36:53 +00002213 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2214 Ovl, MemberLoc, Context.OverloadTy));
Douglas Gregord33e3282009-09-01 00:37:14 +00002215 }
Douglas Gregorcad27f62009-06-22 23:06:13 +00002216 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2217 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002218 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2219 Enum, MemberLoc, Enum->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002220 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002221 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00002222 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002223 << MemberName << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00002224
Douglas Gregor82d44772008-12-20 23:49:58 +00002225 // We found a declaration kind that we didn't expect. This is a
2226 // generic error message that tells the user that she can't refer
2227 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00002228 return ExprError(Diag(MemberLoc,
2229 diag::err_typecheck_member_reference_unknown)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002230 << MemberName << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00002231 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002232
Steve Naroff329ec222009-07-10 23:34:53 +00002233 // Handle properties on ObjC 'Class' types.
Steve Naroff7982a642009-07-13 17:19:15 +00002234 if (OpKind == tok::period && BaseType->isObjCClassType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00002235 // Also must look for a getter name which uses property syntax.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002236 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2237 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002238 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2239 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2240 ObjCMethodDecl *Getter;
2241 // FIXME: need to also look locally in the implementation.
2242 if ((Getter = IFace->lookupClassMethod(Sel))) {
2243 // Check the use of this method.
2244 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2245 return ExprError();
2246 }
2247 // If we found a getter then this may be a valid dot-reference, we
2248 // will look for the matching setter, in case it is needed.
2249 Selector SetterSel =
2250 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson9935ab92009-08-26 18:25:21 +00002251 PP.getSelectorTable(), Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002252 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2253 if (!Setter) {
2254 // If this reference is in an @implementation, also check for 'private'
2255 // methods.
2256 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
2257 }
2258 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002259 if (!Setter)
2260 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff329ec222009-07-10 23:34:53 +00002261
2262 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2263 return ExprError();
2264
2265 if (Getter || Setter) {
2266 QualType PType;
2267
2268 if (Getter)
2269 PType = Getter->getResultType();
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002270 else
2271 // Get the expression type from Setter's incoming parameter.
2272 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00002273 // FIXME: we must check that the setter has property type.
Fariborz Jahanian128cdc52009-08-20 17:02:02 +00002274 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff329ec222009-07-10 23:34:53 +00002275 Setter, MemberLoc, BaseExpr));
2276 }
2277 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002278 << MemberName << BaseType);
Steve Naroff329ec222009-07-10 23:34:53 +00002279 }
2280 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002281 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2282 // (*Obj).ivar.
Steve Naroff329ec222009-07-10 23:34:53 +00002283 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2284 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
2285 const ObjCObjectPointerType *OPT = BaseType->getAsObjCObjectPointerType();
2286 const ObjCInterfaceType *IFaceT =
2287 OPT ? OPT->getInterfaceType() : BaseType->getAsObjCInterfaceType();
Steve Naroff4e743962009-07-16 00:25:06 +00002288 if (IFaceT) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002289 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2290
Steve Naroff4e743962009-07-16 00:25:06 +00002291 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2292 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson9935ab92009-08-26 18:25:21 +00002293 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Steve Naroff4e743962009-07-16 00:25:06 +00002294
2295 if (IV) {
2296 // If the decl being referenced had an error, return an error for this
2297 // sub-expr without emitting another error, in order to avoid cascading
2298 // error cases.
2299 if (IV->isInvalidDecl())
2300 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00002301
Steve Naroff4e743962009-07-16 00:25:06 +00002302 // Check whether we can reference this field.
2303 if (DiagnoseUseOfDecl(IV, MemberLoc))
2304 return ExprError();
2305 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2306 IV->getAccessControl() != ObjCIvarDecl::Package) {
2307 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2308 if (ObjCMethodDecl *MD = getCurMethodDecl())
2309 ClassOfMethodDecl = MD->getClassInterface();
2310 else if (ObjCImpDecl && getCurFunctionDecl()) {
2311 // Case of a c-function declared inside an objc implementation.
2312 // FIXME: For a c-style function nested inside an objc implementation
2313 // class, there is no implementation context available, so we pass
2314 // down the context as argument to this routine. Ideally, this context
2315 // need be passed down in the AST node and somehow calculated from the
2316 // AST for a function decl.
2317 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
2318 if (ObjCImplementationDecl *IMPD =
2319 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2320 ClassOfMethodDecl = IMPD->getClassInterface();
2321 else if (ObjCCategoryImplDecl* CatImplClass =
2322 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2323 ClassOfMethodDecl = CatImplClass->getClassInterface();
2324 }
2325
2326 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2327 if (ClassDeclared != IDecl ||
2328 ClassOfMethodDecl != ClassDeclared)
2329 Diag(MemberLoc, diag::error_private_ivar_access)
2330 << IV->getDeclName();
Mike Stump90fc78e2009-08-04 21:02:39 +00002331 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2332 // @protected
Steve Naroff4e743962009-07-16 00:25:06 +00002333 Diag(MemberLoc, diag::error_protected_ivar_access)
2334 << IV->getDeclName();
Steve Narofff9606572009-03-04 18:34:24 +00002335 }
Steve Naroff4e743962009-07-16 00:25:06 +00002336
2337 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2338 MemberLoc, BaseExpr,
2339 OpKind == tok::arrow));
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002340 }
Steve Naroff4e743962009-07-16 00:25:06 +00002341 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002342 << IDecl->getDeclName() << MemberName
Steve Naroff4e743962009-07-16 00:25:06 +00002343 << BaseExpr->getSourceRange());
Fariborz Jahanian09772392008-12-13 22:20:28 +00002344 }
Chris Lattnera57cf472008-07-21 04:28:12 +00002345 }
Steve Naroff7bffd372009-07-15 18:40:39 +00002346 // Handle properties on 'id' and qualified "id".
2347 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
2348 BaseType->isObjCQualifiedIdType())) {
2349 const ObjCObjectPointerType *QIdTy = BaseType->getAsObjCObjectPointerType();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002350 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Steve Naroff7bffd372009-07-15 18:40:39 +00002351
Steve Naroff329ec222009-07-10 23:34:53 +00002352 // Check protocols on qualified interfaces.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002353 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002354 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2355 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2356 // Check the use of this declaration
2357 if (DiagnoseUseOfDecl(PD, MemberLoc))
2358 return ExprError();
2359
2360 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2361 MemberLoc, BaseExpr));
2362 }
2363 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2364 // Check the use of this method.
2365 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2366 return ExprError();
2367
2368 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
2369 OMD->getResultType(),
2370 OMD, OpLoc, MemberLoc,
2371 NULL, 0));
2372 }
2373 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002374
Steve Naroff329ec222009-07-10 23:34:53 +00002375 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002376 << MemberName << BaseType);
Steve Naroff329ec222009-07-10 23:34:53 +00002377 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002378 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2379 // pointer to a (potentially qualified) interface type.
Steve Naroff329ec222009-07-10 23:34:53 +00002380 const ObjCObjectPointerType *OPT;
2381 if (OpKind == tok::period &&
2382 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2383 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2384 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002385 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Steve Naroff329ec222009-07-10 23:34:53 +00002386
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002387 // Search for a declared property first.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002388 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002389 // Check whether we can reference this property.
2390 if (DiagnoseUseOfDecl(PD, MemberLoc))
2391 return ExprError();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002392 QualType ResTy = PD->getType();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002393 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002394 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian80ccaa92009-05-08 20:20:55 +00002395 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2396 ResTy = Getter->getResultType();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002397 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner51f6fb32009-02-16 18:35:08 +00002398 MemberLoc, BaseExpr));
2399 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002400 // Check protocols on qualified interfaces.
Steve Naroff8194a542009-07-20 17:56:53 +00002401 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2402 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002403 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002404 // Check whether we can reference this property.
2405 if (DiagnoseUseOfDecl(PD, MemberLoc))
2406 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00002407
Steve Naroff774e4152009-01-21 00:14:39 +00002408 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002409 MemberLoc, BaseExpr));
2410 }
Steve Naroff329ec222009-07-10 23:34:53 +00002411 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2412 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002413 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Steve Naroff329ec222009-07-10 23:34:53 +00002414 // Check whether we can reference this property.
2415 if (DiagnoseUseOfDecl(PD, MemberLoc))
2416 return ExprError();
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002417
Steve Naroff329ec222009-07-10 23:34:53 +00002418 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2419 MemberLoc, BaseExpr));
2420 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002421 // If that failed, look for an "implicit" property by seeing if the nullary
2422 // selector is implemented.
2423
2424 // FIXME: The logic for looking up nullary and unary selectors should be
2425 // shared with the code in ActOnInstanceMessage.
2426
Anders Carlsson9935ab92009-08-26 18:25:21 +00002427 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002428 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002429
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002430 // If this reference is in an @implementation, check for 'private' methods.
2431 if (!Getter)
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002432 Getter = FindMethodInNestedImplementations(IFace, Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002433
Steve Naroff04151f32008-10-22 19:16:27 +00002434 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002435 if (!Getter)
2436 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002437 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002438 // Check if we can reference this property.
2439 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2440 return ExprError();
Steve Naroffdede0c92009-03-11 13:48:17 +00002441 }
2442 // If we found a getter then this may be a valid dot-reference, we
2443 // will look for the matching setter, in case it is needed.
2444 Selector SetterSel =
2445 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson9935ab92009-08-26 18:25:21 +00002446 PP.getSelectorTable(), Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002447 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002448 if (!Setter) {
2449 // If this reference is in an @implementation, also check for 'private'
2450 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002451 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002452 }
2453 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002454 if (!Setter)
2455 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002456
Steve Naroffdede0c92009-03-11 13:48:17 +00002457 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2458 return ExprError();
2459
2460 if (Getter || Setter) {
2461 QualType PType;
2462
2463 if (Getter)
2464 PType = Getter->getResultType();
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002465 else
2466 // Get the expression type from Setter's incoming parameter.
2467 PType = (*(Setter->param_end() -1))->getType();
Steve Naroffdede0c92009-03-11 13:48:17 +00002468 // FIXME: we must check that the setter has property type.
Fariborz Jahanian128cdc52009-08-20 17:02:02 +00002469 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroffdede0c92009-03-11 13:48:17 +00002470 Setter, MemberLoc, BaseExpr));
2471 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002472 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002473 << MemberName << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00002474 }
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002475
Steve Naroff29d293b2009-07-24 17:54:45 +00002476 // Handle the following exceptional case (*Obj).isa.
2477 if (OpKind == tok::period &&
2478 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson9935ab92009-08-26 18:25:21 +00002479 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroff29d293b2009-07-24 17:54:45 +00002480 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2481 Context.getObjCIdType()));
2482
Chris Lattnera57cf472008-07-21 04:28:12 +00002483 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00002484 if (BaseType->isExtVectorType()) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002485 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnera57cf472008-07-21 04:28:12 +00002486 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2487 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00002488 return ExprError();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002489 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff774e4152009-01-21 00:14:39 +00002490 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00002491 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002492
Douglas Gregor762da552009-03-27 06:00:30 +00002493 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2494 << BaseType << BaseExpr->getSourceRange();
2495
2496 // If the user is trying to apply -> or . to a function or function
2497 // pointer, it's probably because they forgot parentheses to call
2498 // the function. Suggest the addition of those parentheses.
2499 if (BaseType == Context.OverloadTy ||
2500 BaseType->isFunctionType() ||
2501 (BaseType->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002502 BaseType->getAs<PointerType>()->isFunctionType())) {
Douglas Gregor762da552009-03-27 06:00:30 +00002503 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2504 Diag(Loc, diag::note_member_reference_needs_call)
2505 << CodeModificationHint::CreateInsertion(Loc, "()");
2506 }
2507
2508 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00002509}
2510
Anders Carlsson9935ab92009-08-26 18:25:21 +00002511Action::OwningExprResult
2512Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2513 tok::TokenKind OpKind, SourceLocation MemberLoc,
2514 IdentifierInfo &Member,
2515 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
2516 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, MemberLoc,
2517 DeclarationName(&Member), ObjCImpDecl, SS);
2518}
2519
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002520Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2521 FunctionDecl *FD,
2522 ParmVarDecl *Param) {
2523 if (Param->hasUnparsedDefaultArg()) {
2524 Diag (CallLoc,
2525 diag::err_use_of_default_argument_to_function_declared_later) <<
2526 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
2527 Diag(UnparsedDefaultArgLocs[Param],
2528 diag::note_default_argument_declared_here);
2529 } else {
2530 if (Param->hasUninstantiatedDefaultArg()) {
2531 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2532
2533 // Instantiate the expression.
Douglas Gregor8dbd0382009-08-28 20:31:08 +00002534 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002535
2536 // FIXME: We should really make a new InstantiatingTemplate ctor
2537 // that has a better message - right now we're just piggy-backing
2538 // off the "default template argument" error message.
2539 InstantiatingTemplate Inst(*this, CallLoc, FD->getPrimaryTemplate(),
Douglas Gregor8dbd0382009-08-28 20:31:08 +00002540 ArgList.getInnermost().getFlatArgumentList(),
2541 ArgList.getInnermost().flat_size());
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002542
John McCall0ba26ee2009-08-25 22:02:44 +00002543 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002544 if (Result.isInvalid())
2545 return ExprError();
2546
2547 if (SetParamDefaultArgument(Param, move(Result),
2548 /*FIXME:EqualLoc*/
2549 UninstExpr->getSourceRange().getBegin()))
2550 return ExprError();
2551 }
2552
2553 Expr *DefaultExpr = Param->getDefaultArg();
2554
2555 // If the default expression creates temporaries, we need to
2556 // push them to the current stack of expression temporaries so they'll
2557 // be properly destroyed.
2558 if (CXXExprWithTemporaries *E
2559 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
2560 assert(!E->shouldDestroyTemporaries() &&
2561 "Can't destroy temporaries in a default argument expr!");
2562 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2563 ExprTemporaries.push_back(E->getTemporary(I));
2564 }
2565 }
2566
2567 // We already type-checked the argument, so we know it works.
2568 return Owned(CXXDefaultArgExpr::Create(Context, Param));
2569}
2570
Douglas Gregor3257fb52008-12-22 05:46:06 +00002571/// ConvertArgumentsForCall - Converts the arguments specified in
2572/// Args/NumArgs to the parameter types of the function FDecl with
2573/// function prototype Proto. Call is the call expression itself, and
2574/// Fn is the function expression. For a C++ member function, this
2575/// routine does not attempt to convert the object argument. Returns
2576/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00002577bool
2578Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002579 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002580 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002581 Expr **Args, unsigned NumArgs,
2582 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00002583 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00002584 // assignment, to the types of the corresponding parameter, ...
2585 unsigned NumArgsInProto = Proto->getNumArgs();
2586 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002587 bool Invalid = false;
2588
Douglas Gregor3257fb52008-12-22 05:46:06 +00002589 // If too few arguments are available (and we don't have default
2590 // arguments for the remaining parameters), don't make the call.
2591 if (NumArgs < NumArgsInProto) {
2592 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2593 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2594 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2595 // Use default arguments for missing arguments
2596 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00002597 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002598 }
2599
2600 // If too many are passed and not variadic, error on the extras and drop
2601 // them.
2602 if (NumArgs > NumArgsInProto) {
2603 if (!Proto->isVariadic()) {
2604 Diag(Args[NumArgsInProto]->getLocStart(),
2605 diag::err_typecheck_call_too_many_args)
2606 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2607 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2608 Args[NumArgs-1]->getLocEnd());
2609 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002610 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002611 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002612 }
2613 NumArgsToCheck = NumArgsInProto;
2614 }
Mike Stump9afab102009-02-19 03:04:26 +00002615
Douglas Gregor3257fb52008-12-22 05:46:06 +00002616 // Continue to check argument types (even if we have too few/many args).
2617 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2618 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00002619
Douglas Gregor3257fb52008-12-22 05:46:06 +00002620 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002621 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002622 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002623
Eli Friedman83dec9e2009-03-22 22:00:50 +00002624 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2625 ProtoArgType,
Anders Carlssona21e7872009-08-26 23:45:07 +00002626 PDiag(diag::err_call_incomplete_argument)
2627 << Arg->getSourceRange()))
Eli Friedman83dec9e2009-03-22 22:00:50 +00002628 return true;
2629
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002630 // Pass the argument.
2631 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2632 return true;
Anders Carlssona116e6e2009-06-12 16:51:40 +00002633 } else {
Anders Carlsson60eb3be2009-08-25 02:29:20 +00002634 ParmVarDecl *Param = FDecl->getParamDecl(i);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002635
2636 OwningExprResult ArgExpr =
2637 BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(),
2638 FDecl, Param);
2639 if (ArgExpr.isInvalid())
2640 return true;
2641
2642 Arg = ArgExpr.takeAs<Expr>();
Anders Carlssona116e6e2009-06-12 16:51:40 +00002643 }
2644
Douglas Gregor3257fb52008-12-22 05:46:06 +00002645 Call->setArg(i, Arg);
2646 }
Mike Stump9afab102009-02-19 03:04:26 +00002647
Douglas Gregor3257fb52008-12-22 05:46:06 +00002648 // If this is a variadic call, handle args passed through "...".
2649 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002650 VariadicCallType CallType = VariadicFunction;
2651 if (Fn->getType()->isBlockPointerType())
2652 CallType = VariadicBlock; // Block
2653 else if (isa<MemberExpr>(Fn))
2654 CallType = VariadicMethod;
2655
Douglas Gregor3257fb52008-12-22 05:46:06 +00002656 // Promote the arguments (C99 6.5.2.2p7).
2657 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2658 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00002659 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002660 Call->setArg(i, Arg);
2661 }
2662 }
2663
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002664 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002665}
2666
Steve Naroff87d58b42007-09-16 03:34:24 +00002667/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002668/// This provides the location of the left/right parens and a list of comma
2669/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002670Action::OwningExprResult
2671Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2672 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002673 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002674 unsigned NumArgs = args.size();
Nate Begemane85f43d2009-08-10 23:49:36 +00002675
2676 // Since this might be a postfix expression, get rid of ParenListExprs.
2677 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
2678
Anders Carlssonc154a722009-05-01 19:30:39 +00002679 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl8b769972009-01-19 00:08:26 +00002680 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002681 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002682 FunctionDecl *FDecl = NULL;
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002683 NamedDecl *NDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002684 DeclarationName UnqualifiedName;
Nate Begemane85f43d2009-08-10 23:49:36 +00002685
Douglas Gregor3257fb52008-12-22 05:46:06 +00002686 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002687 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002688 // in which case we won't do any semantic analysis now.
Mike Stumpe127ae32009-05-16 07:39:55 +00002689 // FIXME: Will need to cache the results of name lookup (including ADL) in
2690 // Fn.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002691 bool Dependent = false;
2692 if (Fn->isTypeDependent())
2693 Dependent = true;
2694 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2695 Dependent = true;
2696
2697 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002698 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002699 Context.DependentTy, RParenLoc));
2700
2701 // Determine whether this is a call to an object (C++ [over.call.object]).
2702 if (Fn->getType()->isRecordType())
2703 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2704 CommaLocs, RParenLoc));
2705
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002706 // Determine whether this is a call to a member function.
Douglas Gregorb60eb752009-06-25 22:08:12 +00002707 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2708 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2709 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2710 isa<CXXMethodDecl>(MemDecl) ||
2711 (isa<FunctionTemplateDecl>(MemDecl) &&
2712 isa<CXXMethodDecl>(
2713 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redl8b769972009-01-19 00:08:26 +00002714 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2715 CommaLocs, RParenLoc));
Douglas Gregorb60eb752009-06-25 22:08:12 +00002716 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00002717 }
2718
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002719 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002720 // Also, in C++, keep track of whether we should perform argument-dependent
2721 // lookup and whether there were any explicitly-specified template arguments.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002722 Expr *FnExpr = Fn;
2723 bool ADL = true;
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002724 bool HasExplicitTemplateArgs = 0;
2725 const TemplateArgument *ExplicitTemplateArgs = 0;
2726 unsigned NumExplicitTemplateArgs = 0;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002727 while (true) {
2728 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2729 FnExpr = IcExpr->getSubExpr();
2730 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002731 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002732 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002733 ADL = false;
2734 FnExpr = PExpr->getSubExpr();
2735 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002736 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002737 == UnaryOperator::AddrOf) {
2738 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor28857752009-06-30 22:34:41 +00002739 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002740 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2741 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
Douglas Gregor28857752009-06-30 22:34:41 +00002742 NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl());
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002743 break;
Mike Stump9afab102009-02-19 03:04:26 +00002744 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002745 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2746 UnqualifiedName = DepName->getName();
2747 break;
Douglas Gregor28857752009-06-30 22:34:41 +00002748 } else if (TemplateIdRefExpr *TemplateIdRef
2749 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2750 NDecl = TemplateIdRef->getTemplateName().getAsTemplateDecl();
Douglas Gregor6631cb42009-07-29 18:26:50 +00002751 if (!NDecl)
2752 NDecl = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002753 HasExplicitTemplateArgs = true;
2754 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2755 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2756
2757 // C++ [temp.arg.explicit]p6:
2758 // [Note: For simple function names, argument dependent lookup (3.4.2)
2759 // applies even when the function name is not visible within the
2760 // scope of the call. This is because the call still has the syntactic
2761 // form of a function call (3.4.1). But when a function template with
2762 // explicit template arguments is used, the call does not have the
2763 // correct syntactic form unless there is a function template with
2764 // that name visible at the point of the call. If no such name is
2765 // visible, the call is not syntactically well-formed and
2766 // argument-dependent lookup does not apply. If some such name is
2767 // visible, argument dependent lookup applies and additional function
2768 // templates may be found in other namespaces.
2769 //
2770 // The summary of this paragraph is that, if we get to this point and the
2771 // template-id was not a qualified name, then argument-dependent lookup
2772 // is still possible.
2773 if (TemplateIdRef->getQualifier())
2774 ADL = false;
Douglas Gregor28857752009-06-30 22:34:41 +00002775 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002776 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002777 // Any kind of name that does not refer to a declaration (or
2778 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2779 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002780 break;
2781 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002782 }
Mike Stump9afab102009-02-19 03:04:26 +00002783
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002784 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregorb60eb752009-06-25 22:08:12 +00002785 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregor28857752009-06-30 22:34:41 +00002786 if (NDecl) {
2787 FDecl = dyn_cast<FunctionDecl>(NDecl);
2788 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
Douglas Gregorb60eb752009-06-25 22:08:12 +00002789 FDecl = FunctionTemplate->getTemplatedDecl();
2790 else
Douglas Gregor28857752009-06-30 22:34:41 +00002791 FDecl = dyn_cast<FunctionDecl>(NDecl);
2792 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002793 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002794
Douglas Gregorb60eb752009-06-25 22:08:12 +00002795 if (Ovl || FunctionTemplate ||
2796 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002797 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002798 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002799 ADL = false;
2800
Douglas Gregorfcb19192009-02-11 23:02:49 +00002801 // We don't perform ADL in C.
2802 if (!getLangOptions().CPlusPlus)
2803 ADL = false;
2804
Douglas Gregorb60eb752009-06-25 22:08:12 +00002805 if (Ovl || FunctionTemplate || ADL) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002806 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
2807 HasExplicitTemplateArgs,
2808 ExplicitTemplateArgs,
2809 NumExplicitTemplateArgs,
2810 LParenLoc, Args, NumArgs, CommaLocs,
2811 RParenLoc, ADL);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002812 if (!FDecl)
2813 return ExprError();
2814
2815 // Update Fn to refer to the actual function selected.
2816 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002817 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor28857752009-06-30 22:34:41 +00002818 = dyn_cast<QualifiedDeclRefExpr>(FnExpr))
Douglas Gregor1e589cc2009-03-26 23:50:42 +00002819 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2820 QDRExpr->getLocation(),
2821 false, false,
2822 QDRExpr->getQualifierRange(),
2823 QDRExpr->getQualifier());
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002824 else
Mike Stump9afab102009-02-19 03:04:26 +00002825 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002826 Fn->getSourceRange().getBegin());
2827 Fn->Destroy(Context);
2828 Fn = NewFn;
2829 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002830 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002831
2832 // Promote the function operand.
2833 UsualUnaryConversions(Fn);
2834
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002835 // Make the call expr early, before semantic checks. This guarantees cleanup
2836 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002837 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2838 Args, NumArgs,
2839 Context.BoolTy,
2840 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002841
Steve Naroffd6163f32008-09-05 22:11:13 +00002842 const FunctionType *FuncT;
2843 if (!Fn->getType()->isBlockPointerType()) {
2844 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2845 // have type pointer to function".
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002846 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffd6163f32008-09-05 22:11:13 +00002847 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002848 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2849 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002850 FuncT = PT->getPointeeType()->getAsFunctionType();
2851 } else { // This is a block call.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002852 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
Steve Naroffd6163f32008-09-05 22:11:13 +00002853 getAsFunctionType();
2854 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002855 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002856 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2857 << Fn->getType() << Fn->getSourceRange());
2858
Eli Friedman83dec9e2009-03-22 22:00:50 +00002859 // Check for a valid return type
2860 if (!FuncT->getResultType()->isVoidType() &&
2861 RequireCompleteType(Fn->getSourceRange().getBegin(),
2862 FuncT->getResultType(),
Anders Carlssona21e7872009-08-26 23:45:07 +00002863 PDiag(diag::err_call_incomplete_return)
2864 << TheCall->getSourceRange()))
Eli Friedman83dec9e2009-03-22 22:00:50 +00002865 return ExprError();
2866
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002867 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002868 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002869
Douglas Gregor4fa58902009-02-26 23:50:07 +00002870 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002871 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002872 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002873 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002874 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002875 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002876
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002877 if (FDecl) {
2878 // Check if we have too few/too many template arguments, based
2879 // on our knowledge of the function definition.
2880 const FunctionDecl *Def = 0;
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00002881 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanf7ed7812009-06-01 09:24:59 +00002882 const FunctionProtoType *Proto =
2883 Def->getType()->getAsFunctionProtoType();
2884 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2885 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2886 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2887 }
2888 }
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002889 }
2890
Steve Naroffdb65e052007-08-28 23:30:39 +00002891 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002892 for (unsigned i = 0; i != NumArgs; i++) {
2893 Expr *Arg = Args[i];
2894 DefaultArgumentPromotion(Arg);
Eli Friedman83dec9e2009-03-22 22:00:50 +00002895 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2896 Arg->getType(),
Anders Carlssona21e7872009-08-26 23:45:07 +00002897 PDiag(diag::err_call_incomplete_argument)
2898 << Arg->getSourceRange()))
Eli Friedman83dec9e2009-03-22 22:00:50 +00002899 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002900 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002901 }
Chris Lattner4b009652007-07-25 00:24:17 +00002902 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002903
Douglas Gregor3257fb52008-12-22 05:46:06 +00002904 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2905 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002906 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2907 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002908
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002909 // Check for sentinels
2910 if (NDecl)
2911 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Anders Carlsson7fb13802009-08-16 01:56:34 +00002912
Chris Lattner2e64c072007-08-10 20:18:51 +00002913 // Do special checking on direct calls to functions.
Anders Carlsson7fb13802009-08-16 01:56:34 +00002914 if (FDecl) {
2915 if (CheckFunctionCall(FDecl, TheCall.get()))
2916 return ExprError();
2917
2918 if (unsigned BuiltinID = FDecl->getBuiltinID(Context))
2919 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
2920 } else if (NDecl) {
2921 if (CheckBlockCall(NDecl, TheCall.get()))
2922 return ExprError();
2923 }
Chris Lattner2e64c072007-08-10 20:18:51 +00002924
Anders Carlsson54ad8a02009-08-16 03:06:32 +00002925 return MaybeBindToTemporary(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002926}
2927
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002928Action::OwningExprResult
2929Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2930 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002931 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00002932 //FIXME: Preserve type source info.
2933 QualType literalType = GetTypeFromParser(Ty);
Chris Lattner4b009652007-07-25 00:24:17 +00002934 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002935 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002936 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002937
Eli Friedman8c2173d2008-05-20 05:22:08 +00002938 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002939 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002940 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2941 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregored71c542009-05-21 23:48:18 +00002942 } else if (!literalType->isDependentType() &&
2943 RequireCompleteType(LParenLoc, literalType,
Anders Carlssona21e7872009-08-26 23:45:07 +00002944 PDiag(diag::err_typecheck_decl_incomplete_type)
2945 << SourceRange(LParenLoc,
2946 literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002947 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002948
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002949 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002950 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002951 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002952
Chris Lattnere5cb5862008-12-04 23:50:19 +00002953 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002954 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002955 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002956 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002957 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002958 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002959 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002960 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002961}
2962
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002963Action::OwningExprResult
2964Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002965 SourceLocation RBraceLoc) {
2966 unsigned NumInit = initlist.size();
2967 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002968
Steve Naroff0acc9c92007-09-15 18:49:24 +00002969 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002970 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002971
Mike Stump9afab102009-02-19 03:04:26 +00002972 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002973 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002974 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002975 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002976}
2977
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002978/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlc358b622009-07-29 13:50:23 +00002979bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00002980 CastExpr::CastKind& Kind,
2981 CXXMethodDecl *& ConversionDecl,
2982 bool FunctionalStyle) {
Sebastian Redl0e35d042009-07-25 15:41:38 +00002983 if (getLangOptions().CPlusPlus)
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00002984 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
2985 ConversionDecl);
Sebastian Redl0e35d042009-07-25 15:41:38 +00002986
Eli Friedman01e0f652009-08-15 19:02:19 +00002987 DefaultFunctionArrayConversion(castExpr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002988
2989 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2990 // type needs to be scalar.
2991 if (castType->isVoidType()) {
2992 // Cast to void allows any expr type.
2993 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002994 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2995 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2996 (castType->isStructureType() || castType->isUnionType())) {
2997 // GCC struct/union extension: allow cast to self.
Eli Friedman2b128322009-03-23 00:24:07 +00002998 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002999 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3000 << castType << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00003001 Kind = CastExpr::CK_NoOp;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003002 } else if (castType->isUnionType()) {
3003 // GCC cast to union extension
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003004 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003005 RecordDecl::field_iterator Field, FieldEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003006 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003007 Field != FieldEnd; ++Field) {
3008 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
3009 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
3010 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3011 << castExpr->getSourceRange();
3012 break;
3013 }
3014 }
3015 if (Field == FieldEnd)
3016 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3017 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00003018 Kind = CastExpr::CK_ToUnion;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003019 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003020 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00003021 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003022 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003023 }
Mike Stump9afab102009-02-19 03:04:26 +00003024 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003025 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003026 return Diag(castExpr->getLocStart(),
3027 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003028 << castExpr->getType() << castExpr->getSourceRange();
Nate Begemanbd42e022009-06-26 00:50:28 +00003029 } else if (castType->isExtVectorType()) {
3030 if (CheckExtVectorCast(TyR, castType, castExpr->getType()))
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003031 return true;
3032 } else if (castType->isVectorType()) {
3033 if (CheckVectorCast(TyR, castType, castExpr->getType()))
3034 return true;
Nate Begemanbd42e022009-06-26 00:50:28 +00003035 } else if (castExpr->getType()->isVectorType()) {
3036 if (CheckVectorCast(TyR, castExpr->getType(), castType))
3037 return true;
Steve Naroffff6c8022009-03-04 15:11:40 +00003038 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroff49fd7ad2009-04-08 23:52:26 +00003039 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Eli Friedman970e56c2009-05-01 02:23:58 +00003040 } else if (!castType->isArithmeticType()) {
3041 QualType castExprType = castExpr->getType();
3042 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3043 return Diag(castExpr->getLocStart(),
3044 diag::err_cast_pointer_from_non_pointer_int)
3045 << castExprType << castExpr->getSourceRange();
3046 } else if (!castExpr->getType()->isArithmeticType()) {
3047 if (!castType->isIntegralType() && castType->isArithmeticType())
3048 return Diag(castExpr->getLocStart(),
3049 diag::err_cast_pointer_to_non_pointer_int)
3050 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003051 }
Fariborz Jahanian4862e872009-05-22 21:42:52 +00003052 if (isa<ObjCSelectorExpr>(castExpr))
3053 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003054 return false;
3055}
3056
Chris Lattnerd1f26b32007-12-20 00:44:32 +00003057bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003058 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00003059
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003060 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003061 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003062 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00003063 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003064 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00003065 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003066 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003067 } else
3068 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00003069 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003070 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00003071
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003072 return false;
3073}
3074
Nate Begemanbd42e022009-06-26 00:50:28 +00003075bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) {
3076 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
3077
Nate Begeman9e063702009-06-27 22:05:55 +00003078 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3079 // an ExtVectorType.
Nate Begemanbd42e022009-06-26 00:50:28 +00003080 if (SrcTy->isVectorType()) {
3081 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3082 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3083 << DestTy << SrcTy << R;
3084 return false;
3085 }
3086
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003087 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanbd42e022009-06-26 00:50:28 +00003088 // conversion will take place first from scalar to elt type, and then
3089 // splat from elt type to vector.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003090 if (SrcTy->isPointerType())
3091 return Diag(R.getBegin(),
3092 diag::err_invalid_conversion_between_vector_and_scalar)
3093 << DestTy << SrcTy << R;
Nate Begemanbd42e022009-06-26 00:50:28 +00003094 return false;
3095}
3096
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003097Action::OwningExprResult
Nate Begemane85f43d2009-08-10 23:49:36 +00003098Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003099 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlsson9583fa72009-08-07 22:21:05 +00003100 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3101
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003102 assert((Ty != 0) && (Op.get() != 0) &&
3103 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00003104
Nate Begemane85f43d2009-08-10 23:49:36 +00003105 Expr *castExpr = (Expr *)Op.get();
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00003106 //FIXME: Preserve type source info.
3107 QualType castType = GetTypeFromParser(Ty);
Nate Begemane85f43d2009-08-10 23:49:36 +00003108
3109 // If the Expr being casted is a ParenListExpr, handle it specially.
3110 if (isa<ParenListExpr>(castExpr))
3111 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00003112 CXXMethodDecl *ConversionDecl = 0;
Anders Carlsson9583fa72009-08-07 22:21:05 +00003113 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00003114 Kind, ConversionDecl))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003115 return ExprError();
Fariborz Jahanianec172132009-08-29 19:15:16 +00003116 if (ConversionDecl) {
3117 // encounterred a c-style cast requiring a conversion function.
3118 if (CXXConversionDecl *CD = dyn_cast<CXXConversionDecl>(ConversionDecl)) {
3119 castExpr =
3120 new (Context) CXXFunctionalCastExpr(castType.getNonReferenceType(),
3121 castType, LParenLoc,
3122 CastExpr::CK_UserDefinedConversion,
3123 castExpr, CD,
3124 RParenLoc);
3125 Kind = CastExpr::CK_UserDefinedConversion;
3126 }
3127 // FIXME. AST for when dealing with conversion functions (FunctionDecl).
3128 }
Nate Begemane85f43d2009-08-10 23:49:36 +00003129
3130 Op.release();
Sebastian Redl0e35d042009-07-25 15:41:38 +00003131 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Anders Carlsson9583fa72009-08-07 22:21:05 +00003132 Kind, castExpr, castType,
3133 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00003134}
3135
Nate Begemane85f43d2009-08-10 23:49:36 +00003136/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3137/// of comma binary operators.
3138Action::OwningExprResult
3139Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3140 Expr *expr = EA.takeAs<Expr>();
3141 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3142 if (!E)
3143 return Owned(expr);
3144
3145 OwningExprResult Result(*this, E->getExpr(0));
3146
3147 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3148 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3149 Owned(E->getExpr(i)));
3150
3151 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3152}
3153
3154Action::OwningExprResult
3155Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3156 SourceLocation RParenLoc, ExprArg Op,
3157 QualType Ty) {
3158 ParenListExpr *PE = (ParenListExpr *)Op.get();
3159
3160 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
3161 // then handle it as such.
3162 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3163 if (PE->getNumExprs() == 0) {
3164 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3165 return ExprError();
3166 }
3167
3168 llvm::SmallVector<Expr *, 8> initExprs;
3169 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3170 initExprs.push_back(PE->getExpr(i));
3171
3172 // FIXME: This means that pretty-printing the final AST will produce curly
3173 // braces instead of the original commas.
3174 Op.release();
3175 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
3176 initExprs.size(), RParenLoc);
3177 E->setType(Ty);
3178 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
3179 Owned(E));
3180 } else {
3181 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
3182 // sequence of BinOp comma operators.
3183 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3184 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3185 }
3186}
3187
3188Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3189 SourceLocation R,
3190 MultiExprArg Val) {
3191 unsigned nexprs = Val.size();
3192 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3193 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3194 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3195 return Owned(expr);
3196}
3197
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003198/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3199/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00003200/// C99 6.5.15
3201QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3202 SourceLocation QuestionLoc) {
Sebastian Redlbd261962009-04-16 17:51:27 +00003203 // C++ is sufficiently different to merit its own checker.
3204 if (getLangOptions().CPlusPlus)
3205 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3206
Chris Lattnere2897262009-02-18 04:28:32 +00003207 UsualUnaryConversions(Cond);
3208 UsualUnaryConversions(LHS);
3209 UsualUnaryConversions(RHS);
3210 QualType CondTy = Cond->getType();
3211 QualType LHSTy = LHS->getType();
3212 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003213
3214 // first, check the condition.
Sebastian Redlbd261962009-04-16 17:51:27 +00003215 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3216 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3217 << CondTy;
3218 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003219 }
Mike Stump9afab102009-02-19 03:04:26 +00003220
Chris Lattner992ae932008-01-06 22:42:25 +00003221 // Now check the two expressions.
Nate Begemane85f43d2009-08-10 23:49:36 +00003222 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3223 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003224
Chris Lattner992ae932008-01-06 22:42:25 +00003225 // If both operands have arithmetic type, do the usual arithmetic conversions
3226 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00003227 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3228 UsualArithmeticConversions(LHS, RHS);
3229 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003230 }
Mike Stump9afab102009-02-19 03:04:26 +00003231
Chris Lattner992ae932008-01-06 22:42:25 +00003232 // If both operands are the same structure or union type, the result is that
3233 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003234 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3235 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner98a425c2007-11-26 01:40:58 +00003236 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003237 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00003238 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00003239 return LHSTy.getUnqualifiedType();
Eli Friedman2b128322009-03-23 00:24:07 +00003240 // FIXME: Type of conditional expression must be complete in C mode.
Chris Lattner4b009652007-07-25 00:24:17 +00003241 }
Mike Stump9afab102009-02-19 03:04:26 +00003242
Chris Lattner992ae932008-01-06 22:42:25 +00003243 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00003244 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00003245 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3246 if (!LHSTy->isVoidType())
3247 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3248 << RHS->getSourceRange();
3249 if (!RHSTy->isVoidType())
3250 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3251 << LHS->getSourceRange();
3252 ImpCastExprToType(LHS, Context.VoidTy);
3253 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00003254 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00003255 }
Steve Naroff12ebf272008-01-08 01:11:38 +00003256 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3257 // the type of the other operand."
Steve Naroff79ae19a2009-07-14 18:25:06 +00003258 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003259 RHS->isNullPointerConstant(Context)) {
3260 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
3261 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003262 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00003263 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003264 LHS->isNullPointerConstant(Context)) {
3265 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
3266 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003267 }
David Chisnall44663db2009-08-17 16:35:33 +00003268 // Handle things like Class and struct objc_class*. Here we case the result
3269 // to the pseudo-builtin, because that will be implicitly cast back to the
3270 // redefinition type if an attempt is made to access its fields.
3271 if (LHSTy->isObjCClassType() &&
3272 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3273 ImpCastExprToType(RHS, LHSTy);
3274 return LHSTy;
3275 }
3276 if (RHSTy->isObjCClassType() &&
3277 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3278 ImpCastExprToType(LHS, RHSTy);
3279 return RHSTy;
3280 }
3281 // And the same for struct objc_object* / id
3282 if (LHSTy->isObjCIdType() &&
3283 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3284 ImpCastExprToType(RHS, LHSTy);
3285 return LHSTy;
3286 }
3287 if (RHSTy->isObjCIdType() &&
3288 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3289 ImpCastExprToType(LHS, RHSTy);
3290 return RHSTy;
3291 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003292 // Handle block pointer types.
3293 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3294 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3295 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3296 QualType destType = Context.getPointerType(Context.VoidTy);
3297 ImpCastExprToType(LHS, destType);
3298 ImpCastExprToType(RHS, destType);
3299 return destType;
3300 }
3301 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3302 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3303 return QualType();
Mike Stumpe97a8542009-05-07 03:14:14 +00003304 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003305 // We have 2 block pointer types.
3306 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3307 // Two identical block pointer types are always compatible.
Mike Stumpe97a8542009-05-07 03:14:14 +00003308 return LHSTy;
3309 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003310 // The block pointer types aren't identical, continue checking.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003311 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3312 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003313
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003314 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3315 rhptee.getUnqualifiedType())) {
Mike Stumpe97a8542009-05-07 03:14:14 +00003316 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3317 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3318 // In this situation, we assume void* type. No especially good
3319 // reason, but this is what gcc does, and we do have to pick
3320 // to get a consistent AST.
3321 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3322 ImpCastExprToType(LHS, incompatTy);
3323 ImpCastExprToType(RHS, incompatTy);
3324 return incompatTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003325 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003326 // The block pointer types are compatible.
3327 ImpCastExprToType(LHS, LHSTy);
3328 ImpCastExprToType(RHS, LHSTy);
Steve Naroff6ba22682009-04-08 17:05:15 +00003329 return LHSTy;
3330 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003331 // Check constraints for Objective-C object pointers types.
Steve Naroff329ec222009-07-10 23:34:53 +00003332 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003333
3334 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3335 // Two identical object pointer types are always compatible.
3336 return LHSTy;
3337 }
Steve Naroff329ec222009-07-10 23:34:53 +00003338 const ObjCObjectPointerType *LHSOPT = LHSTy->getAsObjCObjectPointerType();
3339 const ObjCObjectPointerType *RHSOPT = RHSTy->getAsObjCObjectPointerType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003340 QualType compositeType = LHSTy;
3341
3342 // If both operands are interfaces and either operand can be
3343 // assigned to the other, use that type as the composite
3344 // type. This allows
3345 // xxx ? (A*) a : (B*) b
3346 // where B is a subclass of A.
3347 //
3348 // Additionally, as for assignment, if either type is 'id'
3349 // allow silent coercion. Finally, if the types are
3350 // incompatible then make sure to use 'id' as the composite
3351 // type so the result is acceptable for sending messages to.
3352
3353 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3354 // It could return the composite type.
Steve Naroff329ec222009-07-10 23:34:53 +00003355 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahanian2e006d22009-08-22 22:27:17 +00003356 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003357 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahanian2e006d22009-08-22 22:27:17 +00003358 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003359 } else if ((LHSTy->isObjCQualifiedIdType() ||
3360 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff99eb86b2009-07-23 01:01:38 +00003361 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Steve Naroff329ec222009-07-10 23:34:53 +00003362 // Need to handle "id<xx>" explicitly.
3363 // GCC allows qualified id and any Objective-C type to devolve to
3364 // id. Currently localizing to here until clear this should be
3365 // part of ObjCQualifiedIdTypesAreCompatible.
3366 compositeType = Context.getObjCIdType();
3367 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003368 compositeType = Context.getObjCIdType();
3369 } else {
3370 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3371 << LHSTy << RHSTy
3372 << LHS->getSourceRange() << RHS->getSourceRange();
3373 QualType incompatTy = Context.getObjCIdType();
3374 ImpCastExprToType(LHS, incompatTy);
3375 ImpCastExprToType(RHS, incompatTy);
3376 return incompatTy;
3377 }
3378 // The object pointer types are compatible.
3379 ImpCastExprToType(LHS, compositeType);
3380 ImpCastExprToType(RHS, compositeType);
3381 return compositeType;
3382 }
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003383 // Check Objective-C object pointer types and 'void *'
3384 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003385 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003386 QualType rhptee = RHSTy->getAsObjCObjectPointerType()->getPointeeType();
3387 QualType destPointee = lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3388 QualType destType = Context.getPointerType(destPointee);
3389 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3390 ImpCastExprToType(RHS, destType); // promote to void*
3391 return destType;
3392 }
3393 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
3394 QualType lhptee = LHSTy->getAsObjCObjectPointerType()->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003395 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003396 QualType destPointee = rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3397 QualType destType = Context.getPointerType(destPointee);
3398 ImpCastExprToType(RHS, destType); // add qualifiers if necessary
3399 ImpCastExprToType(LHS, destType); // promote to void*
3400 return destType;
3401 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003402 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3403 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3404 // get the "pointed to" types
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003405 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3406 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003407
3408 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3409 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3410 // Figure out necessary qualifiers (C99 6.5.15p6)
3411 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3412 QualType destType = Context.getPointerType(destPointee);
3413 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3414 ImpCastExprToType(RHS, destType); // promote to void*
3415 return destType;
3416 }
3417 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3418 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3419 QualType destType = Context.getPointerType(destPointee);
3420 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3421 ImpCastExprToType(RHS, destType); // promote to void*
3422 return destType;
3423 }
3424
3425 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3426 // Two identical pointer types are always compatible.
3427 return LHSTy;
3428 }
3429 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3430 rhptee.getUnqualifiedType())) {
3431 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3432 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3433 // In this situation, we assume void* type. No especially good
3434 // reason, but this is what gcc does, and we do have to pick
3435 // to get a consistent AST.
3436 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3437 ImpCastExprToType(LHS, incompatTy);
3438 ImpCastExprToType(RHS, incompatTy);
3439 return incompatTy;
3440 }
3441 // The pointer types are compatible.
3442 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3443 // differently qualified versions of compatible types, the result type is
3444 // a pointer to an appropriately qualified version of the *composite*
3445 // type.
3446 // FIXME: Need to calculate the composite type.
3447 // FIXME: Need to add qualifiers
3448 ImpCastExprToType(LHS, LHSTy);
3449 ImpCastExprToType(RHS, LHSTy);
3450 return LHSTy;
3451 }
3452
3453 // GCC compatibility: soften pointer/integer mismatch.
3454 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3455 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3456 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3457 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3458 return RHSTy;
3459 }
3460 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3461 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3462 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3463 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3464 return LHSTy;
3465 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00003466
Chris Lattner992ae932008-01-06 22:42:25 +00003467 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00003468 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3469 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003470 return QualType();
3471}
3472
Steve Naroff87d58b42007-09-16 03:34:24 +00003473/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00003474/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003475Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3476 SourceLocation ColonLoc,
3477 ExprArg Cond, ExprArg LHS,
3478 ExprArg RHS) {
3479 Expr *CondExpr = (Expr *) Cond.get();
3480 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00003481
3482 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3483 // was the condition.
3484 bool isLHSNull = LHSExpr == 0;
3485 if (isLHSNull)
3486 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003487
3488 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00003489 RHSExpr, QuestionLoc);
3490 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003491 return ExprError();
3492
3493 Cond.release();
3494 LHS.release();
3495 RHS.release();
Douglas Gregor34619872009-08-26 14:37:04 +00003496 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff774e4152009-01-21 00:14:39 +00003497 isLHSNull ? 0 : LHSExpr,
Douglas Gregor34619872009-08-26 14:37:04 +00003498 ColonLoc, RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00003499}
3500
Chris Lattner4b009652007-07-25 00:24:17 +00003501// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00003502// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00003503// routine is it effectively iqnores the qualifiers on the top level pointee.
3504// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3505// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00003506Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003507Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3508 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003509
David Chisnall44663db2009-08-17 16:35:33 +00003510 if ((lhsType->isObjCClassType() &&
3511 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3512 (rhsType->isObjCClassType() &&
3513 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3514 return Compatible;
3515 }
3516
Chris Lattner4b009652007-07-25 00:24:17 +00003517 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003518 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3519 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003520
Chris Lattner4b009652007-07-25 00:24:17 +00003521 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003522 lhptee = Context.getCanonicalType(lhptee);
3523 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00003524
Chris Lattner005ed752008-01-04 18:04:52 +00003525 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003526
3527 // C99 6.5.16.1p1: This following citation is common to constraints
3528 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3529 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00003530 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003531 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00003532 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00003533
Mike Stump9afab102009-02-19 03:04:26 +00003534 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3535 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00003536 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00003537 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003538 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003539 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00003540
Chris Lattner4ca3d772008-01-03 22:56:36 +00003541 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003542 assert(rhptee->isFunctionType());
3543 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003544 }
Mike Stump9afab102009-02-19 03:04:26 +00003545
Chris Lattner4ca3d772008-01-03 22:56:36 +00003546 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003547 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003548 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003549
3550 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003551 assert(lhptee->isFunctionType());
3552 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003553 }
Mike Stump9afab102009-02-19 03:04:26 +00003554 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00003555 // unqualified versions of compatible types, ...
Eli Friedman6ca28cb2009-03-22 23:59:44 +00003556 lhptee = lhptee.getUnqualifiedType();
3557 rhptee = rhptee.getUnqualifiedType();
3558 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3559 // Check if the pointee types are compatible ignoring the sign.
3560 // We explicitly check for char so that we catch "char" vs
3561 // "unsigned char" on systems where "char" is unsigned.
3562 if (lhptee->isCharType()) {
3563 lhptee = Context.UnsignedCharTy;
3564 } else if (lhptee->isSignedIntegerType()) {
3565 lhptee = Context.getCorrespondingUnsignedType(lhptee);
3566 }
3567 if (rhptee->isCharType()) {
3568 rhptee = Context.UnsignedCharTy;
3569 } else if (rhptee->isSignedIntegerType()) {
3570 rhptee = Context.getCorrespondingUnsignedType(rhptee);
3571 }
3572 if (lhptee == rhptee) {
3573 // Types are compatible ignoring the sign. Qualifier incompatibility
3574 // takes priority over sign incompatibility because the sign
3575 // warning can be disabled.
3576 if (ConvTy != Compatible)
3577 return ConvTy;
3578 return IncompatiblePointerSign;
3579 }
3580 // General pointer incompatibility takes priority over qualifiers.
3581 return IncompatiblePointer;
3582 }
Chris Lattner005ed752008-01-04 18:04:52 +00003583 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003584}
3585
Steve Naroff3454b6c2008-09-04 15:10:53 +00003586/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3587/// block pointer types are compatible or whether a block and normal pointer
3588/// are compatible. It is more restrict than comparing two function pointer
3589// types.
Mike Stump9afab102009-02-19 03:04:26 +00003590Sema::AssignConvertType
3591Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00003592 QualType rhsType) {
3593 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003594
Steve Naroff3454b6c2008-09-04 15:10:53 +00003595 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003596 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3597 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003598
Steve Naroff3454b6c2008-09-04 15:10:53 +00003599 // make sure we operate on the canonical type
3600 lhptee = Context.getCanonicalType(lhptee);
3601 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00003602
Steve Naroff3454b6c2008-09-04 15:10:53 +00003603 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003604
Steve Naroff3454b6c2008-09-04 15:10:53 +00003605 // For blocks we enforce that qualifiers are identical.
3606 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3607 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00003608
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00003609 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00003610 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003611 return ConvTy;
3612}
3613
Mike Stump9afab102009-02-19 03:04:26 +00003614/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3615/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00003616/// pointers. Here are some objectionable examples that GCC considers warnings:
3617///
3618/// int a, *pint;
3619/// short *pshort;
3620/// struct foo *pfoo;
3621///
3622/// pint = pshort; // warning: assignment from incompatible pointer type
3623/// a = pint; // warning: assignment makes integer from pointer without a cast
3624/// pint = a; // warning: assignment makes pointer from integer without a cast
3625/// pint = pfoo; // warning: assignment from incompatible pointer type
3626///
3627/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00003628/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00003629///
Chris Lattner005ed752008-01-04 18:04:52 +00003630Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003631Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00003632 // Get canonical types. We're not formatting these types, just comparing
3633 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003634 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3635 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00003636
3637 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00003638 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00003639
David Chisnall44663db2009-08-17 16:35:33 +00003640 if ((lhsType->isObjCClassType() &&
3641 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3642 (rhsType->isObjCClassType() &&
3643 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3644 return Compatible;
3645 }
3646
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003647 // If the left-hand side is a reference type, then we are in a
3648 // (rare!) case where we've allowed the use of references in C,
3649 // e.g., as a parameter type in a built-in function. In this case,
3650 // just make sure that the type referenced is compatible with the
3651 // right-hand side type. The caller is responsible for adjusting
3652 // lhsType so that the resulting expression does not have reference
3653 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003654 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003655 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00003656 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003657 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003658 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003659 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3660 // to the same ExtVector type.
3661 if (lhsType->isExtVectorType()) {
3662 if (rhsType->isExtVectorType())
3663 return lhsType == rhsType ? Compatible : Incompatible;
3664 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3665 return Compatible;
3666 }
3667
Nate Begemanc5f0f652008-07-14 18:02:46 +00003668 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003669 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00003670 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00003671 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003672 if (getLangOptions().LaxVectorConversions &&
3673 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003674 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00003675 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003676 }
3677 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00003678 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003679
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003680 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00003681 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003682
Chris Lattner390564e2008-04-07 06:49:41 +00003683 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003684 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003685 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003686
Chris Lattner390564e2008-04-07 06:49:41 +00003687 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003688 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003689
Steve Naroff8194a542009-07-20 17:56:53 +00003690 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003691 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003692 if (lhsType->isVoidPointerType()) // an exception to the rule.
3693 return Compatible;
3694 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003695 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003696 if (rhsType->getAs<BlockPointerType>()) {
3697 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003698 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00003699
3700 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003701 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003702 return Compatible;
3703 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003704 return Incompatible;
3705 }
3706
3707 if (isa<BlockPointerType>(lhsType)) {
3708 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00003709 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00003710
Steve Naroffa982c712008-09-29 18:10:17 +00003711 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003712 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003713 return Compatible;
3714
Steve Naroff3454b6c2008-09-04 15:10:53 +00003715 if (rhsType->isBlockPointerType())
3716 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003717
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003718 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff3454b6c2008-09-04 15:10:53 +00003719 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003720 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003721 }
Chris Lattner1853da22008-01-04 23:18:45 +00003722 return Incompatible;
3723 }
3724
Steve Naroff329ec222009-07-10 23:34:53 +00003725 if (isa<ObjCObjectPointerType>(lhsType)) {
3726 if (rhsType->isIntegerType())
3727 return IntToPointer;
Steve Naroff8194a542009-07-20 17:56:53 +00003728
3729 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003730 if (isa<PointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003731 if (rhsType->isVoidPointerType()) // an exception to the rule.
3732 return Compatible;
3733 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003734 }
3735 if (rhsType->isObjCObjectPointerType()) {
Steve Naroff7bffd372009-07-15 18:40:39 +00003736 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3737 return Compatible;
Steve Naroff8194a542009-07-20 17:56:53 +00003738 if (Context.typesAreCompatible(lhsType, rhsType))
3739 return Compatible;
Steve Naroff99eb86b2009-07-23 01:01:38 +00003740 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3741 return IncompatibleObjCQualifiedId;
Steve Naroff8194a542009-07-20 17:56:53 +00003742 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003743 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003744 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff329ec222009-07-10 23:34:53 +00003745 if (RHSPT->getPointeeType()->isVoidType())
3746 return Compatible;
3747 }
3748 // Treat block pointers as objects.
3749 if (rhsType->isBlockPointerType())
3750 return Compatible;
3751 return Incompatible;
3752 }
Chris Lattner390564e2008-04-07 06:49:41 +00003753 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003754 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00003755 if (lhsType == Context.BoolTy)
3756 return Compatible;
3757
3758 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003759 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00003760
Mike Stump9afab102009-02-19 03:04:26 +00003761 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003762 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003763
3764 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003765 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003766 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003767 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003768 }
Steve Naroff329ec222009-07-10 23:34:53 +00003769 if (isa<ObjCObjectPointerType>(rhsType)) {
3770 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3771 if (lhsType == Context.BoolTy)
3772 return Compatible;
3773
3774 if (lhsType->isIntegerType())
3775 return PointerToInt;
3776
Steve Naroff8194a542009-07-20 17:56:53 +00003777 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003778 if (isa<PointerType>(lhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003779 if (lhsType->isVoidPointerType()) // an exception to the rule.
3780 return Compatible;
3781 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003782 }
3783 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003784 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff329ec222009-07-10 23:34:53 +00003785 return Compatible;
3786 return Incompatible;
3787 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003788
Chris Lattner1853da22008-01-04 23:18:45 +00003789 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00003790 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003791 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00003792 }
3793 return Incompatible;
3794}
3795
Douglas Gregor144b06c2009-04-29 22:16:16 +00003796/// \brief Constructs a transparent union from an expression that is
3797/// used to initialize the transparent union.
3798static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3799 QualType UnionType, FieldDecl *Field) {
3800 // Build an initializer list that designates the appropriate member
3801 // of the transparent union.
3802 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3803 &E, 1,
3804 SourceLocation());
3805 Initializer->setType(UnionType);
3806 Initializer->setInitializedFieldInUnion(Field);
3807
3808 // Build a compound literal constructing a value of the transparent
3809 // union type from this initializer list.
3810 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3811 false);
3812}
3813
3814Sema::AssignConvertType
3815Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3816 QualType FromType = rExpr->getType();
3817
3818 // If the ArgType is a Union type, we want to handle a potential
3819 // transparent_union GCC extension.
3820 const RecordType *UT = ArgType->getAsUnionType();
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003821 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor144b06c2009-04-29 22:16:16 +00003822 return Incompatible;
3823
3824 // The field to initialize within the transparent union.
3825 RecordDecl *UD = UT->getDecl();
3826 FieldDecl *InitField = 0;
3827 // It's compatible if the expression matches any of the fields.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003828 for (RecordDecl::field_iterator it = UD->field_begin(),
3829 itend = UD->field_end();
Douglas Gregor144b06c2009-04-29 22:16:16 +00003830 it != itend; ++it) {
3831 if (it->getType()->isPointerType()) {
3832 // If the transparent union contains a pointer type, we allow:
3833 // 1) void pointer
3834 // 2) null pointer constant
3835 if (FromType->isPointerType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003836 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor144b06c2009-04-29 22:16:16 +00003837 ImpCastExprToType(rExpr, it->getType());
3838 InitField = *it;
3839 break;
3840 }
3841
3842 if (rExpr->isNullPointerConstant(Context)) {
3843 ImpCastExprToType(rExpr, it->getType());
3844 InitField = *it;
3845 break;
3846 }
3847 }
3848
3849 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3850 == Compatible) {
3851 InitField = *it;
3852 break;
3853 }
3854 }
3855
3856 if (!InitField)
3857 return Incompatible;
3858
3859 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3860 return Compatible;
3861}
3862
Chris Lattner005ed752008-01-04 18:04:52 +00003863Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003864Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003865 if (getLangOptions().CPlusPlus) {
3866 if (!lhsType->isRecordType()) {
3867 // C++ 5.17p3: If the left operand is not of class type, the
3868 // expression is implicitly converted (C++ 4) to the
3869 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00003870 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3871 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003872 return Incompatible;
Chris Lattner79e9a422009-04-12 09:02:39 +00003873 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003874 }
3875
3876 // FIXME: Currently, we fall through and treat C++ classes like C
3877 // structures.
3878 }
3879
Steve Naroffcdee22d2007-11-27 17:58:44 +00003880 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3881 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00003882 if ((lhsType->isPointerType() ||
Steve Naroff329ec222009-07-10 23:34:53 +00003883 lhsType->isObjCObjectPointerType() ||
Mike Stump9afab102009-02-19 03:04:26 +00003884 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00003885 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003886 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00003887 return Compatible;
3888 }
Mike Stump9afab102009-02-19 03:04:26 +00003889
Chris Lattner5f505bf2007-10-16 02:55:40 +00003890 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00003891 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00003892 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00003893 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00003894 //
Mike Stump9afab102009-02-19 03:04:26 +00003895 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00003896 if (!lhsType->isReferenceType())
3897 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00003898
Chris Lattner005ed752008-01-04 18:04:52 +00003899 Sema::AssignConvertType result =
3900 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00003901
Steve Naroff0f32f432007-08-24 22:33:52 +00003902 // C99 6.5.16.1p2: The value of the right operand is converted to the
3903 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003904 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3905 // so that we can use references in built-in functions even in C.
3906 // The getNonReferenceType() call makes sure that the resulting expression
3907 // does not have reference type.
Douglas Gregor144b06c2009-04-29 22:16:16 +00003908 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003909 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00003910 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00003911}
3912
Chris Lattner1eafdea2008-11-18 01:30:42 +00003913QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003914 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003915 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003916 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00003917 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003918}
3919
Mike Stump9afab102009-02-19 03:04:26 +00003920inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00003921 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00003922 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00003923 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003924 QualType lhsType =
3925 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3926 QualType rhsType =
3927 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00003928
Nate Begemanc5f0f652008-07-14 18:02:46 +00003929 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00003930 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00003931 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00003932
Nate Begemanc5f0f652008-07-14 18:02:46 +00003933 // Handle the case of a vector & extvector type of the same size and element
3934 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00003935 if (getLangOptions().LaxVectorConversions) {
3936 // FIXME: Should we warn here?
3937 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003938 if (const VectorType *RV = rhsType->getAsVectorType())
3939 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00003940 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003941 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00003942 }
3943 }
3944 }
Mike Stump9afab102009-02-19 03:04:26 +00003945
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003946 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
3947 // swap back (so that we don't reverse the inputs to a subtract, for instance.
3948 bool swapped = false;
3949 if (rhsType->isExtVectorType()) {
3950 swapped = true;
3951 std::swap(rex, lex);
3952 std::swap(rhsType, lhsType);
3953 }
3954
Nate Begemanf1695892009-06-28 19:12:57 +00003955 // Handle the case of an ext vector and scalar.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003956 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) {
3957 QualType EltTy = LV->getElementType();
3958 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
3959 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00003960 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003961 if (swapped) std::swap(rex, lex);
3962 return lhsType;
3963 }
3964 }
3965 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
3966 rhsType->isRealFloatingType()) {
3967 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00003968 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003969 if (swapped) std::swap(rex, lex);
3970 return lhsType;
3971 }
Nate Begemanec2d1062007-12-30 02:59:45 +00003972 }
3973 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003974
Nate Begemanf1695892009-06-28 19:12:57 +00003975 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner70b93d82008-11-18 22:52:51 +00003976 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003977 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003978 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003979 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00003980}
3981
Chris Lattner4b009652007-07-25 00:24:17 +00003982inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003983 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003984{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00003985 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003986 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003987
Steve Naroff8f708362007-08-24 19:07:16 +00003988 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003989
Chris Lattner4b009652007-07-25 00:24:17 +00003990 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00003991 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003992 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003993}
3994
3995inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003996 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003997{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00003998 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3999 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4000 return CheckVectorOperands(Loc, lex, rex);
4001 return InvalidOperands(Loc, lex, rex);
4002 }
Chris Lattner4b009652007-07-25 00:24:17 +00004003
Steve Naroff8f708362007-08-24 19:07:16 +00004004 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004005
Chris Lattner4b009652007-07-25 00:24:17 +00004006 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00004007 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004008 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004009}
4010
4011inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Eli Friedman3cd92882009-03-28 01:22:36 +00004012 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
Chris Lattner4b009652007-07-25 00:24:17 +00004013{
Eli Friedman3cd92882009-03-28 01:22:36 +00004014 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4015 QualType compType = CheckVectorOperands(Loc, lex, rex);
4016 if (CompLHSTy) *CompLHSTy = compType;
4017 return compType;
4018 }
Chris Lattner4b009652007-07-25 00:24:17 +00004019
Eli Friedman3cd92882009-03-28 01:22:36 +00004020 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004021
Chris Lattner4b009652007-07-25 00:24:17 +00004022 // handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00004023 if (lex->getType()->isArithmeticType() &&
4024 rex->getType()->isArithmeticType()) {
4025 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00004026 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00004027 }
Chris Lattner4b009652007-07-25 00:24:17 +00004028
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004029 // Put any potential pointer into PExp
4030 Expr* PExp = lex, *IExp = rex;
Steve Naroff79ae19a2009-07-14 18:25:06 +00004031 if (IExp->getType()->isAnyPointerType())
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004032 std::swap(PExp, IExp);
4033
Steve Naroff79ae19a2009-07-14 18:25:06 +00004034 if (PExp->getType()->isAnyPointerType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00004035
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004036 if (IExp->getType()->isIntegerType()) {
Steve Naroff18b38122009-07-13 21:20:41 +00004037 QualType PointeeTy = PExp->getType()->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00004038
Chris Lattner184f92d2009-04-24 23:50:08 +00004039 // Check for arithmetic on pointers to incomplete types.
4040 if (PointeeTy->isVoidType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00004041 if (getLangOptions().CPlusPlus) {
4042 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner8ba580c2008-11-19 05:08:23 +00004043 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004044 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004045 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004046
4047 // GNU extension: arithmetic on pointer to void
4048 Diag(Loc, diag::ext_gnu_void_ptr)
4049 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner184f92d2009-04-24 23:50:08 +00004050 } else if (PointeeTy->isFunctionType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00004051 if (getLangOptions().CPlusPlus) {
4052 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4053 << lex->getType() << lex->getSourceRange();
4054 return QualType();
4055 }
4056
4057 // GNU extension: arithmetic on pointer to function
4058 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4059 << lex->getType() << lex->getSourceRange();
Steve Naroff3fc227b2009-07-13 21:32:29 +00004060 } else {
Steve Naroff18b38122009-07-13 21:20:41 +00004061 // Check if we require a complete type.
4062 if (((PExp->getType()->isPointerType() &&
Steve Naroff3fc227b2009-07-13 21:32:29 +00004063 !PExp->getType()->isDependentType()) ||
Steve Naroff18b38122009-07-13 21:20:41 +00004064 PExp->getType()->isObjCObjectPointerType()) &&
4065 RequireCompleteType(Loc, PointeeTy,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004066 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4067 << PExp->getSourceRange()
4068 << PExp->getType()))
Steve Naroff18b38122009-07-13 21:20:41 +00004069 return QualType();
4070 }
Chris Lattner184f92d2009-04-24 23:50:08 +00004071 // Diagnose bad cases where we step over interface counts.
4072 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4073 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4074 << PointeeTy << PExp->getSourceRange();
4075 return QualType();
4076 }
4077
Eli Friedman3cd92882009-03-28 01:22:36 +00004078 if (CompLHSTy) {
Eli Friedman1931cc82009-08-20 04:21:42 +00004079 QualType LHSTy = Context.isPromotableBitField(lex);
4080 if (LHSTy.isNull()) {
4081 LHSTy = lex->getType();
4082 if (LHSTy->isPromotableIntegerType())
4083 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004084 }
Eli Friedman3cd92882009-03-28 01:22:36 +00004085 *CompLHSTy = LHSTy;
4086 }
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004087 return PExp->getType();
4088 }
4089 }
4090
Chris Lattner1eafdea2008-11-18 01:30:42 +00004091 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004092}
4093
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004094// C99 6.5.6
4095QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman3cd92882009-03-28 01:22:36 +00004096 SourceLocation Loc, QualType* CompLHSTy) {
4097 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4098 QualType compType = CheckVectorOperands(Loc, lex, rex);
4099 if (CompLHSTy) *CompLHSTy = compType;
4100 return compType;
4101 }
Mike Stump9afab102009-02-19 03:04:26 +00004102
Eli Friedman3cd92882009-03-28 01:22:36 +00004103 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump9afab102009-02-19 03:04:26 +00004104
Chris Lattnerf6da2912007-12-09 21:53:25 +00004105 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00004106
Chris Lattnerf6da2912007-12-09 21:53:25 +00004107 // Handle the common case first (both operands are arithmetic).
Mike Stumpea3d74e2009-05-07 18:43:07 +00004108 if (lex->getType()->isArithmeticType()
4109 && rex->getType()->isArithmeticType()) {
Eli Friedman3cd92882009-03-28 01:22:36 +00004110 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00004111 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00004112 }
Steve Naroff329ec222009-07-10 23:34:53 +00004113
Chris Lattnerf6da2912007-12-09 21:53:25 +00004114 // Either ptr - int or ptr - ptr.
Steve Naroff79ae19a2009-07-14 18:25:06 +00004115 if (lex->getType()->isAnyPointerType()) {
Steve Naroff7982a642009-07-13 17:19:15 +00004116 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004117
Douglas Gregor05e28f62009-03-24 19:52:54 +00004118 // The LHS must be an completely-defined object type.
Douglas Gregorb3193242009-01-23 00:36:41 +00004119
Douglas Gregor05e28f62009-03-24 19:52:54 +00004120 bool ComplainAboutVoid = false;
4121 Expr *ComplainAboutFunc = 0;
4122 if (lpointee->isVoidType()) {
4123 if (getLangOptions().CPlusPlus) {
4124 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4125 << lex->getSourceRange() << rex->getSourceRange();
4126 return QualType();
4127 }
4128
4129 // GNU C extension: arithmetic on pointer to void
4130 ComplainAboutVoid = true;
4131 } else if (lpointee->isFunctionType()) {
4132 if (getLangOptions().CPlusPlus) {
4133 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004134 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004135 return QualType();
4136 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004137
4138 // GNU C extension: arithmetic on pointer to function
4139 ComplainAboutFunc = lex;
4140 } else if (!lpointee->isDependentType() &&
4141 RequireCompleteType(Loc, lpointee,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004142 PDiag(diag::err_typecheck_sub_ptr_object)
4143 << lex->getSourceRange()
4144 << lex->getType()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00004145 return QualType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004146
Chris Lattner184f92d2009-04-24 23:50:08 +00004147 // Diagnose bad cases where we step over interface counts.
4148 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4149 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4150 << lpointee << lex->getSourceRange();
4151 return QualType();
4152 }
4153
Chris Lattnerf6da2912007-12-09 21:53:25 +00004154 // The result type of a pointer-int computation is the pointer type.
Douglas Gregor05e28f62009-03-24 19:52:54 +00004155 if (rex->getType()->isIntegerType()) {
4156 if (ComplainAboutVoid)
4157 Diag(Loc, diag::ext_gnu_void_ptr)
4158 << lex->getSourceRange() << rex->getSourceRange();
4159 if (ComplainAboutFunc)
4160 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4161 << ComplainAboutFunc->getType()
4162 << ComplainAboutFunc->getSourceRange();
4163
Eli Friedman3cd92882009-03-28 01:22:36 +00004164 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004165 return lex->getType();
Douglas Gregor05e28f62009-03-24 19:52:54 +00004166 }
Mike Stump9afab102009-02-19 03:04:26 +00004167
Chris Lattnerf6da2912007-12-09 21:53:25 +00004168 // Handle pointer-pointer subtractions.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004169 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman50727042008-02-08 01:19:44 +00004170 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004171
Douglas Gregor05e28f62009-03-24 19:52:54 +00004172 // RHS must be a completely-type object type.
4173 // Handle the GNU void* extension.
4174 if (rpointee->isVoidType()) {
4175 if (getLangOptions().CPlusPlus) {
4176 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4177 << lex->getSourceRange() << rex->getSourceRange();
4178 return QualType();
4179 }
Mike Stump9afab102009-02-19 03:04:26 +00004180
Douglas Gregor05e28f62009-03-24 19:52:54 +00004181 ComplainAboutVoid = true;
4182 } else if (rpointee->isFunctionType()) {
4183 if (getLangOptions().CPlusPlus) {
4184 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004185 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004186 return QualType();
4187 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004188
4189 // GNU extension: arithmetic on pointer to function
4190 if (!ComplainAboutFunc)
4191 ComplainAboutFunc = rex;
4192 } else if (!rpointee->isDependentType() &&
4193 RequireCompleteType(Loc, rpointee,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004194 PDiag(diag::err_typecheck_sub_ptr_object)
4195 << rex->getSourceRange()
4196 << rex->getType()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00004197 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004198
Eli Friedman143ddc92009-05-16 13:54:38 +00004199 if (getLangOptions().CPlusPlus) {
4200 // Pointee types must be the same: C++ [expr.add]
4201 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4202 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4203 << lex->getType() << rex->getType()
4204 << lex->getSourceRange() << rex->getSourceRange();
4205 return QualType();
4206 }
4207 } else {
4208 // Pointee types must be compatible C99 6.5.6p3
4209 if (!Context.typesAreCompatible(
4210 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4211 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4212 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4213 << lex->getType() << rex->getType()
4214 << lex->getSourceRange() << rex->getSourceRange();
4215 return QualType();
4216 }
Chris Lattnerf6da2912007-12-09 21:53:25 +00004217 }
Mike Stump9afab102009-02-19 03:04:26 +00004218
Douglas Gregor05e28f62009-03-24 19:52:54 +00004219 if (ComplainAboutVoid)
4220 Diag(Loc, diag::ext_gnu_void_ptr)
4221 << lex->getSourceRange() << rex->getSourceRange();
4222 if (ComplainAboutFunc)
4223 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4224 << ComplainAboutFunc->getType()
4225 << ComplainAboutFunc->getSourceRange();
Eli Friedman3cd92882009-03-28 01:22:36 +00004226
4227 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004228 return Context.getPointerDiffType();
4229 }
4230 }
Mike Stump9afab102009-02-19 03:04:26 +00004231
Chris Lattner1eafdea2008-11-18 01:30:42 +00004232 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004233}
4234
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004235// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00004236QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004237 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00004238 // C99 6.5.7p2: Each of the operands shall have integer type.
4239 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004240 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00004241
Chris Lattner2c8bff72007-12-12 05:47:28 +00004242 // Shifts don't perform usual arithmetic conversions, they just do integer
4243 // promotions on each operand. C99 6.5.7p3
Eli Friedman1931cc82009-08-20 04:21:42 +00004244 QualType LHSTy = Context.isPromotableBitField(lex);
4245 if (LHSTy.isNull()) {
4246 LHSTy = lex->getType();
4247 if (LHSTy->isPromotableIntegerType())
4248 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004249 }
Chris Lattnerbb19bc42007-12-13 07:28:16 +00004250 if (!isCompAssign)
Eli Friedman3cd92882009-03-28 01:22:36 +00004251 ImpCastExprToType(lex, LHSTy);
4252
Chris Lattner2c8bff72007-12-12 05:47:28 +00004253 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004254
Ryan Flynnf109fff2009-08-07 16:20:20 +00004255 // Sanity-check shift operands
4256 llvm::APSInt Right;
4257 // Check right/shifter operand
4258 if (rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynna5e76932009-08-08 19:18:23 +00004259 if (Right.isNegative())
Ryan Flynnf109fff2009-08-07 16:20:20 +00004260 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4261 else {
4262 llvm::APInt LeftBits(Right.getBitWidth(),
4263 Context.getTypeSize(lex->getType()));
4264 if (Right.uge(LeftBits))
4265 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4266 }
4267 }
4268
Chris Lattner2c8bff72007-12-12 05:47:28 +00004269 // "The type of the result is that of the promoted left operand."
Eli Friedman3cd92882009-03-28 01:22:36 +00004270 return LHSTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004271}
4272
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004273// C99 6.5.8, C++ [expr.rel]
Chris Lattner1eafdea2008-11-18 01:30:42 +00004274QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor1f12c352009-04-06 18:45:53 +00004275 unsigned OpaqueOpc, bool isRelational) {
4276 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4277
Nate Begemanc5f0f652008-07-14 18:02:46 +00004278 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004279 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00004280
Chris Lattner254f3bc2007-08-26 01:18:55 +00004281 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00004282 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4283 UsualArithmeticConversions(lex, rex);
4284 else {
4285 UsualUnaryConversions(lex);
4286 UsualUnaryConversions(rex);
4287 }
Chris Lattner4b009652007-07-25 00:24:17 +00004288 QualType lType = lex->getType();
4289 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004290
Mike Stumpea3d74e2009-05-07 18:43:07 +00004291 if (!lType->isFloatingType()
4292 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004293 // For non-floating point types, check for self-comparisons of the form
4294 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4295 // often indicate logic errors in the program.
Ted Kremenek264b5cb2009-03-20 19:57:37 +00004296 // NOTE: Don't warn about comparisons of enum constants. These can arise
4297 // from macro expansions, and are usually quite deliberate.
Chris Lattner4e479f92009-03-08 19:39:53 +00004298 Expr *LHSStripped = lex->IgnoreParens();
4299 Expr *RHSStripped = rex->IgnoreParens();
4300 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4301 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekf042dc62009-03-20 18:35:45 +00004302 if (DRL->getDecl() == DRR->getDecl() &&
4303 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump9afab102009-02-19 03:04:26 +00004304 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner4e479f92009-03-08 19:39:53 +00004305
4306 if (isa<CastExpr>(LHSStripped))
4307 LHSStripped = LHSStripped->IgnoreParenCasts();
4308 if (isa<CastExpr>(RHSStripped))
4309 RHSStripped = RHSStripped->IgnoreParenCasts();
4310
4311 // Warn about comparisons against a string constant (unless the other
4312 // operand is null), the user probably wants strcmp.
Douglas Gregor1f12c352009-04-06 18:45:53 +00004313 Expr *literalString = 0;
4314 Expr *literalStringStripped = 0;
Chris Lattner4e479f92009-03-08 19:39:53 +00004315 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00004316 !RHSStripped->isNullPointerConstant(Context)) {
4317 literalString = lex;
4318 literalStringStripped = LHSStripped;
Mike Stump90fc78e2009-08-04 21:02:39 +00004319 } else if ((isa<StringLiteral>(RHSStripped) ||
4320 isa<ObjCEncodeExpr>(RHSStripped)) &&
4321 !LHSStripped->isNullPointerConstant(Context)) {
Douglas Gregor1f12c352009-04-06 18:45:53 +00004322 literalString = rex;
4323 literalStringStripped = RHSStripped;
4324 }
4325
4326 if (literalString) {
4327 std::string resultComparison;
4328 switch (Opc) {
4329 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4330 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4331 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4332 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4333 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4334 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4335 default: assert(false && "Invalid comparison operator");
4336 }
4337 Diag(Loc, diag::warn_stringcompare)
4338 << isa<ObjCEncodeExpr>(literalStringStripped)
4339 << literalString->getSourceRange()
Douglas Gregor3faaa812009-04-01 23:51:29 +00004340 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4341 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4342 "strcmp(")
4343 << CodeModificationHint::CreateInsertion(
4344 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor1f12c352009-04-06 18:45:53 +00004345 resultComparison);
4346 }
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00004347 }
Mike Stump9afab102009-02-19 03:04:26 +00004348
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004349 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner4e479f92009-03-08 19:39:53 +00004350 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004351
Chris Lattner254f3bc2007-08-26 01:18:55 +00004352 if (isRelational) {
4353 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004354 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004355 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00004356 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00004357 if (lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004358 assert(rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004359 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00004360 }
Mike Stump9afab102009-02-19 03:04:26 +00004361
Chris Lattner254f3bc2007-08-26 01:18:55 +00004362 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004363 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004364 }
Mike Stump9afab102009-02-19 03:04:26 +00004365
Chris Lattner22be8422007-08-26 01:10:14 +00004366 bool LHSIsNull = lex->isNullPointerConstant(Context);
4367 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00004368
Chris Lattner254f3bc2007-08-26 01:18:55 +00004369 // All of the following pointer related warnings are GCC extensions, except
4370 // when handling null pointer constants. One day, we can consider making them
4371 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00004372 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00004373 QualType LCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004374 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00004375 QualType RCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004376 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00004377
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004378 if (getLangOptions().CPlusPlus) {
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004379 if (LCanPointeeTy == RCanPointeeTy)
4380 return ResultTy;
4381
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004382 // C++ [expr.rel]p2:
4383 // [...] Pointer conversions (4.10) and qualification
4384 // conversions (4.4) are performed on pointer operands (or on
4385 // a pointer operand and a null pointer constant) to bring
4386 // them to their composite pointer type. [...]
4387 //
Douglas Gregor70be4db2009-08-24 17:42:35 +00004388 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004389 // comparisons of pointers.
Douglas Gregorcf651d22009-05-05 04:50:50 +00004390 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004391 if (T.isNull()) {
4392 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4393 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4394 return QualType();
4395 }
4396
4397 ImpCastExprToType(lex, T);
4398 ImpCastExprToType(rex, T);
4399 return ResultTy;
4400 }
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004401 // C99 6.5.9p2 and C99 6.5.8p2
4402 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4403 RCanPointeeTy.getUnqualifiedType())) {
4404 // Valid unless a relational comparison of function pointers
4405 if (isRelational && LCanPointeeTy->isFunctionType()) {
4406 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4407 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4408 }
4409 } else if (!isRelational &&
4410 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4411 // Valid unless comparison between non-null pointer and function pointer
4412 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4413 && !LHSIsNull && !RHSIsNull) {
4414 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4415 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4416 }
4417 } else {
4418 // Invalid
Chris Lattner70b93d82008-11-18 22:52:51 +00004419 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004420 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004421 }
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004422 if (LCanPointeeTy != RCanPointeeTy)
4423 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004424 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004425 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004426
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004427 if (getLangOptions().CPlusPlus) {
Douglas Gregor70be4db2009-08-24 17:42:35 +00004428 // Comparison of pointers with null pointer constants and equality
4429 // comparisons of member pointers to null pointer constants.
4430 if (RHSIsNull &&
4431 (lType->isPointerType() ||
4432 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson9a385522009-08-24 18:03:14 +00004433 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004434 return ResultTy;
4435 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004436 if (LHSIsNull &&
4437 (rType->isPointerType() ||
4438 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson9a385522009-08-24 18:03:14 +00004439 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004440 return ResultTy;
4441 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004442
4443 // Comparison of member pointers.
4444 if (!isRelational &&
4445 lType->isMemberPointerType() && rType->isMemberPointerType()) {
4446 // C++ [expr.eq]p2:
4447 // In addition, pointers to members can be compared, or a pointer to
4448 // member and a null pointer constant. Pointer to member conversions
4449 // (4.11) and qualification conversions (4.4) are performed to bring
4450 // them to a common type. If one operand is a null pointer constant,
4451 // the common type is the type of the other operand. Otherwise, the
4452 // common type is a pointer to member type similar (4.4) to the type
4453 // of one of the operands, with a cv-qualification signature (4.4)
4454 // that is the union of the cv-qualification signatures of the operand
4455 // types.
4456 QualType T = FindCompositePointerType(lex, rex);
4457 if (T.isNull()) {
4458 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4459 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4460 return QualType();
4461 }
4462
4463 ImpCastExprToType(lex, T);
4464 ImpCastExprToType(rex, T);
4465 return ResultTy;
4466 }
4467
4468 // Comparison of nullptr_t with itself.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004469 if (lType->isNullPtrType() && rType->isNullPtrType())
4470 return ResultTy;
4471 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004472
Steve Naroff3454b6c2008-09-04 15:10:53 +00004473 // Handle block pointer types.
Mike Stumpe97a8542009-05-07 03:14:14 +00004474 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004475 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4476 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004477
Steve Naroff3454b6c2008-09-04 15:10:53 +00004478 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00004479 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004480 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004481 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00004482 }
4483 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004484 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004485 }
Steve Narofff85d66c2008-09-28 01:11:11 +00004486 // Allow block pointers to be compared with null pointer constants.
Mike Stumpe97a8542009-05-07 03:14:14 +00004487 if (!isRelational
4488 && ((lType->isBlockPointerType() && rType->isPointerType())
4489 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Narofff85d66c2008-09-28 01:11:11 +00004490 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004491 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004492 ->getPointeeType()->isVoidType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004493 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004494 ->getPointeeType()->isVoidType())))
4495 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4496 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00004497 }
4498 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004499 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00004500 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00004501
Steve Naroff329ec222009-07-10 23:34:53 +00004502 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00004503 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004504 const PointerType *LPT = lType->getAs<PointerType>();
4505 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump9afab102009-02-19 03:04:26 +00004506 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004507 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004508 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004509 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004510
Steve Naroff030fcda2008-11-17 19:49:16 +00004511 if (!LPtrToVoid && !RPtrToVoid &&
4512 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004513 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004514 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00004515 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00004516 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004517 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00004518 }
Steve Naroff329ec222009-07-10 23:34:53 +00004519 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004520 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff329ec222009-07-10 23:34:53 +00004521 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4522 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff936c4362008-06-03 14:04:54 +00004523 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004524 return ResultTy;
Steve Naroff936c4362008-06-03 14:04:54 +00004525 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00004526 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004527 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner124569f2009-08-23 00:03:44 +00004528 unsigned DiagID = 0;
4529 if (RHSIsNull) {
4530 if (isRelational)
4531 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4532 } else if (isRelational)
4533 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4534 else
4535 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
4536
4537 if (DiagID) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004538 Diag(Loc, DiagID)
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004539 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner8b88b142009-08-22 18:58:31 +00004540 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004541 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004542 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004543 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004544 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner124569f2009-08-23 00:03:44 +00004545 unsigned DiagID = 0;
4546 if (LHSIsNull) {
4547 if (isRelational)
4548 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4549 } else if (isRelational)
4550 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4551 else
4552 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Chris Lattner8b88b142009-08-22 18:58:31 +00004553
Chris Lattner124569f2009-08-23 00:03:44 +00004554 if (DiagID) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004555 Diag(Loc, DiagID)
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004556 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner8b88b142009-08-22 18:58:31 +00004557 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004558 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004559 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004560 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00004561 // Handle block pointers.
Mike Stumpea3d74e2009-05-07 18:43:07 +00004562 if (!isRelational && RHSIsNull
4563 && lType->isBlockPointerType() && rType->isIntegerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004564 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004565 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004566 }
Mike Stumpea3d74e2009-05-07 18:43:07 +00004567 if (!isRelational && LHSIsNull
4568 && lType->isIntegerType() && rType->isBlockPointerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004569 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004570 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004571 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00004572 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004573}
4574
Nate Begemanc5f0f652008-07-14 18:02:46 +00004575/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00004576/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004577/// like a scalar comparison, a vector comparison produces a vector of integer
4578/// types.
4579QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00004580 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004581 bool isRelational) {
4582 // Check to make sure we're operating on vectors of the same type and width,
4583 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004584 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004585 if (vType.isNull())
4586 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00004587
Nate Begemanc5f0f652008-07-14 18:02:46 +00004588 QualType lType = lex->getType();
4589 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004590
Nate Begemanc5f0f652008-07-14 18:02:46 +00004591 // For non-floating point types, check for self-comparisons of the form
4592 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4593 // often indicate logic errors in the program.
4594 if (!lType->isFloatingType()) {
4595 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4596 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4597 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00004598 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004599 }
Mike Stump9afab102009-02-19 03:04:26 +00004600
Nate Begemanc5f0f652008-07-14 18:02:46 +00004601 // Check for comparisons of floating point operands using != and ==.
4602 if (!isRelational && lType->isFloatingType()) {
4603 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004604 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004605 }
Mike Stump9afab102009-02-19 03:04:26 +00004606
Nate Begemanc5f0f652008-07-14 18:02:46 +00004607 // Return the type for the comparison, which is the same as vector type for
4608 // integer vectors, or an integer type of identical size and number of
4609 // elements for floating point vectors.
4610 if (lType->isIntegerType())
4611 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00004612
Nate Begemanc5f0f652008-07-14 18:02:46 +00004613 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00004614 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00004615 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00004616 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner10687e32009-03-31 07:46:52 +00004617 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begemand6d2f772009-01-18 03:20:47 +00004618 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4619
Mike Stump9afab102009-02-19 03:04:26 +00004620 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00004621 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00004622 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4623}
4624
Chris Lattner4b009652007-07-25 00:24:17 +00004625inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004626 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004627{
4628 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004629 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004630
Steve Naroff8f708362007-08-24 19:07:16 +00004631 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004632
Chris Lattner4b009652007-07-25 00:24:17 +00004633 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00004634 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004635 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004636}
4637
4638inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00004639 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00004640{
4641 UsualUnaryConversions(lex);
4642 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004643
Eli Friedmanbea3f842008-05-13 20:16:47 +00004644 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00004645 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004646 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004647}
4648
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004649/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4650/// is a read-only property; return true if so. A readonly property expression
4651/// depends on various declarations and thus must be treated specially.
4652///
Mike Stump9afab102009-02-19 03:04:26 +00004653static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004654{
4655 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4656 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4657 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4658 QualType BaseType = PropExpr->getBase()->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00004659 if (const ObjCObjectPointerType *OPT =
4660 BaseType->getAsObjCInterfacePointerType())
4661 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4662 if (S.isPropertyReadonly(PDecl, IFace))
4663 return true;
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004664 }
4665 }
4666 return false;
4667}
4668
Chris Lattner4c2642c2008-11-18 01:22:49 +00004669/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4670/// emit an error and return true. If so, return false.
4671static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004672 SourceLocation OrigLoc = Loc;
4673 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4674 &Loc);
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004675 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4676 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004677 if (IsLV == Expr::MLV_Valid)
4678 return false;
Mike Stump9afab102009-02-19 03:04:26 +00004679
Chris Lattner4c2642c2008-11-18 01:22:49 +00004680 unsigned Diag = 0;
4681 bool NeedType = false;
4682 switch (IsLV) { // C99 6.5.16p2
4683 default: assert(0 && "Unknown result from isModifiableLvalue!");
4684 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00004685 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004686 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4687 NeedType = true;
4688 break;
Mike Stump9afab102009-02-19 03:04:26 +00004689 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004690 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4691 NeedType = true;
4692 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00004693 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004694 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4695 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004696 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004697 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4698 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004699 case Expr::MLV_IncompleteType:
4700 case Expr::MLV_IncompleteVoidType:
Douglas Gregorc84d8932009-03-09 16:13:40 +00004701 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssona21e7872009-08-26 23:45:07 +00004702 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
4703 << E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00004704 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004705 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4706 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00004707 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004708 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4709 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00004710 case Expr::MLV_ReadonlyProperty:
4711 Diag = diag::error_readonly_property_assignment;
4712 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00004713 case Expr::MLV_NoSetterProperty:
4714 Diag = diag::error_nosetter_property_assignment;
4715 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004716 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00004717
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004718 SourceRange Assign;
4719 if (Loc != OrigLoc)
4720 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner4c2642c2008-11-18 01:22:49 +00004721 if (NeedType)
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004722 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004723 else
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004724 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004725 return true;
4726}
4727
4728
4729
4730// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00004731QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4732 SourceLocation Loc,
4733 QualType CompoundType) {
4734 // Verify that LHS is a modifiable lvalue, and emit error if not.
4735 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00004736 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00004737
4738 QualType LHSType = LHS->getType();
4739 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00004740
Chris Lattner005ed752008-01-04 18:04:52 +00004741 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004742 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00004743 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004744 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004745 // Special case of NSObject attributes on c-style pointer types.
4746 if (ConvTy == IncompatiblePointer &&
4747 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004748 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004749 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004750 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004751 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00004752
Chris Lattner34c85082008-08-21 18:04:13 +00004753 // If the RHS is a unary plus or minus, check to see if they = and + are
4754 // right next to each other. If so, the user may have typo'd "x =+ 4"
4755 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004756 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00004757 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4758 RHSCheck = ICE->getSubExpr();
4759 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4760 if ((UO->getOpcode() == UnaryOperator::Plus ||
4761 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00004762 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00004763 // Only if the two operators are exactly adjacent.
Chris Lattner55a17242009-03-08 06:51:10 +00004764 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4765 // And there is a space or other character before the subexpr of the
4766 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnerf1e5d4a2009-03-09 07:11:10 +00004767 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4768 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004769 Diag(Loc, diag::warn_not_compound_assign)
4770 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4771 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner55a17242009-03-08 06:51:10 +00004772 }
Chris Lattner34c85082008-08-21 18:04:13 +00004773 }
4774 } else {
4775 // Compound assignment "x += y"
Eli Friedmanb653af42009-05-16 05:56:02 +00004776 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00004777 }
Chris Lattner005ed752008-01-04 18:04:52 +00004778
Chris Lattner1eafdea2008-11-18 01:30:42 +00004779 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4780 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00004781 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004782
Chris Lattner4b009652007-07-25 00:24:17 +00004783 // C99 6.5.16p3: The type of an assignment expression is the type of the
4784 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00004785 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00004786 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4787 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004788 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004789 // operand.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004790 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00004791}
4792
Chris Lattner1eafdea2008-11-18 01:30:42 +00004793// C99 6.5.17
4794QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00004795 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004796 DefaultFunctionArrayConversion(RHS);
Eli Friedman2b128322009-03-23 00:24:07 +00004797
4798 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4799 // incomplete in C++).
4800
Chris Lattner1eafdea2008-11-18 01:30:42 +00004801 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00004802}
4803
4804/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4805/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004806QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4807 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004808 if (Op->isTypeDependent())
4809 return Context.DependentTy;
4810
Chris Lattnere65182c2008-11-21 07:05:48 +00004811 QualType ResType = Op->getType();
4812 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004813
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004814 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4815 // Decrement of bool is not allowed.
4816 if (!isInc) {
4817 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4818 return QualType();
4819 }
4820 // Increment of bool sets it to true, but is deprecated.
4821 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4822 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00004823 // OK!
Steve Naroff79ae19a2009-07-14 18:25:06 +00004824 } else if (ResType->isAnyPointerType()) {
4825 QualType PointeeTy = ResType->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00004826
Chris Lattnere65182c2008-11-21 07:05:48 +00004827 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff329ec222009-07-10 23:34:53 +00004828 if (PointeeTy->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004829 if (getLangOptions().CPlusPlus) {
4830 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4831 << Op->getSourceRange();
4832 return QualType();
4833 }
4834
4835 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00004836 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004837 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004838 if (getLangOptions().CPlusPlus) {
4839 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4840 << Op->getType() << Op->getSourceRange();
4841 return QualType();
4842 }
4843
4844 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004845 << ResType << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004846 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004847 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4848 << Op->getSourceRange()
4849 << ResType))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004850 return QualType();
Fariborz Jahanian4738ac52009-07-16 17:59:14 +00004851 // Diagnose bad cases where we step over interface counts.
4852 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4853 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
4854 << PointeeTy << Op->getSourceRange();
4855 return QualType();
4856 }
Chris Lattnere65182c2008-11-21 07:05:48 +00004857 } else if (ResType->isComplexType()) {
4858 // C99 does not support ++/-- on complex types, we allow as an extension.
4859 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004860 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004861 } else {
4862 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004863 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004864 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00004865 }
Mike Stump9afab102009-02-19 03:04:26 +00004866 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00004867 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00004868 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00004869 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00004870 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00004871}
4872
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004873/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00004874/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004875/// where the declaration is needed for type checking. We only need to
4876/// handle cases when the expression references a function designator
4877/// or is an lvalue. Here are some examples:
4878/// - &(x) => x
4879/// - &*****f => f for f a function designator.
4880/// - &s.xx => s
4881/// - &s.zz[1].yy -> s, if zz is an array
4882/// - *(x + 1) -> x, if x is an array
4883/// - &"123"[2] -> 0
4884/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00004885static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00004886 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00004887 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00004888 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004889 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00004890 case Stmt::MemberExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004891 // If this is an arrow operator, the address is an offset from
4892 // the base's value, so the object the base refers to is
4893 // irrelevant.
Chris Lattner48d7f382008-04-02 04:24:33 +00004894 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00004895 return 0;
Eli Friedman93ecce22009-04-20 08:23:18 +00004896 // Otherwise, the expression refers to a part of the base
Chris Lattner48d7f382008-04-02 04:24:33 +00004897 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004898 case Stmt::ArraySubscriptExprClass: {
Mike Stumpe127ae32009-05-16 07:39:55 +00004899 // FIXME: This code shouldn't be necessary! We should catch the implicit
4900 // promotion of register arrays earlier.
Eli Friedman93ecce22009-04-20 08:23:18 +00004901 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4902 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4903 if (ICE->getSubExpr()->getType()->isArrayType())
4904 return getPrimaryDecl(ICE->getSubExpr());
4905 }
4906 return 0;
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004907 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004908 case Stmt::UnaryOperatorClass: {
4909 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00004910
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004911 switch(UO->getOpcode()) {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004912 case UnaryOperator::Real:
4913 case UnaryOperator::Imag:
4914 case UnaryOperator::Extension:
4915 return getPrimaryDecl(UO->getSubExpr());
4916 default:
4917 return 0;
4918 }
4919 }
Chris Lattner4b009652007-07-25 00:24:17 +00004920 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004921 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00004922 case Stmt::ImplicitCastExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004923 // If the result of an implicit cast is an l-value, we care about
4924 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner48d7f382008-04-02 04:24:33 +00004925 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00004926 default:
4927 return 0;
4928 }
4929}
4930
4931/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00004932/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00004933/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00004934/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00004935/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00004936/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00004937/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00004938QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman93ecce22009-04-20 08:23:18 +00004939 // Make sure to ignore parentheses in subsequent checks
4940 op = op->IgnoreParens();
4941
Douglas Gregore6be68a2008-12-17 22:52:20 +00004942 if (op->isTypeDependent())
4943 return Context.DependentTy;
4944
Steve Naroff9c6c3592008-01-13 17:10:08 +00004945 if (getLangOptions().C99) {
4946 // Implement C99-only parts of addressof rules.
4947 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
4948 if (uOp->getOpcode() == UnaryOperator::Deref)
4949 // Per C99 6.5.3.2, the address of a deref always returns a valid result
4950 // (assuming the deref expression is valid).
4951 return uOp->getSubExpr()->getType();
4952 }
4953 // Technically, there should be a check for array subscript
4954 // expressions here, but the result of one is always an lvalue anyway.
4955 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00004956 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00004957 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00004958
Eli Friedman14ab4c42009-05-16 23:27:50 +00004959 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
4960 // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004961 // The operand must be either an l-value or a function designator
Eli Friedman14ab4c42009-05-16 23:27:50 +00004962 if (!op->getType()->isFunctionType()) {
Chris Lattnera3249072007-11-16 17:46:48 +00004963 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00004964 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
4965 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004966 return QualType();
4967 }
Douglas Gregor531434b2009-05-02 02:18:30 +00004968 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004969 // The operand cannot be a bit-field
4970 Diag(OpLoc, diag::err_typecheck_address_of)
4971 << "bit-field" << op->getSourceRange();
Douglas Gregor82d44772008-12-20 23:49:58 +00004972 return QualType();
Nate Begemana9187ab2009-02-15 22:45:20 +00004973 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
4974 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman93ecce22009-04-20 08:23:18 +00004975 // The operand cannot be an element of a vector
Chris Lattner77d52da2008-11-20 06:06:08 +00004976 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00004977 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004978 return QualType();
Fariborz Jahanianb35984a2009-07-07 18:50:52 +00004979 } else if (isa<ObjCPropertyRefExpr>(op)) {
4980 // cannot take address of a property expression.
4981 Diag(OpLoc, diag::err_typecheck_address_of)
4982 << "property expression" << op->getSourceRange();
4983 return QualType();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004984 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00004985 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00004986 // with the register storage-class specifier.
4987 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
4988 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004989 Diag(OpLoc, diag::err_typecheck_address_of)
4990 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004991 return QualType();
4992 }
Douglas Gregor62f78762009-07-08 20:55:45 +00004993 } else if (isa<OverloadedFunctionDecl>(dcl) ||
4994 isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00004995 return Context.OverloadTy;
Anders Carlsson64371472009-07-08 21:45:58 +00004996 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor5b82d612008-12-10 21:26:49 +00004997 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00004998 // Could be a pointer to member, though, if there is an explicit
4999 // scope qualifier for the class.
5000 if (isa<QualifiedDeclRefExpr>(op)) {
5001 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson64371472009-07-08 21:45:58 +00005002 if (Ctx && Ctx->isRecord()) {
5003 if (FD->getType()->isReferenceType()) {
5004 Diag(OpLoc,
5005 diag::err_cannot_form_pointer_to_member_of_reference_type)
5006 << FD->getDeclName() << FD->getType();
5007 return QualType();
5008 }
5009
Sebastian Redl0c9da212009-02-03 20:19:35 +00005010 return Context.getMemberPointerType(op->getType(),
5011 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson64371472009-07-08 21:45:58 +00005012 }
Sebastian Redl0c9da212009-02-03 20:19:35 +00005013 }
Anders Carlssone9cc4c42009-05-16 21:43:42 +00005014 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopesdf239522008-12-16 22:58:26 +00005015 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00005016 // As above.
Anders Carlssone9cc4c42009-05-16 21:43:42 +00005017 if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
5018 return Context.getMemberPointerType(op->getType(),
5019 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5020 } else if (!isa<FunctionDecl>(dcl))
Chris Lattner4b009652007-07-25 00:24:17 +00005021 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00005022 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00005023
Eli Friedman14ab4c42009-05-16 23:27:50 +00005024 if (lval == Expr::LV_IncompleteVoidType) {
5025 // Taking the address of a void variable is technically illegal, but we
5026 // allow it in cases which are otherwise valid.
5027 // Example: "extern void x; void* y = &x;".
5028 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5029 }
5030
Chris Lattner4b009652007-07-25 00:24:17 +00005031 // If the operand has type "type", the result has type "pointer to type".
5032 return Context.getPointerType(op->getType());
5033}
5034
Chris Lattnerda5c0872008-11-23 09:13:29 +00005035QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005036 if (Op->isTypeDependent())
5037 return Context.DependentTy;
5038
Chris Lattnerda5c0872008-11-23 09:13:29 +00005039 UsualUnaryConversions(Op);
5040 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00005041
Chris Lattnerda5c0872008-11-23 09:13:29 +00005042 // Note that per both C89 and C99, this is always legal, even if ptype is an
5043 // incomplete type or void. It would be possible to warn about dereferencing
5044 // a void pointer, but it's completely well-defined, and such a warning is
5045 // unlikely to catch any mistakes.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00005046 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff9c6c3592008-01-13 17:10:08 +00005047 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00005048
Fariborz Jahanian81699d92009-09-03 00:43:07 +00005049 if (const ObjCObjectPointerType *OPT = Ty->getAsObjCObjectPointerType())
5050 return OPT->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00005051
Chris Lattner77d52da2008-11-20 06:06:08 +00005052 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00005053 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00005054 return QualType();
5055}
5056
5057static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5058 tok::TokenKind Kind) {
5059 BinaryOperator::Opcode Opc;
5060 switch (Kind) {
5061 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00005062 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5063 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00005064 case tok::star: Opc = BinaryOperator::Mul; break;
5065 case tok::slash: Opc = BinaryOperator::Div; break;
5066 case tok::percent: Opc = BinaryOperator::Rem; break;
5067 case tok::plus: Opc = BinaryOperator::Add; break;
5068 case tok::minus: Opc = BinaryOperator::Sub; break;
5069 case tok::lessless: Opc = BinaryOperator::Shl; break;
5070 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5071 case tok::lessequal: Opc = BinaryOperator::LE; break;
5072 case tok::less: Opc = BinaryOperator::LT; break;
5073 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5074 case tok::greater: Opc = BinaryOperator::GT; break;
5075 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5076 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5077 case tok::amp: Opc = BinaryOperator::And; break;
5078 case tok::caret: Opc = BinaryOperator::Xor; break;
5079 case tok::pipe: Opc = BinaryOperator::Or; break;
5080 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5081 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5082 case tok::equal: Opc = BinaryOperator::Assign; break;
5083 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5084 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5085 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5086 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5087 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5088 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5089 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5090 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5091 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5092 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5093 case tok::comma: Opc = BinaryOperator::Comma; break;
5094 }
5095 return Opc;
5096}
5097
5098static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5099 tok::TokenKind Kind) {
5100 UnaryOperator::Opcode Opc;
5101 switch (Kind) {
5102 default: assert(0 && "Unknown unary op!");
5103 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5104 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5105 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5106 case tok::star: Opc = UnaryOperator::Deref; break;
5107 case tok::plus: Opc = UnaryOperator::Plus; break;
5108 case tok::minus: Opc = UnaryOperator::Minus; break;
5109 case tok::tilde: Opc = UnaryOperator::Not; break;
5110 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00005111 case tok::kw___real: Opc = UnaryOperator::Real; break;
5112 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5113 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5114 }
5115 return Opc;
5116}
5117
Douglas Gregord7f915e2008-11-06 23:29:22 +00005118/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5119/// operator @p Opc at location @c TokLoc. This routine only supports
5120/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005121Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5122 unsigned Op,
5123 Expr *lhs, Expr *rhs) {
Eli Friedman3cd92882009-03-28 01:22:36 +00005124 QualType ResultTy; // Result type of the binary operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00005125 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman3cd92882009-03-28 01:22:36 +00005126 // The following two variables are used for compound assignment operators
5127 QualType CompLHSTy; // Type of LHS after promotions for computation
5128 QualType CompResultTy; // Type of computation result
Douglas Gregord7f915e2008-11-06 23:29:22 +00005129
5130 switch (Opc) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00005131 case BinaryOperator::Assign:
5132 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5133 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005134 case BinaryOperator::PtrMemD:
5135 case BinaryOperator::PtrMemI:
5136 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5137 Opc == BinaryOperator::PtrMemI);
5138 break;
5139 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005140 case BinaryOperator::Div:
5141 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5142 break;
5143 case BinaryOperator::Rem:
5144 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5145 break;
5146 case BinaryOperator::Add:
5147 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5148 break;
5149 case BinaryOperator::Sub:
5150 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5151 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005152 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005153 case BinaryOperator::Shr:
5154 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5155 break;
5156 case BinaryOperator::LE:
5157 case BinaryOperator::LT:
5158 case BinaryOperator::GE:
5159 case BinaryOperator::GT:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005160 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005161 break;
5162 case BinaryOperator::EQ:
5163 case BinaryOperator::NE:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005164 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005165 break;
5166 case BinaryOperator::And:
5167 case BinaryOperator::Xor:
5168 case BinaryOperator::Or:
5169 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5170 break;
5171 case BinaryOperator::LAnd:
5172 case BinaryOperator::LOr:
5173 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5174 break;
5175 case BinaryOperator::MulAssign:
5176 case BinaryOperator::DivAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005177 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5178 CompLHSTy = CompResultTy;
5179 if (!CompResultTy.isNull())
5180 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005181 break;
5182 case BinaryOperator::RemAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005183 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5184 CompLHSTy = CompResultTy;
5185 if (!CompResultTy.isNull())
5186 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005187 break;
5188 case BinaryOperator::AddAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005189 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5190 if (!CompResultTy.isNull())
5191 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005192 break;
5193 case BinaryOperator::SubAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005194 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5195 if (!CompResultTy.isNull())
5196 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005197 break;
5198 case BinaryOperator::ShlAssign:
5199 case BinaryOperator::ShrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005200 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5201 CompLHSTy = CompResultTy;
5202 if (!CompResultTy.isNull())
5203 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005204 break;
5205 case BinaryOperator::AndAssign:
5206 case BinaryOperator::XorAssign:
5207 case BinaryOperator::OrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005208 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5209 CompLHSTy = CompResultTy;
5210 if (!CompResultTy.isNull())
5211 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005212 break;
5213 case BinaryOperator::Comma:
5214 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5215 break;
5216 }
5217 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005218 return ExprError();
Eli Friedman3cd92882009-03-28 01:22:36 +00005219 if (CompResultTy.isNull())
Steve Naroff774e4152009-01-21 00:14:39 +00005220 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5221 else
5222 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman3cd92882009-03-28 01:22:36 +00005223 CompLHSTy, CompResultTy,
5224 OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00005225}
5226
Chris Lattner4b009652007-07-25 00:24:17 +00005227// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005228Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5229 tok::TokenKind Kind,
5230 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00005231 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005232 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Chris Lattner4b009652007-07-25 00:24:17 +00005233
Steve Naroff87d58b42007-09-16 03:34:24 +00005234 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5235 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00005236
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005237 if (getLangOptions().CPlusPlus &&
5238 (lhs->getType()->isOverloadableType() ||
5239 rhs->getType()->isOverloadableType())) {
5240 // Find all of the overloaded operators visible from this
5241 // point. We perform both an operator-name lookup from the local
5242 // scope and an argument-dependent lookup based on the types of
5243 // the arguments.
Douglas Gregor3fc092f2009-03-13 00:33:25 +00005244 FunctionSet Functions;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005245 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5246 if (OverOp != OO_None) {
5247 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5248 Functions);
5249 Expr *Args[2] = { lhs, rhs };
5250 DeclarationName OpName
5251 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5252 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregor70d26122008-11-12 17:17:38 +00005253 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005254
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005255 // Build the (potentially-overloaded, potentially-dependent)
5256 // binary operation.
5257 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005258 }
5259
Douglas Gregord7f915e2008-11-06 23:29:22 +00005260 // Build a built-in binary operation.
5261 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00005262}
5263
Douglas Gregorc78182d2009-03-13 23:49:33 +00005264Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
5265 unsigned OpcIn,
5266 ExprArg InputArg) {
5267 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005268
Mike Stumpe127ae32009-05-16 07:39:55 +00005269 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorc78182d2009-03-13 23:49:33 +00005270 Expr *Input = (Expr *)InputArg.get();
Chris Lattner4b009652007-07-25 00:24:17 +00005271 QualType resultType;
5272 switch (Opc) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00005273 case UnaryOperator::OffsetOf:
5274 assert(false && "Invalid unary operator");
5275 break;
5276
Chris Lattner4b009652007-07-25 00:24:17 +00005277 case UnaryOperator::PreInc:
5278 case UnaryOperator::PreDec:
Eli Friedman79341142009-07-22 22:25:00 +00005279 case UnaryOperator::PostInc:
5280 case UnaryOperator::PostDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00005281 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman79341142009-07-22 22:25:00 +00005282 Opc == UnaryOperator::PreInc ||
5283 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00005284 break;
Mike Stump9afab102009-02-19 03:04:26 +00005285 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00005286 resultType = CheckAddressOfOperand(Input, OpLoc);
5287 break;
Mike Stump9afab102009-02-19 03:04:26 +00005288 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00005289 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00005290 resultType = CheckIndirectionOperand(Input, OpLoc);
5291 break;
5292 case UnaryOperator::Plus:
5293 case UnaryOperator::Minus:
5294 UsualUnaryConversions(Input);
5295 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005296 if (resultType->isDependentType())
5297 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005298 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5299 break;
5300 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5301 resultType->isEnumeralType())
5302 break;
5303 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5304 Opc == UnaryOperator::Plus &&
5305 resultType->isPointerType())
5306 break;
5307
Sebastian Redl8b769972009-01-19 00:08:26 +00005308 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5309 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005310 case UnaryOperator::Not: // bitwise complement
5311 UsualUnaryConversions(Input);
5312 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005313 if (resultType->isDependentType())
5314 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00005315 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5316 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5317 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00005318 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00005319 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00005320 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00005321 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5322 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005323 break;
5324 case UnaryOperator::LNot: // logical negation
5325 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
5326 DefaultFunctionArrayConversion(Input);
5327 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005328 if (resultType->isDependentType())
5329 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005330 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00005331 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5332 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005333 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00005334 // In C++, it's bool. C++ 5.3.1p8
5335 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00005336 break;
Chris Lattner03931a72007-08-24 21:16:53 +00005337 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00005338 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00005339 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00005340 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005341 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00005342 resultType = Input->getType();
5343 break;
5344 }
5345 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00005346 return ExprError();
Douglas Gregorc78182d2009-03-13 23:49:33 +00005347
5348 InputArg.release();
Steve Naroff774e4152009-01-21 00:14:39 +00005349 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005350}
5351
Douglas Gregorc78182d2009-03-13 23:49:33 +00005352// Unary Operators. 'Tok' is the token for the operator.
5353Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5354 tok::TokenKind Op, ExprArg input) {
5355 Expr *Input = (Expr*)input.get();
5356 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5357
5358 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5359 // Find all of the overloaded operators visible from this
5360 // point. We perform both an operator-name lookup from the local
5361 // scope and an argument-dependent lookup based on the types of
5362 // the arguments.
5363 FunctionSet Functions;
5364 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5365 if (OverOp != OO_None) {
5366 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5367 Functions);
5368 DeclarationName OpName
5369 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5370 ArgumentDependentLookup(OpName, &Input, 1, Functions);
5371 }
5372
5373 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5374 }
5375
5376 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5377}
5378
Steve Naroff5cbb02f2007-09-16 14:56:35 +00005379/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005380Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5381 SourceLocation LabLoc,
5382 IdentifierInfo *LabelII) {
Chris Lattner4b009652007-07-25 00:24:17 +00005383 // Look up the record for this label identifier.
Chris Lattner2616d8c2009-04-18 20:01:55 +00005384 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00005385
Daniel Dunbar879788d2008-08-04 16:51:22 +00005386 // If we haven't seen this label yet, create a forward reference. It
5387 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffb88d81c2009-03-13 15:38:40 +00005388 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00005389 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00005390
Chris Lattner4b009652007-07-25 00:24:17 +00005391 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005392 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5393 Context.getPointerType(Context.VoidTy)));
Chris Lattner4b009652007-07-25 00:24:17 +00005394}
5395
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005396Sema::OwningExprResult
5397Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5398 SourceLocation RPLoc) { // "({..})"
5399 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner4b009652007-07-25 00:24:17 +00005400 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5401 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5402
Eli Friedmanbc941e12009-01-24 23:09:00 +00005403 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattneraa257592009-04-25 19:11:05 +00005404 if (isFileScope)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005405 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmanbc941e12009-01-24 23:09:00 +00005406
Chris Lattner4b009652007-07-25 00:24:17 +00005407 // FIXME: there are a variety of strange constraints to enforce here, for
5408 // example, it is not possible to goto into a stmt expression apparently.
5409 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00005410
Chris Lattner4b009652007-07-25 00:24:17 +00005411 // If there are sub stmts in the compound stmt, take the type of the last one
5412 // as the type of the stmtexpr.
5413 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00005414
Chris Lattner200964f2008-07-26 19:51:01 +00005415 if (!Compound->body_empty()) {
5416 Stmt *LastStmt = Compound->body_back();
5417 // If LastStmt is a label, skip down through into the body.
5418 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5419 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00005420
Chris Lattner200964f2008-07-26 19:51:01 +00005421 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00005422 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00005423 }
Mike Stump9afab102009-02-19 03:04:26 +00005424
Eli Friedman2b128322009-03-23 00:24:07 +00005425 // FIXME: Check that expression type is complete/non-abstract; statement
5426 // expressions are not lvalues.
5427
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005428 substmt.release();
5429 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005430}
Steve Naroff63bad2d2007-08-01 22:05:33 +00005431
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005432Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5433 SourceLocation BuiltinLoc,
5434 SourceLocation TypeLoc,
5435 TypeTy *argty,
5436 OffsetOfComponent *CompPtr,
5437 unsigned NumComponents,
5438 SourceLocation RPLoc) {
5439 // FIXME: This function leaks all expressions in the offset components on
5440 // error.
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005441 // FIXME: Preserve type source info.
5442 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005443 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00005444
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005445 bool Dependent = ArgTy->isDependentType();
5446
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005447 // We must have at least one component that refers to the type, and the first
5448 // one is known to be a field designator. Verify that the ArgTy represents
5449 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005450 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005451 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump9afab102009-02-19 03:04:26 +00005452
Eli Friedman2b128322009-03-23 00:24:07 +00005453 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5454 // with an incomplete type would be illegal.
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00005455
Eli Friedman342d9432009-02-27 06:44:11 +00005456 // Otherwise, create a null pointer as the base, and iteratively process
5457 // the offsetof designators.
5458 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5459 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005460 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman342d9432009-02-27 06:44:11 +00005461 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00005462
Chris Lattnerb37522e2007-08-31 21:49:13 +00005463 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5464 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00005465 // FIXME: This diagnostic isn't actually visible because the location is in
5466 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00005467 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00005468 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5469 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00005470
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005471 if (!Dependent) {
Eli Friedmanc24ae002009-05-03 21:22:18 +00005472 bool DidWarnAboutNonPOD = false;
Anders Carlsson68c926c2009-05-02 18:36:10 +00005473
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005474 // FIXME: Dependent case loses a lot of information here. And probably
5475 // leaks like a sieve.
5476 for (unsigned i = 0; i != NumComponents; ++i) {
5477 const OffsetOfComponent &OC = CompPtr[i];
5478 if (OC.isBrackets) {
5479 // Offset of an array sub-field. TODO: Should we allow vector elements?
5480 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5481 if (!AT) {
5482 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005483 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5484 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005485 }
5486
5487 // FIXME: C++: Verify that operator[] isn't overloaded.
5488
Eli Friedman342d9432009-02-27 06:44:11 +00005489 // Promote the array so it looks more like a normal array subscript
5490 // expression.
5491 DefaultFunctionArrayConversion(Res);
5492
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005493 // C99 6.5.2.1p1
5494 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005495 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005496 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005497 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner7264d212009-04-25 22:50:55 +00005498 diag::err_typecheck_subscript_not_integer)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005499 << Idx->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005500
5501 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5502 OC.LocEnd);
5503 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005504 }
Mike Stump9afab102009-02-19 03:04:26 +00005505
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00005506 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005507 if (!RC) {
5508 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005509 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5510 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005511 }
Chris Lattner2af6a802007-08-30 17:59:59 +00005512
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005513 // Get the decl corresponding to this.
5514 RecordDecl *RD = RC->getDecl();
Anders Carlsson356946e2009-05-01 23:20:30 +00005515 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson68c926c2009-05-02 18:36:10 +00005516 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonbbceaea2009-05-02 17:45:47 +00005517 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5518 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5519 << Res->getType());
Anders Carlsson68c926c2009-05-02 18:36:10 +00005520 DidWarnAboutNonPOD = true;
5521 }
Anders Carlsson356946e2009-05-01 23:20:30 +00005522 }
5523
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005524 FieldDecl *MemberDecl
5525 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
5526 LookupMemberName)
5527 .getAsDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005528 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005529 if (!MemberDecl)
Anders Carlsson4355a392009-08-30 00:54:35 +00005530 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member_deprecated)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005531 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump9afab102009-02-19 03:04:26 +00005532
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005533 // FIXME: C++: Verify that MemberDecl isn't a static field.
5534 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman35719da2009-04-26 20:50:44 +00005535 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonc154a722009-05-01 19:30:39 +00005536 Res = BuildAnonymousStructUnionMemberReference(
5537 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedman35719da2009-04-26 20:50:44 +00005538 } else {
5539 // MemberDecl->getType() doesn't get the right qualifiers, but it
5540 // doesn't matter here.
5541 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5542 MemberDecl->getType().getNonReferenceType());
5543 }
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005544 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005545 }
Mike Stump9afab102009-02-19 03:04:26 +00005546
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005547 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5548 Context.getSizeType(), BuiltinLoc));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005549}
5550
5551
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005552Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5553 TypeTy *arg1,TypeTy *arg2,
5554 SourceLocation RPLoc) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005555 // FIXME: Preserve type source info.
5556 QualType argT1 = GetTypeFromParser(arg1);
5557 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00005558
Steve Naroff63bad2d2007-08-01 22:05:33 +00005559 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00005560
Douglas Gregore6211502009-05-19 22:28:02 +00005561 if (getLangOptions().CPlusPlus) {
5562 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5563 << SourceRange(BuiltinLoc, RPLoc);
5564 return ExprError();
5565 }
5566
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005567 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5568 argT1, argT2, RPLoc));
Steve Naroff63bad2d2007-08-01 22:05:33 +00005569}
5570
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005571Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5572 ExprArg cond,
5573 ExprArg expr1, ExprArg expr2,
5574 SourceLocation RPLoc) {
5575 Expr *CondExpr = static_cast<Expr*>(cond.get());
5576 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5577 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump9afab102009-02-19 03:04:26 +00005578
Steve Naroff93c53012007-08-03 21:21:27 +00005579 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5580
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005581 QualType resType;
Douglas Gregordd4ae3f2009-05-19 22:43:30 +00005582 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005583 resType = Context.DependentTy;
5584 } else {
5585 // The conditional expression is required to be a constant expression.
5586 llvm::APSInt condEval(32);
5587 SourceLocation ExpLoc;
5588 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005589 return ExprError(Diag(ExpLoc,
5590 diag::err_typecheck_choose_expr_requires_constant)
5591 << CondExpr->getSourceRange());
Steve Naroff93c53012007-08-03 21:21:27 +00005592
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005593 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5594 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5595 }
5596
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005597 cond.release(); expr1.release(); expr2.release();
5598 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5599 resType, RPLoc));
Steve Naroff93c53012007-08-03 21:21:27 +00005600}
5601
Steve Naroff52a81c02008-09-03 18:15:37 +00005602//===----------------------------------------------------------------------===//
5603// Clang Extensions.
5604//===----------------------------------------------------------------------===//
5605
5606/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00005607void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005608 // Analyze block parameters.
5609 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00005610
Steve Naroff52a81c02008-09-03 18:15:37 +00005611 // Add BSI to CurBlock.
5612 BSI->PrevBlockInfo = CurBlock;
5613 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00005614
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005615 BSI->ReturnType = QualType();
Steve Naroff52a81c02008-09-03 18:15:37 +00005616 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00005617 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarc7ef2b92009-07-29 01:59:17 +00005618 BSI->hasPrototype = false;
Chris Lattnere7765e12009-04-19 05:28:12 +00005619 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5620 CurFunctionNeedsScopeChecking = false;
Mike Stump9afab102009-02-19 03:04:26 +00005621
Steve Naroff52059382008-10-10 01:28:17 +00005622 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00005623 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00005624}
5625
Mike Stumpc1fddff2009-02-04 22:31:32 +00005626void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpea3d74e2009-05-07 18:43:07 +00005627 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stumpc1fddff2009-02-04 22:31:32 +00005628
5629 if (ParamInfo.getNumTypeObjects() == 0
5630 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005631 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stumpc1fddff2009-02-04 22:31:32 +00005632 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5633
Mike Stump458287d2009-04-28 01:10:27 +00005634 if (T->isArrayType()) {
5635 Diag(ParamInfo.getSourceRange().getBegin(),
5636 diag::err_block_returns_array);
5637 return;
5638 }
5639
Mike Stumpc1fddff2009-02-04 22:31:32 +00005640 // The parameter list is optional, if there was none, assume ().
5641 if (!T->isFunctionType())
5642 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5643
5644 CurBlock->hasPrototype = true;
5645 CurBlock->isVariadic = false;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005646 // Check for a valid sentinel attribute on this block.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005647 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005648 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005649 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005650 // FIXME: remove the attribute.
5651 }
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005652 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
5653
5654 // Do not allow returning a objc interface by-value.
5655 if (RetTy->isObjCInterfaceType()) {
5656 Diag(ParamInfo.getSourceRange().getBegin(),
5657 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5658 return;
5659 }
Mike Stumpc1fddff2009-02-04 22:31:32 +00005660 return;
5661 }
5662
Steve Naroff52a81c02008-09-03 18:15:37 +00005663 // Analyze arguments to block.
5664 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5665 "Not a function declarator!");
5666 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00005667
Steve Naroff52059382008-10-10 01:28:17 +00005668 CurBlock->hasPrototype = FTI.hasPrototype;
5669 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00005670
Steve Naroff52a81c02008-09-03 18:15:37 +00005671 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5672 // no arguments, not a function that takes a single void argument.
5673 if (FTI.hasPrototype &&
5674 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner5261d0c2009-03-28 19:18:32 +00005675 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5676 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005677 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00005678 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00005679 } else if (FTI.hasPrototype) {
5680 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner5261d0c2009-03-28 19:18:32 +00005681 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff52059382008-10-10 01:28:17 +00005682 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00005683 }
Jay Foad9e6bef42009-05-21 09:52:38 +00005684 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005685 CurBlock->Params.size());
Fariborz Jahanian536f73d2009-05-19 17:08:59 +00005686 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005687 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff52059382008-10-10 01:28:17 +00005688 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5689 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5690 // If this has an identifier, add it to the scope stack.
5691 if ((*AI)->getIdentifier())
5692 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005693
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005694 // Check for a valid sentinel attribute on this block.
Douglas Gregor98da6ae2009-06-18 16:11:24 +00005695 if (!CurBlock->isVariadic &&
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005696 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005697 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005698 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005699 // FIXME: remove the attribute.
5700 }
5701
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005702 // Analyze the return type.
5703 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5704 QualType RetTy = T->getAsFunctionType()->getResultType();
5705
5706 // Do not allow returning a objc interface by-value.
5707 if (RetTy->isObjCInterfaceType()) {
5708 Diag(ParamInfo.getSourceRange().getBegin(),
5709 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5710 } else if (!RetTy->isDependentType())
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005711 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00005712}
5713
5714/// ActOnBlockError - If there is an error parsing a block, this callback
5715/// is invoked to pop the information about the block from the action impl.
5716void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5717 // Ensure that CurBlock is deleted.
5718 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00005719
Chris Lattnere7765e12009-04-19 05:28:12 +00005720 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5721
Steve Naroff52a81c02008-09-03 18:15:37 +00005722 // Pop off CurBlock, handle nested blocks.
Chris Lattnereb4d4a52009-04-21 22:38:46 +00005723 PopDeclContext();
Steve Naroff52a81c02008-09-03 18:15:37 +00005724 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff52a81c02008-09-03 18:15:37 +00005725 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff52a81c02008-09-03 18:15:37 +00005726}
5727
5728/// ActOnBlockStmtExpr - This is called when the body of a block statement
5729/// literal was successfully completed. ^(int x){...}
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005730Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5731 StmtArg body, Scope *CurScope) {
Chris Lattnerc14c7f02009-03-27 04:18:06 +00005732 // If blocks are disabled, emit an error.
5733 if (!LangOpts.Blocks)
5734 Diag(CaretLoc, diag::err_blocks_disable);
5735
Steve Naroff52a81c02008-09-03 18:15:37 +00005736 // Ensure that CurBlock is deleted.
5737 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff52a81c02008-09-03 18:15:37 +00005738
Steve Naroff52059382008-10-10 01:28:17 +00005739 PopDeclContext();
5740
Steve Naroff52a81c02008-09-03 18:15:37 +00005741 // Pop off CurBlock, handle nested blocks.
5742 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00005743
Steve Naroff52a81c02008-09-03 18:15:37 +00005744 QualType RetTy = Context.VoidTy;
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005745 if (!BSI->ReturnType.isNull())
5746 RetTy = BSI->ReturnType;
Mike Stump9afab102009-02-19 03:04:26 +00005747
Steve Naroff52a81c02008-09-03 18:15:37 +00005748 llvm::SmallVector<QualType, 8> ArgTypes;
5749 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5750 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00005751
Mike Stump8e288f42009-07-28 22:04:01 +00005752 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff52a81c02008-09-03 18:15:37 +00005753 QualType BlockTy;
5754 if (!BSI->hasPrototype)
Mike Stump8e288f42009-07-28 22:04:01 +00005755 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5756 NoReturn);
Steve Naroff52a81c02008-09-03 18:15:37 +00005757 else
Jay Foad9e6bef42009-05-21 09:52:38 +00005758 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump8e288f42009-07-28 22:04:01 +00005759 BSI->isVariadic, 0, false, false, 0, 0,
5760 NoReturn);
Mike Stump9afab102009-02-19 03:04:26 +00005761
Eli Friedman2b128322009-03-23 00:24:07 +00005762 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregor98189262009-06-19 23:52:42 +00005763 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff52a81c02008-09-03 18:15:37 +00005764 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00005765
Chris Lattnere7765e12009-04-19 05:28:12 +00005766 // If needed, diagnose invalid gotos and switches in the block.
5767 if (CurFunctionNeedsScopeChecking)
5768 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5769 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5770
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005771 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump8e288f42009-07-28 22:04:01 +00005772 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005773 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5774 BSI->hasBlockDeclRefExprs));
Steve Naroff52a81c02008-09-03 18:15:37 +00005775}
5776
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005777Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5778 ExprArg expr, TypeTy *type,
5779 SourceLocation RPLoc) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005780 QualType T = GetTypeFromParser(type);
Chris Lattnerda139482009-04-05 15:49:53 +00005781 Expr *E = static_cast<Expr*>(expr.get());
5782 Expr *OrigExpr = E;
5783
Anders Carlsson36760332007-10-15 20:28:48 +00005784 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005785
5786 // Get the va_list type
5787 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman6f6e8922009-05-16 12:46:54 +00005788 if (VaListType->isArrayType()) {
5789 // Deal with implicit array decay; for example, on x86-64,
5790 // va_list is an array, but it's supposed to decay to
5791 // a pointer for va_arg.
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005792 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman6f6e8922009-05-16 12:46:54 +00005793 // Make sure the input expression also decays appropriately.
5794 UsualUnaryConversions(E);
5795 } else {
5796 // Otherwise, the va_list argument must be an l-value because
5797 // it is modified by va_arg.
Douglas Gregor25990972009-05-19 23:10:31 +00005798 if (!E->isTypeDependent() &&
5799 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman6f6e8922009-05-16 12:46:54 +00005800 return ExprError();
5801 }
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005802
Douglas Gregor25990972009-05-19 23:10:31 +00005803 if (!E->isTypeDependent() &&
5804 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005805 return ExprError(Diag(E->getLocStart(),
5806 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerda139482009-04-05 15:49:53 +00005807 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner89a72c52009-04-05 00:59:53 +00005808 }
Mike Stump9afab102009-02-19 03:04:26 +00005809
Eli Friedman2b128322009-03-23 00:24:07 +00005810 // FIXME: Check that type is complete/non-abstract
Anders Carlsson36760332007-10-15 20:28:48 +00005811 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00005812
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005813 expr.release();
5814 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5815 RPLoc));
Anders Carlsson36760332007-10-15 20:28:48 +00005816}
5817
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005818Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregorad4b3792008-11-29 04:51:27 +00005819 // The type of __null will be int or long, depending on the size of
5820 // pointers on the target.
5821 QualType Ty;
5822 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5823 Ty = Context.IntTy;
5824 else
5825 Ty = Context.LongTy;
5826
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005827 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregorad4b3792008-11-29 04:51:27 +00005828}
5829
Chris Lattner005ed752008-01-04 18:04:52 +00005830bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5831 SourceLocation Loc,
5832 QualType DstType, QualType SrcType,
5833 Expr *SrcExpr, const char *Flavor) {
5834 // Decode the result (notice that AST's are still created for extensions).
5835 bool isInvalid = false;
5836 unsigned DiagKind;
5837 switch (ConvTy) {
5838 default: assert(0 && "Unknown conversion type");
5839 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005840 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00005841 DiagKind = diag::ext_typecheck_convert_pointer_int;
5842 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005843 case IntToPointer:
5844 DiagKind = diag::ext_typecheck_convert_int_pointer;
5845 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005846 case IncompatiblePointer:
5847 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5848 break;
Eli Friedman6ca28cb2009-03-22 23:59:44 +00005849 case IncompatiblePointerSign:
5850 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5851 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005852 case FunctionVoidPointer:
5853 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5854 break;
5855 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00005856 // If the qualifiers lost were because we were applying the
5857 // (deprecated) C++ conversion from a string literal to a char*
5858 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
5859 // Ideally, this check would be performed in
5860 // CheckPointerTypesForAssignment. However, that would require a
5861 // bit of refactoring (so that the second argument is an
5862 // expression, rather than a type), which should be done as part
5863 // of a larger effort to fix CheckPointerTypesForAssignment for
5864 // C++ semantics.
5865 if (getLangOptions().CPlusPlus &&
5866 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5867 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00005868 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5869 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005870 case IntToBlockPointer:
5871 DiagKind = diag::err_int_to_block_pointer;
5872 break;
5873 case IncompatibleBlockPointer:
Mike Stumpd331e752009-04-21 22:51:42 +00005874 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005875 break;
Steve Naroff19608432008-10-14 22:18:38 +00005876 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00005877 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00005878 // it can give a more specific diagnostic.
5879 DiagKind = diag::warn_incompatible_qualified_id;
5880 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00005881 case IncompatibleVectors:
5882 DiagKind = diag::warn_incompatible_vectors;
5883 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005884 case Incompatible:
5885 DiagKind = diag::err_typecheck_convert_incompatible;
5886 isInvalid = true;
5887 break;
5888 }
Mike Stump9afab102009-02-19 03:04:26 +00005889
Chris Lattner271d4c22008-11-24 05:29:24 +00005890 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5891 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00005892 return isInvalid;
5893}
Anders Carlssond5201b92008-11-30 19:50:32 +00005894
Chris Lattnereec8ae22009-04-25 21:59:05 +00005895bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmance329412009-04-25 22:26:58 +00005896 llvm::APSInt ICEResult;
5897 if (E->isIntegerConstantExpr(ICEResult, Context)) {
5898 if (Result)
5899 *Result = ICEResult;
5900 return false;
5901 }
5902
Anders Carlssond5201b92008-11-30 19:50:32 +00005903 Expr::EvalResult EvalResult;
5904
Mike Stump9afab102009-02-19 03:04:26 +00005905 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00005906 EvalResult.HasSideEffects) {
5907 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5908
5909 if (EvalResult.Diag) {
5910 // We only show the note if it's not the usual "invalid subexpression"
5911 // or if it's actually in a subexpression.
5912 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5913 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5914 Diag(EvalResult.DiagLoc, EvalResult.Diag);
5915 }
Mike Stump9afab102009-02-19 03:04:26 +00005916
Anders Carlssond5201b92008-11-30 19:50:32 +00005917 return true;
5918 }
5919
Eli Friedmance329412009-04-25 22:26:58 +00005920 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5921 E->getSourceRange();
Anders Carlssond5201b92008-11-30 19:50:32 +00005922
Eli Friedmance329412009-04-25 22:26:58 +00005923 if (EvalResult.Diag &&
5924 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5925 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump9afab102009-02-19 03:04:26 +00005926
Anders Carlssond5201b92008-11-30 19:50:32 +00005927 if (Result)
5928 *Result = EvalResult.Val.getInt();
5929 return false;
5930}
Douglas Gregor98189262009-06-19 23:52:42 +00005931
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005932Sema::ExpressionEvaluationContext
5933Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
5934 // Introduce a new set of potentially referenced declarations to the stack.
5935 if (NewContext == PotentiallyPotentiallyEvaluated)
5936 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
5937
5938 std::swap(ExprEvalContext, NewContext);
5939 return NewContext;
5940}
5941
5942void
5943Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
5944 ExpressionEvaluationContext NewContext) {
5945 ExprEvalContext = NewContext;
5946
5947 if (OldContext == PotentiallyPotentiallyEvaluated) {
5948 // Mark any remaining declarations in the current position of the stack
5949 // as "referenced". If they were not meant to be referenced, semantic
5950 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
5951 PotentiallyReferencedDecls RemainingDecls;
5952 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
5953 PotentiallyReferencedDeclStack.pop_back();
5954
5955 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
5956 IEnd = RemainingDecls.end();
5957 I != IEnd; ++I)
5958 MarkDeclarationReferenced(I->first, I->second);
5959 }
5960}
Douglas Gregor98189262009-06-19 23:52:42 +00005961
5962/// \brief Note that the given declaration was referenced in the source code.
5963///
5964/// This routine should be invoke whenever a given declaration is referenced
5965/// in the source code, and where that reference occurred. If this declaration
5966/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
5967/// C99 6.9p3), then the declaration will be marked as used.
5968///
5969/// \param Loc the location where the declaration was referenced.
5970///
5971/// \param D the declaration that has been referenced by the source code.
5972void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
5973 assert(D && "No declaration?");
5974
Douglas Gregorcad27f62009-06-22 23:06:13 +00005975 if (D->isUsed())
5976 return;
5977
Douglas Gregor98189262009-06-19 23:52:42 +00005978 // Mark a parameter declaration "used", regardless of whether we're in a
5979 // template or not.
5980 if (isa<ParmVarDecl>(D))
5981 D->setUsed(true);
5982
5983 // Do not mark anything as "used" within a dependent context; wait for
5984 // an instantiation.
5985 if (CurContext->isDependentContext())
5986 return;
5987
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005988 switch (ExprEvalContext) {
5989 case Unevaluated:
5990 // We are in an expression that is not potentially evaluated; do nothing.
5991 return;
5992
5993 case PotentiallyEvaluated:
5994 // We are in a potentially-evaluated expression, so this declaration is
5995 // "used"; handle this below.
5996 break;
5997
5998 case PotentiallyPotentiallyEvaluated:
5999 // We are in an expression that may be potentially evaluated; queue this
6000 // declaration reference until we know whether the expression is
6001 // potentially evaluated.
6002 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
6003 return;
6004 }
6005
Douglas Gregor98189262009-06-19 23:52:42 +00006006 // Note that this declaration has been used.
Fariborz Jahanian8915a3d2009-06-22 17:30:33 +00006007 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00006008 unsigned TypeQuals;
Fariborz Jahanian2f5a0a32009-06-22 20:37:23 +00006009 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
6010 if (!Constructor->isUsed())
6011 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump90fc78e2009-08-04 21:02:39 +00006012 } else if (Constructor->isImplicit() &&
6013 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00006014 if (!Constructor->isUsed())
6015 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
6016 }
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00006017 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
6018 if (Destructor->isImplicit() && !Destructor->isUsed())
6019 DefineImplicitDestructor(Loc, Destructor);
6020
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00006021 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
6022 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
6023 MethodDecl->getOverloadedOperator() == OO_Equal) {
6024 if (!MethodDecl->isUsed())
6025 DefineImplicitOverloadedAssign(Loc, MethodDecl);
6026 }
6027 }
Fariborz Jahanianb12bd432009-06-24 22:09:44 +00006028 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00006029 // Implicit instantiation of function templates and member functions of
6030 // class templates.
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00006031 if (!Function->getBody()) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00006032 // FIXME: distinguish between implicit instantiations of function
6033 // templates and explicit specializations (the latter don't get
6034 // instantiated, naturally).
6035 if (Function->getInstantiatedFromMemberFunction() ||
6036 Function->getPrimaryTemplate())
Douglas Gregordcdb3842009-06-30 17:20:14 +00006037 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregorcad27f62009-06-22 23:06:13 +00006038 }
6039
6040
Douglas Gregor98189262009-06-19 23:52:42 +00006041 // FIXME: keep track of references to static functions
Douglas Gregor98189262009-06-19 23:52:42 +00006042 Function->setUsed(true);
6043 return;
Douglas Gregorcad27f62009-06-22 23:06:13 +00006044 }
Douglas Gregor98189262009-06-19 23:52:42 +00006045
6046 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor181fe792009-07-24 20:34:43 +00006047 // Implicit instantiation of static data members of class templates.
6048 // FIXME: distinguish between implicit instantiations (which we need to
6049 // actually instantiate) and explicit specializations.
6050 if (Var->isStaticDataMember() &&
6051 Var->getInstantiatedFromStaticDataMember())
6052 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6053
Douglas Gregor98189262009-06-19 23:52:42 +00006054 // FIXME: keep track of references to static data?
Douglas Gregor181fe792009-07-24 20:34:43 +00006055
Douglas Gregor98189262009-06-19 23:52:42 +00006056 D->setUsed(true);
Douglas Gregor181fe792009-07-24 20:34:43 +00006057 return;
6058}
Douglas Gregor98189262009-06-19 23:52:42 +00006059}
6060