blob: d272be97654a9195313a73c919993875f1881d38 [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())
199 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +0000200 else if (Ty->isArrayType()) {
201 // In C90 mode, arrays only promote to pointers if the array expression is
202 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
203 // type 'array of type' is converted to an expression that has type 'pointer
204 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
205 // that has type 'array of type' ...". The relevant change is "an lvalue"
206 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +0000207 //
208 // C++ 4.2p1:
209 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
210 // T" can be converted to an rvalue of type "pointer to T".
211 //
212 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
213 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson5c09af02009-08-07 23:48:20 +0000214 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
215 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner2aa68822008-07-25 21:33:13 +0000216 }
Chris Lattner299b8842008-07-25 21:10:04 +0000217}
218
219/// UsualUnaryConversions - Performs various conversions that are common to most
220/// operators (C99 6.3). The conversions of array and function types are
221/// sometimes surpressed. For example, the array->pointer conversion doesn't
222/// apply if the array is an argument to the sizeof or address (&) operators.
223/// In these instances, this routine should *not* be called.
224Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
225 QualType Ty = Expr->getType();
226 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
227
Douglas Gregor70b307e2009-05-01 20:41:21 +0000228 // C99 6.3.1.1p2:
229 //
230 // The following may be used in an expression wherever an int or
231 // unsigned int may be used:
232 // - an object or expression with an integer type whose integer
233 // conversion rank is less than or equal to the rank of int
234 // and unsigned int.
235 // - A bit-field of type _Bool, int, signed int, or unsigned int.
236 //
237 // If an int can represent all values of the original type, the
238 // value is converted to an int; otherwise, it is converted to an
239 // unsigned int. These are called the integer promotions. All
240 // other types are unchanged by the integer promotions.
Eli Friedman1931cc82009-08-20 04:21:42 +0000241 QualType PTy = Context.isPromotableBitField(Expr);
242 if (!PTy.isNull()) {
243 ImpCastExprToType(Expr, PTy);
244 return Expr;
245 }
Douglas Gregor70b307e2009-05-01 20:41:21 +0000246 if (Ty->isPromotableIntegerType()) {
Eli Friedman6ae7d112009-08-19 07:44:53 +0000247 QualType PT = Context.getPromotedIntegerType(Ty);
248 ImpCastExprToType(Expr, PT);
Douglas Gregor70b307e2009-05-01 20:41:21 +0000249 return Expr;
Eli Friedman1931cc82009-08-20 04:21:42 +0000250 }
251
Douglas Gregor70b307e2009-05-01 20:41:21 +0000252 DefaultFunctionArrayConversion(Expr);
Chris Lattner299b8842008-07-25 21:10:04 +0000253 return Expr;
254}
255
Chris Lattner9305c3d2008-07-25 22:25:12 +0000256/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
257/// do not have a prototype. Arguments that have type float are promoted to
258/// double. All other argument types are converted by UsualUnaryConversions().
259void Sema::DefaultArgumentPromotion(Expr *&Expr) {
260 QualType Ty = Expr->getType();
261 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
262
263 // If this is a 'float' (CVR qualified or typedef) promote to double.
264 if (const BuiltinType *BT = Ty->getAsBuiltinType())
265 if (BT->getKind() == BuiltinType::Float)
266 return ImpCastExprToType(Expr, Context.DoubleTy);
267
268 UsualUnaryConversions(Expr);
269}
270
Chris Lattner81f00ed2009-04-12 08:11:20 +0000271/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
272/// will warn if the resulting type is not a POD type, and rejects ObjC
273/// interfaces passed by value. This returns true if the argument type is
274/// completely illegal.
275bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000276 DefaultArgumentPromotion(Expr);
277
Chris Lattner81f00ed2009-04-12 08:11:20 +0000278 if (Expr->getType()->isObjCInterfaceType()) {
279 Diag(Expr->getLocStart(),
280 diag::err_cannot_pass_objc_interface_to_vararg)
281 << Expr->getType() << CT;
282 return true;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000283 }
Chris Lattner81f00ed2009-04-12 08:11:20 +0000284
285 if (!Expr->getType()->isPODType())
286 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
287 << Expr->getType() << CT;
288
289 return false;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000290}
291
292
Chris Lattner299b8842008-07-25 21:10:04 +0000293/// UsualArithmeticConversions - Performs various conversions that are common to
294/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
295/// routine returns the first non-arithmetic type found. The client is
296/// responsible for emitting appropriate error diagnostics.
297/// FIXME: verify the conversion rules for "complex int" are consistent with
298/// GCC.
299QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
300 bool isCompAssign) {
Eli Friedman3cd92882009-03-28 01:22:36 +0000301 if (!isCompAssign)
Chris Lattner299b8842008-07-25 21:10:04 +0000302 UsualUnaryConversions(lhsExpr);
Eli Friedman3cd92882009-03-28 01:22:36 +0000303
304 UsualUnaryConversions(rhsExpr);
Douglas Gregor70d26122008-11-12 17:17:38 +0000305
Chris Lattner299b8842008-07-25 21:10:04 +0000306 // For conversion purposes, we ignore any qualifiers.
307 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000308 QualType lhs =
309 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
310 QualType rhs =
311 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000312
313 // If both types are identical, no conversion is needed.
314 if (lhs == rhs)
315 return lhs;
316
317 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
318 // The caller can deal with this (e.g. pointer + int).
319 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
320 return lhs;
321
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000322 // Perform bitfield promotions.
Eli Friedman1931cc82009-08-20 04:21:42 +0000323 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000324 if (!LHSBitfieldPromoteTy.isNull())
325 lhs = LHSBitfieldPromoteTy;
Eli Friedman1931cc82009-08-20 04:21:42 +0000326 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000327 if (!RHSBitfieldPromoteTy.isNull())
328 rhs = RHSBitfieldPromoteTy;
329
Eli Friedman6ae7d112009-08-19 07:44:53 +0000330 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman3cd92882009-03-28 01:22:36 +0000331 if (!isCompAssign)
Douglas Gregor70d26122008-11-12 17:17:38 +0000332 ImpCastExprToType(lhsExpr, destType);
Eli Friedman3cd92882009-03-28 01:22:36 +0000333 ImpCastExprToType(rhsExpr, destType);
Douglas Gregor70d26122008-11-12 17:17:38 +0000334 return destType;
335}
336
Chris Lattner299b8842008-07-25 21:10:04 +0000337//===----------------------------------------------------------------------===//
338// Semantic Analysis for various Expression Types
339//===----------------------------------------------------------------------===//
340
341
Steve Naroff87d58b42007-09-16 03:34:24 +0000342/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000343/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
344/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
345/// multiple tokens. However, the common case is that StringToks points to one
346/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000347///
348Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000349Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000350 assert(NumStringToks && "Must have at least one string!");
351
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000352 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000353 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000354 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000355
356 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
357 for (unsigned i = 0; i != NumStringToks; ++i)
358 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000359
Chris Lattnera6dcce32008-02-11 00:02:17 +0000360 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000361 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000362 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000363
364 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
365 if (getLangOptions().CPlusPlus)
366 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000367
Chris Lattnera6dcce32008-02-11 00:02:17 +0000368 // Get an array type for the string, according to C99 6.4.5. This includes
369 // the nul terminator character as well as the string length for pascal
370 // strings.
371 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattner14032222009-02-26 23:01:51 +0000372 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000373 ArrayType::Normal, 0);
Chris Lattnerc3144742009-02-18 05:49:11 +0000374
Chris Lattner4b009652007-07-25 00:24:17 +0000375 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattneraa491192009-02-18 06:40:38 +0000376 return Owned(StringLiteral::Create(Context, Literal.GetString(),
377 Literal.GetStringLength(),
378 Literal.AnyWide, StrTy,
379 &StringTokLocs[0],
380 StringTokLocs.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000381}
382
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000383/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
384/// CurBlock to VD should cause it to be snapshotted (as we do for auto
385/// variables defined outside the block) or false if this is not needed (e.g.
386/// for values inside the block or for globals).
387///
Chris Lattner0b464252009-04-21 22:26:47 +0000388/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
389/// up-to-date.
390///
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000391static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
392 ValueDecl *VD) {
393 // If the value is defined inside the block, we couldn't snapshot it even if
394 // we wanted to.
395 if (CurBlock->TheDecl == VD->getDeclContext())
396 return false;
397
398 // If this is an enum constant or function, it is constant, don't snapshot.
399 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
400 return false;
401
402 // If this is a reference to an extern, static, or global variable, no need to
403 // snapshot it.
404 // FIXME: What about 'const' variables in C++?
405 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner0b464252009-04-21 22:26:47 +0000406 if (!Var->hasLocalStorage())
407 return false;
408
409 // Blocks that have these can't be constant.
410 CurBlock->hasBlockDeclRefExprs = true;
411
412 // If we have nested blocks, the decl may be declared in an outer block (in
413 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
414 // be defined outside all of the current blocks (in which case the blocks do
415 // all get the bit). Walk the nesting chain.
416 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
417 NextBlock = NextBlock->PrevBlockInfo) {
418 // If we found the defining block for the variable, don't mark the block as
419 // having a reference outside it.
420 if (NextBlock->TheDecl == VD->getDeclContext())
421 break;
422
423 // Otherwise, the DeclRef from the inner block causes the outer one to need
424 // a snapshot as well.
425 NextBlock->hasBlockDeclRefExprs = true;
426 }
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000427
428 return true;
429}
430
431
432
Steve Naroff0acc9c92007-09-15 18:49:24 +0000433/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000434/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000435/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000436/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000437/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000438Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
439 IdentifierInfo &II,
440 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000441 const CXXScopeSpec *SS,
442 bool isAddressOfOperand) {
443 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000444 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000445}
446
Douglas Gregor566782a2009-01-06 05:10:23 +0000447/// BuildDeclRefExpr - Build either a DeclRefExpr or a
448/// QualifiedDeclRefExpr based on whether or not SS is a
449/// nested-name-specifier.
Anders Carlsson4571d812009-06-24 00:10:43 +0000450Sema::OwningExprResult
Sebastian Redl0c9da212009-02-03 20:19:35 +0000451Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
452 bool TypeDependent, bool ValueDependent,
453 const CXXScopeSpec *SS) {
Anders Carlsson9bd48662009-06-26 19:16:07 +0000454 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
455 Diag(Loc,
456 diag::err_auto_variable_cannot_appear_in_own_initializer)
457 << D->getDeclName();
458 return ExprError();
459 }
Anders Carlsson4571d812009-06-24 00:10:43 +0000460
461 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
462 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
463 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
464 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
465 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
466 << D->getIdentifier() << FD->getDeclName();
467 Diag(D->getLocation(), diag::note_local_variable_declared_here)
468 << D->getIdentifier();
469 return ExprError();
470 }
471 }
472 }
473 }
474
Douglas Gregor98189262009-06-19 23:52:42 +0000475 MarkDeclarationReferenced(Loc, D);
Anders Carlsson4571d812009-06-24 00:10:43 +0000476
477 Expr *E;
Douglas Gregor7e508262009-03-19 03:51:16 +0000478 if (SS && !SS->isEmpty()) {
Anders Carlsson4571d812009-06-24 00:10:43 +0000479 E = new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
480 ValueDependent, SS->getRange(),
Douglas Gregor041e9292009-03-26 23:56:24 +0000481 static_cast<NestedNameSpecifier *>(SS->getScopeRep()));
Douglas Gregor7e508262009-03-19 03:51:16 +0000482 } else
Anders Carlsson4571d812009-06-24 00:10:43 +0000483 E = new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
484
485 return Owned(E);
Douglas Gregor566782a2009-01-06 05:10:23 +0000486}
487
Douglas Gregor723d3332009-01-07 00:43:41 +0000488/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
489/// variable corresponding to the anonymous union or struct whose type
490/// is Record.
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000491static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
492 RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000493 assert(Record->isAnonymousStructOrUnion() &&
494 "Record must be an anonymous struct or union!");
495
Mike Stumpe127ae32009-05-16 07:39:55 +0000496 // FIXME: Once Decls are directly linked together, this will be an O(1)
497 // operation rather than a slow walk through DeclContext's vector (which
498 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregor723d3332009-01-07 00:43:41 +0000499 DeclContext *Ctx = Record->getDeclContext();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000500 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
501 DEnd = Ctx->decls_end();
Douglas Gregor723d3332009-01-07 00:43:41 +0000502 D != DEnd; ++D) {
503 if (*D == Record) {
504 // The object for the anonymous struct/union directly
505 // follows its type in the list of declarations.
506 ++D;
507 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000508 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000509 return *D;
510 }
511 }
512
513 assert(false && "Missing object for anonymous record");
514 return 0;
515}
516
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000517/// \brief Given a field that represents a member of an anonymous
518/// struct/union, build the path from that field's context to the
519/// actual member.
520///
521/// Construct the sequence of field member references we'll have to
522/// perform to get to the field in the anonymous union/struct. The
523/// list of members is built from the field outward, so traverse it
524/// backwards to go from an object in the current context to the field
525/// we found.
526///
527/// \returns The variable from which the field access should begin,
528/// for an anonymous struct/union that is not a member of another
529/// class. Otherwise, returns NULL.
530VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
531 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000532 assert(Field->getDeclContext()->isRecord() &&
533 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
534 && "Field must be stored inside an anonymous struct or union");
535
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000536 Path.push_back(Field);
Douglas Gregor723d3332009-01-07 00:43:41 +0000537 VarDecl *BaseObject = 0;
538 DeclContext *Ctx = Field->getDeclContext();
539 do {
540 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000541 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000542 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000543 Path.push_back(AnonField);
Douglas Gregor723d3332009-01-07 00:43:41 +0000544 else {
545 BaseObject = cast<VarDecl>(AnonObject);
546 break;
547 }
548 Ctx = Ctx->getParent();
549 } while (Ctx->isRecord() &&
550 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000551
552 return BaseObject;
553}
554
555Sema::OwningExprResult
556Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
557 FieldDecl *Field,
558 Expr *BaseObjectExpr,
559 SourceLocation OpLoc) {
560 llvm::SmallVector<FieldDecl *, 4> AnonFields;
561 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
562 AnonFields);
563
Douglas Gregor723d3332009-01-07 00:43:41 +0000564 // Build the expression that refers to the base object, from
565 // which we will build a sequence of member references to each
566 // of the anonymous union objects and, eventually, the field we
567 // found via name lookup.
568 bool BaseObjectIsPointer = false;
569 unsigned ExtraQuals = 0;
570 if (BaseObject) {
571 // BaseObject is an anonymous struct/union variable (and is,
572 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000573 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregor98189262009-06-19 23:52:42 +0000574 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff774e4152009-01-21 00:14:39 +0000575 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump9afab102009-02-19 03:04:26 +0000576 SourceLocation());
Douglas Gregor723d3332009-01-07 00:43:41 +0000577 ExtraQuals
578 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
579 } else if (BaseObjectExpr) {
580 // The caller provided the base object expression. Determine
581 // whether its a pointer and whether it adds any qualifiers to the
582 // anonymous struct/union fields we're looking into.
583 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000584 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000585 BaseObjectIsPointer = true;
586 ObjectType = ObjectPtr->getPointeeType();
587 }
588 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
589 } else {
590 // We've found a member of an anonymous struct/union that is
591 // inside a non-anonymous struct/union, so in a well-formed
592 // program our base object expression is "this".
593 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
594 if (!MD->isStatic()) {
595 QualType AnonFieldType
596 = Context.getTagDeclType(
597 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
598 QualType ThisType = Context.getTagDeclType(MD->getParent());
599 if ((Context.getCanonicalType(AnonFieldType)
600 == Context.getCanonicalType(ThisType)) ||
601 IsDerivedFrom(ThisType, AnonFieldType)) {
602 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000603 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000604 MD->getThisType(Context));
Douglas Gregor723d3332009-01-07 00:43:41 +0000605 BaseObjectIsPointer = true;
606 }
607 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000608 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
609 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000610 }
611 ExtraQuals = MD->getTypeQualifiers();
612 }
613
614 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000615 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
616 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000617 }
618
619 // Build the implicit member references to the field of the
620 // anonymous struct/union.
621 Expr *Result = BaseObjectExpr;
Mon P Wang04d89cb2009-07-22 03:08:17 +0000622 unsigned BaseAddrSpace = BaseObjectExpr->getType().getAddressSpace();
Douglas Gregor723d3332009-01-07 00:43:41 +0000623 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
624 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
625 FI != FIEnd; ++FI) {
626 QualType MemberType = (*FI)->getType();
627 if (!(*FI)->isMutable()) {
628 unsigned combinedQualifiers
629 = MemberType.getCVRQualifiers() | ExtraQuals;
630 MemberType = MemberType.getQualifiedType(combinedQualifiers);
631 }
Mon P Wang04d89cb2009-07-22 03:08:17 +0000632 if (BaseAddrSpace != MemberType.getAddressSpace())
633 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor98189262009-06-19 23:52:42 +0000634 MarkDeclarationReferenced(Loc, *FI);
Douglas Gregore399ad42009-08-26 22:36:53 +0000635 // FIXME: Might this end up being a qualified name?
Steve Naroff774e4152009-01-21 00:14:39 +0000636 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
637 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000638 BaseObjectIsPointer = false;
639 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregor723d3332009-01-07 00:43:41 +0000640 }
641
Sebastian Redlcd883f72009-01-18 18:53:16 +0000642 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000643}
644
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000645/// ActOnDeclarationNameExpr - The parser has read some kind of name
646/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
647/// performs lookup on that name and returns an expression that refers
648/// to that name. This routine isn't directly called from the parser,
649/// because the parser doesn't know about DeclarationName. Rather,
650/// this routine is called by ActOnIdentifierExpr,
651/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
652/// which form the DeclarationName from the corresponding syntactic
653/// forms.
654///
655/// HasTrailingLParen indicates whether this identifier is used in a
656/// function call context. LookupCtx is only used for a C++
657/// qualified-id (foo::bar) to indicate the class or namespace that
658/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000659///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000660/// isAddressOfOperand means that this expression is the direct operand
661/// of an address-of operator. This matters because this is the only
662/// situation where a qualified name referencing a non-static member may
663/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000664Sema::OwningExprResult
665Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
666 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000667 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000668 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000669 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000670 if (SS && SS->isInvalid())
671 return ExprError();
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000672
673 // C++ [temp.dep.expr]p3:
674 // An id-expression is type-dependent if it contains:
675 // -- a nested-name-specifier that contains a class-name that
676 // names a dependent type.
Douglas Gregorf3a200f2009-05-29 14:49:33 +0000677 // FIXME: Member of the current instantiation.
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000678 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000679 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
680 Loc, SS->getRange(),
Anders Carlsson4e8d5692009-07-09 00:05:08 +0000681 static_cast<NestedNameSpecifier *>(SS->getScopeRep()),
682 isAddressOfOperand));
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000683 }
684
Douglas Gregor411889e2009-02-13 23:20:09 +0000685 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
686 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000687
Sebastian Redlcd883f72009-01-18 18:53:16 +0000688 if (Lookup.isAmbiguous()) {
689 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
690 SS && SS->isSet() ? SS->getRange()
691 : SourceRange());
692 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000693 }
694
695 NamedDecl *D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000696
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000697 // If this reference is in an Objective-C method, then ivar lookup happens as
698 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000699 IdentifierInfo *II = Name.getAsIdentifierInfo();
700 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000701 // There are two cases to handle here. 1) scoped lookup could have failed,
702 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000703 // found a decl, but that decl is outside the current instance method (i.e.
704 // a global variable). In these two cases, we do a lookup for an ivar with
705 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000706 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000707 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000708 ObjCInterfaceDecl *ClassDeclared;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000709 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000710 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000711 if (DiagnoseUseOfDecl(IV, Loc))
712 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000713
714 // If we're referencing an invalid decl, just return this as a silent
715 // error node. The error diagnostic was already emitted on the decl.
716 if (IV->isInvalidDecl())
717 return ExprError();
718
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000719 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
720 // If a class method attemps to use a free standing ivar, this is
721 // an error.
722 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
723 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
724 << IV->getDeclName());
725 // If a class method uses a global variable, even if an ivar with
726 // same name exists, use the global.
727 if (!IsClsMethod) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000728 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
729 ClassDeclared != IFace)
730 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Mike Stumpe127ae32009-05-16 07:39:55 +0000731 // FIXME: This should use a new expr for a direct reference, don't
732 // turn this into Self->ivar, just return a BareIVarExpr or something.
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000733 IdentifierInfo &II = Context.Idents.get("self");
Argiris Kirtzidis3bb49042009-07-18 08:49:37 +0000734 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, SourceLocation(),
735 II, false);
Douglas Gregor98189262009-06-19 23:52:42 +0000736 MarkDeclarationReferenced(Loc, IV);
Daniel Dunbarf5254bd2009-04-21 01:19:28 +0000737 return Owned(new (Context)
738 ObjCIvarRefExpr(IV, IV->getType(), Loc,
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000739 SelfExpr.takeAs<Expr>(), true, true));
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000740 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000741 }
Mike Stump90fc78e2009-08-04 21:02:39 +0000742 } else if (getCurMethodDecl()->isInstanceMethod()) {
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000743 // We should warn if a local variable hides an ivar.
744 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000745 ObjCInterfaceDecl *ClassDeclared;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000746 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000747 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
748 IFace == ClassDeclared)
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000749 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000750 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000751 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000752 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000753 if (D == 0 && II->isStr("super")) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000754 QualType T;
755
756 if (getCurMethodDecl()->isInstanceMethod())
Steve Naroff329ec222009-07-10 23:34:53 +0000757 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
758 getCurMethodDecl()->getClassInterface()));
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000759 else
760 T = Context.getObjCClassType();
Steve Naroff774e4152009-01-21 00:14:39 +0000761 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000762 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000763 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000764
Douglas Gregoraa57e862009-02-18 21:56:37 +0000765 // Determine whether this name might be a candidate for
766 // argument-dependent lookup.
767 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
768 HasTrailingLParen;
769
770 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000771 // We've seen something of the form
772 //
773 // identifier(
774 //
775 // and we did not find any entity by the name
776 // "identifier". However, this identifier is still subject to
777 // argument-dependent lookup, so keep track of the name.
778 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
779 Context.OverloadTy,
780 Loc));
781 }
782
Chris Lattner4b009652007-07-25 00:24:17 +0000783 if (D == 0) {
784 // Otherwise, this could be an implicitly declared function reference (legal
785 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000786 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000787 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000788 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000789 else {
790 // If this name wasn't predeclared and if this is not a function call,
791 // diagnose the problem.
Anders Carlsson4355a392009-08-30 00:54:35 +0000792 if (SS && !SS->isEmpty()) {
793 DiagnoseMissingMember(Loc, Name,
794 (NestedNameSpecifier *)SS->getScopeRep(),
795 SS->getRange());
796 return ExprError();
797 } else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000798 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000799 return ExprError(Diag(Loc, diag::err_undeclared_use)
800 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000801 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000802 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000803 }
804 }
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000805
806 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
807 // Warn about constructs like:
808 // if (void *X = foo()) { ... } else { X }.
809 // In the else block, the pointer is always false.
810
811 // FIXME: In a template instantiation, we don't have scope
812 // information to check this property.
813 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
814 Scope *CheckS = S;
815 while (CheckS) {
816 if (CheckS->isWithinElse() &&
817 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
818 if (Var->getType()->isBooleanType())
819 ExprError(Diag(Loc, diag::warn_value_always_false)
820 << Var->getDeclName());
821 else
822 ExprError(Diag(Loc, diag::warn_value_always_zero)
823 << Var->getDeclName());
824 break;
825 }
826
827 // Move up one more control parent to check again.
828 CheckS = CheckS->getControlParent();
829 if (CheckS)
830 CheckS = CheckS->getParent();
831 }
832 }
833 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
834 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
835 // C99 DR 316 says that, if a function type comes from a
836 // function definition (without a prototype), that type is only
837 // used for checking compatibility. Therefore, when referencing
838 // the function, we pretend that we don't have the full function
839 // type.
840 if (DiagnoseUseOfDecl(Func, Loc))
841 return ExprError();
Douglas Gregor723d3332009-01-07 00:43:41 +0000842
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000843 QualType T = Func->getType();
844 QualType NoProtoType = T;
845 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
846 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
847 return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
848 }
849 }
850
851 return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand);
852}
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000853/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanian843336e2009-07-29 19:40:11 +0000854bool
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000855Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
856 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
857 if (CXXRecordDecl *RD =
858 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
859 QualType DestType =
860 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000861 if (DestType->isDependentType() || From->getType()->isDependentType())
862 return false;
863 QualType FromRecordType = From->getType();
864 QualType DestRecordType = DestType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000865 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000866 DestType = Context.getPointerType(DestType);
867 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000868 }
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +0000869 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
870 CheckDerivedToBaseConversion(FromRecordType,
871 DestRecordType,
872 From->getSourceRange().getBegin(),
873 From->getSourceRange()))
874 return true;
Anders Carlsson85186942009-07-31 01:23:52 +0000875 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
876 /*isLvalue=*/true);
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000877 }
Fariborz Jahanian843336e2009-07-29 19:40:11 +0000878 return false;
Fariborz Jahanian80b859e2009-07-29 18:40:24 +0000879}
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000880
Douglas Gregorc1991bf2009-08-31 23:41:50 +0000881/// \brief Build a MemberExpr AST node.
Douglas Gregore399ad42009-08-26 22:36:53 +0000882static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
883 const CXXScopeSpec *SS, NamedDecl *Member,
884 SourceLocation Loc, QualType Ty) {
885 if (SS && SS->isSet())
Douglas Gregorc1991bf2009-08-31 23:41:50 +0000886 return MemberExpr::Create(C, Base, isArrow,
887 (NestedNameSpecifier *)SS->getScopeRep(),
Douglas Gregord33e3282009-09-01 00:37:14 +0000888 SS->getRange(), Member, Loc,
889 // FIXME: Explicit template argument lists
890 false, SourceLocation(), 0, 0, SourceLocation(),
891 Ty);
Douglas Gregore399ad42009-08-26 22:36:53 +0000892
893 return new (C) MemberExpr(Base, isArrow, Member, Loc, Ty);
894}
895
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000896/// \brief Complete semantic analysis for a reference to the given declaration.
897Sema::OwningExprResult
898Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
899 bool HasTrailingLParen,
900 const CXXScopeSpec *SS,
901 bool isAddressOfOperand) {
902 assert(D && "Cannot refer to a NULL declaration");
903 DeclarationName Name = D->getDeclName();
904
Sebastian Redl0c9da212009-02-03 20:19:35 +0000905 // If this is an expression of the form &Class::member, don't build an
906 // implicit member ref, because we want a pointer to the member in general,
907 // not any specific instance's member.
908 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000909 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor09be81b2009-02-04 17:27:36 +0000910 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000911 QualType DType;
912 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
913 DType = FD->getType().getNonReferenceType();
914 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
915 DType = Method->getType();
916 } else if (isa<OverloadedFunctionDecl>(D)) {
917 DType = Context.OverloadTy;
918 }
919 // Could be an inner type. That's diagnosed below, so ignore it here.
920 if (!DType.isNull()) {
921 // The pointer is type- and value-dependent if it points into something
922 // dependent.
Douglas Gregorf3a200f2009-05-29 14:49:33 +0000923 bool Dependent = DC->isDependentContext();
Anders Carlsson4571d812009-06-24 00:10:43 +0000924 return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
Sebastian Redl0c9da212009-02-03 20:19:35 +0000925 }
926 }
927 }
928
Douglas Gregor723d3332009-01-07 00:43:41 +0000929 // We may have found a field within an anonymous union or struct
930 // (C++ [class.union]).
931 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
932 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
933 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000934
Douglas Gregor3257fb52008-12-22 05:46:06 +0000935 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
936 if (!MD->isStatic()) {
937 // C++ [class.mfct.nonstatic]p2:
938 // [...] if name lookup (3.4.1) resolves the name in the
939 // id-expression to a nonstatic nontype member of class X or of
940 // a base class of X, the id-expression is transformed into a
941 // class member access expression (5.2.5) using (*this) (9.3.2)
942 // as the postfix-expression to the left of the '.' operator.
943 DeclContext *Ctx = 0;
944 QualType MemberType;
945 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
946 Ctx = FD->getDeclContext();
947 MemberType = FD->getType();
948
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000949 if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
Douglas Gregor3257fb52008-12-22 05:46:06 +0000950 MemberType = RefType->getPointeeType();
951 else if (!FD->isMutable()) {
952 unsigned combinedQualifiers
953 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
954 MemberType = MemberType.getQualifiedType(combinedQualifiers);
955 }
956 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
957 if (!Method->isStatic()) {
958 Ctx = Method->getParent();
959 MemberType = Method->getType();
960 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000961 } else if (FunctionTemplateDecl *FunTmpl
962 = dyn_cast<FunctionTemplateDecl>(D)) {
963 if (CXXMethodDecl *Method
964 = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())) {
965 if (!Method->isStatic()) {
966 Ctx = Method->getParent();
967 MemberType = Context.OverloadTy;
968 }
969 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000970 } else if (OverloadedFunctionDecl *Ovl
971 = dyn_cast<OverloadedFunctionDecl>(D)) {
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000972 // FIXME: We need an abstraction for iterating over one or more function
973 // templates or functions. This code is far too repetitive!
Douglas Gregor3257fb52008-12-22 05:46:06 +0000974 for (OverloadedFunctionDecl::function_iterator
975 Func = Ovl->function_begin(),
976 FuncEnd = Ovl->function_end();
977 Func != FuncEnd; ++Func) {
Douglas Gregor4fdcdda2009-08-21 00:16:32 +0000978 CXXMethodDecl *DMethod = 0;
979 if (FunctionTemplateDecl *FunTmpl
980 = dyn_cast<FunctionTemplateDecl>(*Func))
981 DMethod = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
982 else
983 DMethod = dyn_cast<CXXMethodDecl>(*Func);
984
985 if (DMethod && !DMethod->isStatic()) {
986 Ctx = DMethod->getDeclContext();
987 MemberType = Context.OverloadTy;
988 break;
989 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000990 }
991 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000992
993 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000994 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
995 QualType ThisType = Context.getTagDeclType(MD->getParent());
996 if ((Context.getCanonicalType(CtxType)
997 == Context.getCanonicalType(ThisType)) ||
998 IsDerivedFrom(ThisType, CtxType)) {
999 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +00001000 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +00001001 MD->getThisType(Context));
Douglas Gregor98189262009-06-19 23:52:42 +00001002 MarkDeclarationReferenced(Loc, D);
Fariborz Jahanian843336e2009-07-29 19:40:11 +00001003 if (PerformObjectMemberConversion(This, D))
1004 return ExprError();
Anders Carlsson9fbe6872009-08-08 16:55:18 +00001005 if (DiagnoseUseOfDecl(D, Loc))
1006 return ExprError();
Douglas Gregore399ad42009-08-26 22:36:53 +00001007 return Owned(BuildMemberExpr(Context, This, true, SS, D,
1008 Loc, MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001009 }
1010 }
1011 }
1012 }
1013
Douglas Gregor8acb7272008-12-11 16:49:14 +00001014 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001015 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1016 if (MD->isStatic())
1017 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +00001018 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
1019 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001020 }
1021
Douglas Gregor3257fb52008-12-22 05:46:06 +00001022 // Any other ways we could have found the field in a well-formed
1023 // program would have been turned into implicit member expressions
1024 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001025 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
1026 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001027 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00001028
Chris Lattner4b009652007-07-25 00:24:17 +00001029 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001030 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +00001031 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001032 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001033 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001034 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +00001035
Steve Naroffd6163f32008-09-05 22:11:13 +00001036 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +00001037 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001038 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
1039 false, false, SS);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001040 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001041 return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
1042 false, false, SS);
Anders Carlsson89908542009-08-29 01:06:32 +00001043 else if (UnresolvedUsingDecl *UD = dyn_cast<UnresolvedUsingDecl>(D))
1044 return BuildDeclRefExpr(UD, Context.DependentTy, Loc,
1045 /*TypeDependent=*/true,
1046 /*ValueDependent=*/true, SS);
1047
Steve Naroffd6163f32008-09-05 22:11:13 +00001048 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001049
Douglas Gregoraa57e862009-02-18 21:56:37 +00001050 // Check whether this declaration can be used. Note that we suppress
1051 // this check when we're going to perform argument-dependent lookup
1052 // on this function name, because this might not be the function
1053 // that overload resolution actually selects.
Douglas Gregor6ef403d2009-06-30 15:47:41 +00001054 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
1055 HasTrailingLParen;
Douglas Gregoraa57e862009-02-18 21:56:37 +00001056 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1057 return ExprError();
1058
Steve Naroffd6163f32008-09-05 22:11:13 +00001059 // Only create DeclRefExpr's for valid Decl's.
1060 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001061 return ExprError();
1062
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001063 // If the identifier reference is inside a block, and it refers to a value
1064 // that is outside the block, create a BlockDeclRefExpr instead of a
1065 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1066 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +00001067 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001068 // We do not do this for things like enum constants, global variables, etc,
1069 // as they do not get snapshotted.
1070 //
1071 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregor98189262009-06-19 23:52:42 +00001072 MarkDeclarationReferenced(Loc, VD);
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001073 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff52059382008-10-10 01:28:17 +00001074 // The BlocksAttr indicates the variable is bound by-reference.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00001075 if (VD->getAttr<BlocksAttr>())
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001076 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001077 // This is to record that a 'const' was actually synthesize and added.
1078 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff52059382008-10-10 01:28:17 +00001079 // Variable will be bound by-copy, make it const within the closure.
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001080
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001081 ExprTy.addConst();
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001082 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
1083 constAdded));
Steve Naroff52059382008-10-10 01:28:17 +00001084 }
1085 // If this reference is not in a block or if the referenced variable is
1086 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001087
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001088 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +00001089 bool ValueDependent = false;
1090 if (getLangOptions().CPlusPlus) {
1091 // C++ [temp.dep.expr]p3:
1092 // An id-expression is type-dependent if it contains:
1093 // - an identifier that was declared with a dependent type,
1094 if (VD->getType()->isDependentType())
1095 TypeDependent = true;
1096 // - FIXME: a template-id that is dependent,
1097 // - a conversion-function-id that specifies a dependent type,
1098 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1099 Name.getCXXNameType()->isDependentType())
1100 TypeDependent = true;
1101 // - a nested-name-specifier that contains a class-name that
1102 // names a dependent type.
1103 else if (SS && !SS->isEmpty()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001104 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregora5d84612008-12-10 20:57:37 +00001105 DC; DC = DC->getParent()) {
1106 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +00001107 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +00001108 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1109 if (Context.getTypeDeclType(Record)->isDependentType()) {
1110 TypeDependent = true;
1111 break;
1112 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001113 }
1114 }
1115 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001116
Douglas Gregora5d84612008-12-10 20:57:37 +00001117 // C++ [temp.dep.constexpr]p2:
1118 //
1119 // An identifier is value-dependent if it is:
1120 // - a name declared with a dependent type,
1121 if (TypeDependent)
1122 ValueDependent = true;
1123 // - the name of a non-type template parameter,
1124 else if (isa<NonTypeTemplateParmDecl>(VD))
1125 ValueDependent = true;
1126 // - a constant with integral or enumeration type and is
1127 // initialized with an expression that is value-dependent
Eli Friedman1f7744a2009-06-11 01:11:20 +00001128 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
1129 if (Dcl->getType().getCVRQualifiers() == QualType::Const &&
1130 Dcl->getInit()) {
1131 ValueDependent = Dcl->getInit()->isValueDependent();
1132 }
1133 }
Douglas Gregora5d84612008-12-10 20:57:37 +00001134 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001135
Anders Carlsson4571d812009-06-24 00:10:43 +00001136 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1137 TypeDependent, ValueDependent, SS);
Chris Lattner4b009652007-07-25 00:24:17 +00001138}
1139
Sebastian Redlcd883f72009-01-18 18:53:16 +00001140Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1141 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +00001142 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001143
Chris Lattner4b009652007-07-25 00:24:17 +00001144 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001145 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +00001146 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1147 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1148 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001149 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001150
Chris Lattner7e637512008-01-12 08:14:25 +00001151 // Pre-defined identifiers are of type char[x], where x is the length of the
1152 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001153 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +00001154 if (FunctionDecl *FD = getCurFunctionDecl())
1155 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +00001156 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1157 Length = MD->getSynthesizedMethodSize();
1158 else {
1159 Diag(Loc, diag::ext_predef_outside_function);
1160 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1161 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1162 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001163
1164
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001165 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001166 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001167 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +00001168 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +00001169}
1170
Sebastian Redlcd883f72009-01-18 18:53:16 +00001171Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +00001172 llvm::SmallString<16> CharBuffer;
1173 CharBuffer.resize(Tok.getLength());
1174 const char *ThisTokBegin = &CharBuffer[0];
1175 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001176
Chris Lattner4b009652007-07-25 00:24:17 +00001177 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1178 Tok.getLocation(), PP);
1179 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001180 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001181
1182 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1183
Sebastian Redl75324932009-01-20 22:23:13 +00001184 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1185 Literal.isWide(),
1186 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001187}
1188
Sebastian Redlcd883f72009-01-18 18:53:16 +00001189Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1190 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001191 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1192 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001193 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001194 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001195 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001196 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001197 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001198
Chris Lattner4b009652007-07-25 00:24:17 +00001199 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001200 // Add padding so that NumericLiteralParser can overread by one character.
1201 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001202 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001203
Chris Lattner4b009652007-07-25 00:24:17 +00001204 // Get the spelling of the token, which eliminates trigraphs, etc.
1205 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001206
Chris Lattner4b009652007-07-25 00:24:17 +00001207 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1208 Tok.getLocation(), PP);
1209 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001210 return ExprError();
1211
Chris Lattner1de66eb2007-08-26 03:42:43 +00001212 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001213
Chris Lattner1de66eb2007-08-26 03:42:43 +00001214 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001215 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001216 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001217 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001218 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001219 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001220 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001221 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001222
1223 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1224
Ted Kremenekddedbe22007-11-29 00:56:49 +00001225 // isExact will be set by GetFloatValue().
1226 bool isExact = false;
Chris Lattnerff1bf1a2009-06-29 17:34:55 +00001227 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1228 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001229
Chris Lattner1de66eb2007-08-26 03:42:43 +00001230 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001231 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001232 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001233 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001234
Neil Booth7421e9c2007-08-29 22:00:19 +00001235 // long long is a C99 feature.
1236 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001237 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001238 Diag(Tok.getLocation(), diag::ext_longlong);
1239
Chris Lattner4b009652007-07-25 00:24:17 +00001240 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001241 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001242
Chris Lattner4b009652007-07-25 00:24:17 +00001243 if (Literal.GetIntegerValue(ResultVal)) {
1244 // If this value didn't fit into uintmax_t, warn and force to ull.
1245 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001246 Ty = Context.UnsignedLongLongTy;
1247 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001248 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001249 } else {
1250 // If this value fits into a ULL, try to figure out what else it fits into
1251 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001252
Chris Lattner4b009652007-07-25 00:24:17 +00001253 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1254 // be an unsigned int.
1255 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1256
1257 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001258 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001259 if (!Literal.isLong && !Literal.isLongLong) {
1260 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001261 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001262
Chris Lattner4b009652007-07-25 00:24:17 +00001263 // Does it fit in a unsigned int?
1264 if (ResultVal.isIntN(IntSize)) {
1265 // Does it fit in a signed int?
1266 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001267 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001268 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001269 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001270 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001271 }
Chris Lattner4b009652007-07-25 00:24:17 +00001272 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001273
Chris Lattner4b009652007-07-25 00:24:17 +00001274 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001275 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001276 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001277
Chris Lattner4b009652007-07-25 00:24:17 +00001278 // Does it fit in a unsigned long?
1279 if (ResultVal.isIntN(LongSize)) {
1280 // Does it fit in a signed long?
1281 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001282 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001283 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001284 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001285 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001286 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001287 }
1288
Chris Lattner4b009652007-07-25 00:24:17 +00001289 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001290 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001291 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001292
Chris Lattner4b009652007-07-25 00:24:17 +00001293 // Does it fit in a unsigned long long?
1294 if (ResultVal.isIntN(LongLongSize)) {
1295 // Does it fit in a signed long long?
1296 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001297 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001298 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001299 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001300 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001301 }
1302 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001303
Chris Lattner4b009652007-07-25 00:24:17 +00001304 // If we still couldn't decide a type, we probably have something that
1305 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001306 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001307 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001308 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001309 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001310 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001311
Chris Lattnere4068872008-05-09 05:59:00 +00001312 if (ResultVal.getBitWidth() != Width)
1313 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001314 }
Sebastian Redl75324932009-01-20 22:23:13 +00001315 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001316 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001317
Chris Lattner1de66eb2007-08-26 03:42:43 +00001318 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1319 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001320 Res = new (Context) ImaginaryLiteral(Res,
1321 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001322
1323 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001324}
1325
Sebastian Redlcd883f72009-01-18 18:53:16 +00001326Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1327 SourceLocation R, ExprArg Val) {
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001328 Expr *E = Val.takeAs<Expr>();
Chris Lattner48d7f382008-04-02 04:24:33 +00001329 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001330 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001331}
1332
1333/// The UsualUnaryConversions() function is *not* called by this routine.
1334/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001335bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001336 SourceLocation OpLoc,
1337 const SourceRange &ExprRange,
1338 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001339 if (exprType->isDependentType())
1340 return false;
1341
Chris Lattner4b009652007-07-25 00:24:17 +00001342 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001343 if (isa<FunctionType>(exprType)) {
Chris Lattner95933c12009-04-24 00:30:45 +00001344 // alignof(function) is allowed as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001345 if (isSizeof)
1346 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1347 return false;
1348 }
1349
Chris Lattner95933c12009-04-24 00:30:45 +00001350 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001351 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001352 Diag(OpLoc, diag::ext_sizeof_void_type)
1353 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001354 return false;
1355 }
Chris Lattnere1127c42009-04-21 19:55:16 +00001356
Chris Lattner95933c12009-04-24 00:30:45 +00001357 if (RequireCompleteType(OpLoc, exprType,
1358 isSizeof ? diag::err_sizeof_incomplete_type :
Anders Carlssona21e7872009-08-26 23:45:07 +00001359 PDiag(diag::err_alignof_incomplete_type)
1360 << ExprRange))
Chris Lattner95933c12009-04-24 00:30:45 +00001361 return true;
1362
1363 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianbf2b0952009-04-24 17:34:33 +00001364 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner95933c12009-04-24 00:30:45 +00001365 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnerf3ce8572009-04-24 22:30:50 +00001366 << exprType << isSizeof << ExprRange;
1367 return true;
Chris Lattnere1127c42009-04-21 19:55:16 +00001368 }
1369
Chris Lattner95933c12009-04-24 00:30:45 +00001370 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001371}
1372
Chris Lattner8d9f7962009-01-24 20:17:12 +00001373bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1374 const SourceRange &ExprRange) {
1375 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001376
Chris Lattner8d9f7962009-01-24 20:17:12 +00001377 // alignof decl is always ok.
1378 if (isa<DeclRefExpr>(E))
1379 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001380
1381 // Cannot know anything else if the expression is dependent.
1382 if (E->isTypeDependent())
1383 return false;
1384
Douglas Gregor531434b2009-05-02 02:18:30 +00001385 if (E->getBitField()) {
1386 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1387 return true;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001388 }
Douglas Gregor531434b2009-05-02 02:18:30 +00001389
1390 // Alignment of a field access is always okay, so long as it isn't a
1391 // bit-field.
1392 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump6eeaa782009-07-22 18:58:19 +00001393 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor531434b2009-05-02 02:18:30 +00001394 return false;
1395
Chris Lattner8d9f7962009-01-24 20:17:12 +00001396 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1397}
1398
Douglas Gregor396f1142009-03-13 21:01:28 +00001399/// \brief Build a sizeof or alignof expression given a type operand.
1400Action::OwningExprResult
1401Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1402 bool isSizeOf, SourceRange R) {
1403 if (T.isNull())
1404 return ExprError();
1405
1406 if (!T->isDependentType() &&
1407 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1408 return ExprError();
1409
1410 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1411 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1412 Context.getSizeType(), OpLoc,
1413 R.getEnd()));
1414}
1415
1416/// \brief Build a sizeof or alignof expression given an expression
1417/// operand.
1418Action::OwningExprResult
1419Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1420 bool isSizeOf, SourceRange R) {
1421 // Verify that the operand is valid.
1422 bool isInvalid = false;
1423 if (E->isTypeDependent()) {
1424 // Delay type-checking for type-dependent expressions.
1425 } else if (!isSizeOf) {
1426 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor531434b2009-05-02 02:18:30 +00001427 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor396f1142009-03-13 21:01:28 +00001428 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1429 isInvalid = true;
1430 } else {
1431 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1432 }
1433
1434 if (isInvalid)
1435 return ExprError();
1436
1437 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1438 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1439 Context.getSizeType(), OpLoc,
1440 R.getEnd()));
1441}
1442
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001443/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1444/// the same for @c alignof and @c __alignof
1445/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001446Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001447Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1448 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001449 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001450 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001451
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001452 if (isType) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00001453 // FIXME: Preserve type source info.
1454 QualType ArgTy = GetTypeFromParser(TyOrEx);
Douglas Gregor396f1142009-03-13 21:01:28 +00001455 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1456 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001457
Douglas Gregor396f1142009-03-13 21:01:28 +00001458 // Get the end location.
1459 Expr *ArgEx = (Expr *)TyOrEx;
1460 Action::OwningExprResult Result
1461 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1462
1463 if (Result.isInvalid())
1464 DeleteExpr(ArgEx);
1465
1466 return move(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001467}
1468
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001469QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001470 if (V->isTypeDependent())
1471 return Context.DependentTy;
Chris Lattner03931a72007-08-24 21:16:53 +00001472
Chris Lattnera16e42d2007-08-26 05:39:26 +00001473 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001474 if (const ComplexType *CT = V->getType()->getAsComplexType())
1475 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001476
1477 // Otherwise they pass through real integer and floating point types here.
1478 if (V->getType()->isArithmeticType())
1479 return V->getType();
1480
1481 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001482 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1483 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001484 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001485}
1486
1487
Chris Lattner4b009652007-07-25 00:24:17 +00001488
Sebastian Redl8b769972009-01-19 00:08:26 +00001489Action::OwningExprResult
1490Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1491 tok::TokenKind Kind, ExprArg Input) {
Nate Begemane85f43d2009-08-10 23:49:36 +00001492 // Since this might be a postfix expression, get rid of ParenListExprs.
1493 Input = MaybeConvertParenListExprToParenExpr(S, move(Input));
Sebastian Redl8b769972009-01-19 00:08:26 +00001494 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001495
Chris Lattner4b009652007-07-25 00:24:17 +00001496 UnaryOperator::Opcode Opc;
1497 switch (Kind) {
1498 default: assert(0 && "Unknown unary op!");
1499 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1500 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1501 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001502
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001503 if (getLangOptions().CPlusPlus &&
1504 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1505 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001506 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001507 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1508
1509 // C++ [over.inc]p1:
1510 //
1511 // [...] If the function is a member function with one
1512 // parameter (which shall be of type int) or a non-member
1513 // function with two parameters (the second of which shall be
1514 // of type int), it defines the postfix increment operator ++
1515 // for objects of that type. When the postfix increment is
1516 // called as a result of using the ++ operator, the int
1517 // argument will have value zero.
1518 Expr *Args[2] = {
1519 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001520 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1521 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001522 };
1523
1524 // Build the candidate set for overloading
1525 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001526 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001527
1528 // Perform overload resolution.
1529 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001530 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001531 case OR_Success: {
1532 // We found a built-in operator or an overloaded operator.
1533 FunctionDecl *FnDecl = Best->Function;
1534
1535 if (FnDecl) {
1536 // We matched an overloaded operator. Build a call to that
1537 // operator.
1538
1539 // Convert the arguments.
1540 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1541 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001542 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001543 } else {
1544 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001545 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001546 FnDecl->getParamDecl(0)->getType(),
1547 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001548 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001549 }
1550
1551 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001552 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001553 = FnDecl->getType()->getAsFunctionType()->getResultType();
1554 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001555
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001556 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001557 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001558 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001559 UsualUnaryConversions(FnExpr);
1560
Sebastian Redl8b769972009-01-19 00:08:26 +00001561 Input.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001562 Args[0] = Arg;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001563 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1564 Args, 2, ResultTy,
1565 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001566 } else {
1567 // We matched a built-in operator. Convert the arguments, then
1568 // break out so that we will build the appropriate built-in
1569 // operator node.
1570 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1571 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001572 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001573
1574 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001575 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001576 }
1577
1578 case OR_No_Viable_Function:
1579 // No viable function; fall through to handling this as a
1580 // built-in operator, which will produce an error message for us.
1581 break;
1582
1583 case OR_Ambiguous:
1584 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1585 << UnaryOperator::getOpcodeStr(Opc)
1586 << Arg->getSourceRange();
1587 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001588 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001589
1590 case OR_Deleted:
1591 Diag(OpLoc, diag::err_ovl_deleted_oper)
1592 << Best->Function->isDeleted()
1593 << UnaryOperator::getOpcodeStr(Opc)
1594 << Arg->getSourceRange();
1595 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1596 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001597 }
1598
1599 // Either we found no viable overloaded operator or we matched a
1600 // built-in operator. In either case, fall through to trying to
1601 // build a built-in operation.
1602 }
1603
Eli Friedman94d30952009-07-22 23:24:42 +00001604 Input.release();
1605 Input = Arg;
Eli Friedman79341142009-07-22 22:25:00 +00001606 return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
Chris Lattner4b009652007-07-25 00:24:17 +00001607}
1608
Sebastian Redl8b769972009-01-19 00:08:26 +00001609Action::OwningExprResult
1610Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1611 ExprArg Idx, SourceLocation RLoc) {
Nate Begemane85f43d2009-08-10 23:49:36 +00001612 // Since this might be a postfix expression, get rid of ParenListExprs.
1613 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1614
Sebastian Redl8b769972009-01-19 00:08:26 +00001615 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1616 *RHSExp = static_cast<Expr*>(Idx.get());
Nate Begemane85f43d2009-08-10 23:49:36 +00001617
Douglas Gregor80723c52008-11-19 17:17:41 +00001618 if (getLangOptions().CPlusPlus &&
Douglas Gregorde72f3e2009-05-19 00:01:19 +00001619 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1620 Base.release();
1621 Idx.release();
1622 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1623 Context.DependentTy, RLoc));
1624 }
1625
1626 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001627 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001628 LHSExp->getType()->isEnumeralType() ||
1629 RHSExp->getType()->isRecordType() ||
1630 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001631 // Add the appropriate overloaded operators (C++ [over.match.oper])
1632 // to the candidate set.
1633 OverloadCandidateSet CandidateSet;
1634 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001635 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1636 SourceRange(LLoc, RLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001637
Douglas Gregor80723c52008-11-19 17:17:41 +00001638 // Perform overload resolution.
1639 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001640 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001641 case OR_Success: {
1642 // We found a built-in operator or an overloaded operator.
1643 FunctionDecl *FnDecl = Best->Function;
1644
1645 if (FnDecl) {
1646 // We matched an overloaded operator. Build a call to that
1647 // operator.
1648
1649 // Convert the arguments.
1650 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1651 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1652 PerformCopyInitialization(RHSExp,
1653 FnDecl->getParamDecl(0)->getType(),
1654 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001655 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001656 } else {
1657 // Convert the arguments.
1658 if (PerformCopyInitialization(LHSExp,
1659 FnDecl->getParamDecl(0)->getType(),
1660 "passing") ||
1661 PerformCopyInitialization(RHSExp,
1662 FnDecl->getParamDecl(1)->getType(),
1663 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001664 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001665 }
1666
1667 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001668 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001669 = FnDecl->getType()->getAsFunctionType()->getResultType();
1670 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001671
Douglas Gregor80723c52008-11-19 17:17:41 +00001672 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001673 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1674 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001675 UsualUnaryConversions(FnExpr);
1676
Sebastian Redl8b769972009-01-19 00:08:26 +00001677 Base.release();
1678 Idx.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001679 Args[0] = LHSExp;
1680 Args[1] = RHSExp;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001681 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1682 FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001683 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001684 } else {
1685 // We matched a built-in operator. Convert the arguments, then
1686 // break out so that we will build the appropriate built-in
1687 // operator node.
1688 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1689 "passing") ||
1690 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1691 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001692 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001693
1694 break;
1695 }
1696 }
1697
1698 case OR_No_Viable_Function:
1699 // No viable function; fall through to handling this as a
1700 // built-in operator, which will produce an error message for us.
1701 break;
1702
1703 case OR_Ambiguous:
1704 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1705 << "[]"
1706 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1707 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001708 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001709
1710 case OR_Deleted:
1711 Diag(LLoc, diag::err_ovl_deleted_oper)
1712 << Best->Function->isDeleted()
1713 << "[]"
1714 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1715 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1716 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001717 }
1718
1719 // Either we found no viable overloaded operator or we matched a
1720 // built-in operator. In either case, fall through to trying to
1721 // build a built-in operation.
1722 }
1723
Chris Lattner4b009652007-07-25 00:24:17 +00001724 // Perform default conversions.
1725 DefaultFunctionArrayConversion(LHSExp);
1726 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001727
Chris Lattner4b009652007-07-25 00:24:17 +00001728 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1729
1730 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001731 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001732 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001733 // and index from the expression types.
1734 Expr *BaseExpr, *IndexExpr;
1735 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001736 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1737 BaseExpr = LHSExp;
1738 IndexExpr = RHSExp;
1739 ResultType = Context.DependentTy;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001740 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001741 BaseExpr = LHSExp;
1742 IndexExpr = RHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001743 ResultType = PTy->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001744 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001745 // Handle the uncommon case of "123[Ptr]".
1746 BaseExpr = RHSExp;
1747 IndexExpr = LHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001748 ResultType = PTy->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00001749 } else if (const ObjCObjectPointerType *PTy =
1750 LHSTy->getAsObjCObjectPointerType()) {
1751 BaseExpr = LHSExp;
1752 IndexExpr = RHSExp;
1753 ResultType = PTy->getPointeeType();
1754 } else if (const ObjCObjectPointerType *PTy =
1755 RHSTy->getAsObjCObjectPointerType()) {
1756 // Handle the uncommon case of "123[Ptr]".
1757 BaseExpr = RHSExp;
1758 IndexExpr = LHSExp;
1759 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001760 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1761 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001762 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001763
Chris Lattner4b009652007-07-25 00:24:17 +00001764 // FIXME: need to deal with const...
1765 ResultType = VTy->getElementType();
Eli Friedmand4614072009-04-25 23:46:54 +00001766 } else if (LHSTy->isArrayType()) {
1767 // If we see an array that wasn't promoted by
1768 // DefaultFunctionArrayConversion, it must be an array that
1769 // wasn't promoted because of the C90 rule that doesn't
1770 // allow promoting non-lvalue arrays. Warn, then
1771 // force the promotion here.
1772 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1773 LHSExp->getSourceRange();
1774 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1775 LHSTy = LHSExp->getType();
1776
1777 BaseExpr = LHSExp;
1778 IndexExpr = RHSExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001779 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmand4614072009-04-25 23:46:54 +00001780 } else if (RHSTy->isArrayType()) {
1781 // Same as previous, except for 123[f().a] case
1782 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1783 RHSExp->getSourceRange();
1784 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1785 RHSTy = RHSExp->getType();
1786
1787 BaseExpr = RHSExp;
1788 IndexExpr = LHSExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001789 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001790 } else {
Chris Lattner7264d212009-04-25 22:50:55 +00001791 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1792 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00001793 }
Chris Lattner4b009652007-07-25 00:24:17 +00001794 // C99 6.5.2.1p1
Nate Begemane85f43d2009-08-10 23:49:36 +00001795 if (!(IndexExpr->getType()->isIntegerType() &&
1796 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner7264d212009-04-25 22:50:55 +00001797 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1798 << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001799
Douglas Gregor05e28f62009-03-24 19:52:54 +00001800 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1801 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1802 // type. Note that Functions are not objects, and that (in C99 parlance)
1803 // incomplete types are not object types.
1804 if (ResultType->isFunctionType()) {
1805 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1806 << ResultType << BaseExpr->getSourceRange();
1807 return ExprError();
1808 }
Chris Lattner95933c12009-04-24 00:30:45 +00001809
Douglas Gregor05e28f62009-03-24 19:52:54 +00001810 if (!ResultType->isDependentType() &&
Anders Carlssona21e7872009-08-26 23:45:07 +00001811 RequireCompleteType(LLoc, ResultType,
1812 PDiag(diag::err_subscript_incomplete_type)
1813 << BaseExpr->getSourceRange()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00001814 return ExprError();
Chris Lattner95933c12009-04-24 00:30:45 +00001815
1816 // Diagnose bad cases where we step over interface counts.
1817 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1818 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1819 << ResultType << BaseExpr->getSourceRange();
1820 return ExprError();
1821 }
1822
Sebastian Redl8b769972009-01-19 00:08:26 +00001823 Base.release();
1824 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001825 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001826 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001827}
1828
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001829QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001830CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001831 const IdentifierInfo *CompName,
1832 SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001833 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001834
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001835 // The vector accessor can't exceed the number of elements.
Anders Carlsson9935ab92009-08-26 18:25:21 +00001836 const char *compStr = CompName->getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001837
Mike Stump9afab102009-02-19 03:04:26 +00001838 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001839 // special names that indicate a subset of exactly half the elements are
1840 // to be selected.
1841 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001842
Nate Begeman1486b502009-01-18 01:47:54 +00001843 // This flag determines whether or not CompName has an 's' char prefix,
1844 // indicating that it is a string of hex values to be used as vector indices.
Nate Begemane2ed6f72009-06-25 21:06:09 +00001845 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001846
1847 // Check that we've found one of the special components, or that the component
1848 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001849 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001850 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1851 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001852 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001853 do
1854 compStr++;
1855 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001856 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001857 do
1858 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001859 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001860 }
Nate Begeman1486b502009-01-18 01:47:54 +00001861
Mike Stump9afab102009-02-19 03:04:26 +00001862 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001863 // We didn't get to the end of the string. This means the component names
1864 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001865 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1866 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001867 return QualType();
1868 }
Mike Stump9afab102009-02-19 03:04:26 +00001869
Nate Begeman1486b502009-01-18 01:47:54 +00001870 // Ensure no component accessor exceeds the width of the vector type it
1871 // operates on.
1872 if (!HalvingSwizzle) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00001873 compStr = CompName->getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001874
1875 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001876 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001877
1878 while (*compStr) {
1879 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1880 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1881 << baseType << SourceRange(CompLoc);
1882 return QualType();
1883 }
1884 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001885 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001886
Nate Begeman1486b502009-01-18 01:47:54 +00001887 // If this is a halving swizzle, verify that the base type has an even
1888 // number of elements.
1889 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001890 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001891 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001892 return QualType();
1893 }
Mike Stump9afab102009-02-19 03:04:26 +00001894
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001895 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001896 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001897 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001898 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001899 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001900 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlsson9935ab92009-08-26 18:25:21 +00001901 : CompName->getLength();
Nate Begeman1486b502009-01-18 01:47:54 +00001902 if (HexSwizzle)
1903 CompSize--;
1904
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001905 if (CompSize == 1)
1906 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001907
Nate Begemanaf6ed502008-04-18 23:10:10 +00001908 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001909 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001910 // diagostics look bad. We want extended vector types to appear built-in.
1911 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1912 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1913 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001914 }
1915 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001916}
1917
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001918static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001919 IdentifierInfo *Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001920 const Selector &Sel,
1921 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001922
Anders Carlsson9935ab92009-08-26 18:25:21 +00001923 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001924 return PD;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001925 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001926 return OMD;
1927
1928 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1929 E = PDecl->protocol_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001930 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
1931 Context))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001932 return D;
1933 }
1934 return 0;
1935}
1936
Steve Naroffc75c1a82009-06-17 22:40:22 +00001937static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001938 IdentifierInfo *Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001939 const Selector &Sel,
1940 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001941 // Check protocols on qualified interfaces.
1942 Decl *GDecl = 0;
Steve Naroffc75c1a82009-06-17 22:40:22 +00001943 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001944 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00001945 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001946 GDecl = PD;
1947 break;
1948 }
1949 // Also must look for a getter name which uses property syntax.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001950 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001951 GDecl = OMD;
1952 break;
1953 }
1954 }
1955 if (!GDecl) {
Steve Naroffc75c1a82009-06-17 22:40:22 +00001956 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001957 E = QIdTy->qual_end(); I != E; ++I) {
1958 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001959 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001960 if (GDecl)
1961 return GDecl;
1962 }
1963 }
1964 return GDecl;
1965}
Chris Lattner2cb744b2009-02-15 22:43:40 +00001966
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001967/// FindMethodInNestedImplementations - Look up a method in current and
1968/// all base class implementations.
1969///
1970ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
1971 const ObjCInterfaceDecl *IFace,
1972 const Selector &Sel) {
1973 ObjCMethodDecl *Method = 0;
Argiris Kirtzidisb1c4ee52009-07-21 00:06:04 +00001974 if (ObjCImplementationDecl *ImpDecl = IFace->getImplementation())
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001975 Method = ImpDecl->getInstanceMethod(Sel);
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001976
1977 if (!Method && IFace->getSuperClass())
1978 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
1979 return Method;
1980}
Douglas Gregore399ad42009-08-26 22:36:53 +00001981
Anders Carlsson9935ab92009-08-26 18:25:21 +00001982Action::OwningExprResult
1983Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
Sebastian Redl8b769972009-01-19 00:08:26 +00001984 tok::TokenKind OpKind, SourceLocation MemberLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00001985 DeclarationName MemberName,
Douglas Gregord33e3282009-09-01 00:37:14 +00001986 bool HasExplicitTemplateArgs,
1987 SourceLocation LAngleLoc,
1988 const TemplateArgument *ExplicitTemplateArgs,
1989 unsigned NumExplicitTemplateArgs,
1990 SourceLocation RAngleLoc,
Douglas Gregorda61ad22009-08-06 03:17:00 +00001991 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
Douglas Gregorda61ad22009-08-06 03:17:00 +00001992 if (SS && SS->isInvalid())
1993 return ExprError();
1994
Nate Begemane85f43d2009-08-10 23:49:36 +00001995 // Since this might be a postfix expression, get rid of ParenListExprs.
1996 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1997
Anders Carlssonc154a722009-05-01 19:30:39 +00001998 Expr *BaseExpr = Base.takeAs<Expr>();
Steve Naroff2cb66382007-07-26 03:11:44 +00001999 assert(BaseExpr && "no record expression");
Nate Begemane85f43d2009-08-10 23:49:36 +00002000
Steve Naroff137e11d2007-12-16 21:42:28 +00002001 // Perform default conversions.
2002 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00002003
Steve Naroff2cb66382007-07-26 03:11:44 +00002004 QualType BaseType = BaseExpr->getType();
David Chisnall44663db2009-08-17 16:35:33 +00002005 // If this is an Objective-C pseudo-builtin and a definition is provided then
2006 // use that.
2007 if (BaseType->isObjCIdType()) {
2008 // We have an 'id' type. Rather than fall through, we check if this
2009 // is a reference to 'isa'.
2010 if (BaseType != Context.ObjCIdRedefinitionType) {
2011 BaseType = Context.ObjCIdRedefinitionType;
2012 ImpCastExprToType(BaseExpr, BaseType);
2013 }
2014 } else if (BaseType->isObjCClassType() &&
Douglas Gregorcfa0a632009-08-31 21:16:32 +00002015 BaseType != Context.ObjCClassRedefinitionType) {
David Chisnall44663db2009-08-17 16:35:33 +00002016 BaseType = Context.ObjCClassRedefinitionType;
2017 ImpCastExprToType(BaseExpr, BaseType);
2018 }
Steve Naroff2cb66382007-07-26 03:11:44 +00002019 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00002020
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002021 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2022 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00002023 if (OpKind == tok::arrow) {
Anders Carlsson72d3c662009-05-15 23:10:19 +00002024 if (BaseType->isDependentType())
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002025 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2026 BaseExpr, true,
2027 OpLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00002028 MemberName,
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002029 MemberLoc));
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002030 else if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff2cb66382007-07-26 03:11:44 +00002031 BaseType = PT->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00002032 else if (BaseType->isObjCObjectPointerType())
2033 ;
Steve Naroff2cb66382007-07-26 03:11:44 +00002034 else
Sebastian Redl8b769972009-01-19 00:08:26 +00002035 return ExprError(Diag(MemberLoc,
2036 diag::err_typecheck_member_reference_arrow)
2037 << BaseType << BaseExpr->getSourceRange());
Anders Carlsson72d3c662009-05-15 23:10:19 +00002038 } else {
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002039 if (BaseType->isDependentType()) {
2040 // Require that the base type isn't a pointer type
2041 // (so we'll report an error for)
2042 // T* t;
2043 // t.f;
2044 //
2045 // In Obj-C++, however, the above expression is valid, since it could be
2046 // accessing the 'f' property if T is an Obj-C interface. The extra check
2047 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002048 const PointerType *PT = BaseType->getAs<PointerType>();
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002049
2050 if (!PT || (getLangOptions().ObjC1 &&
2051 !PT->getPointeeType()->isRecordType()))
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002052 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2053 BaseExpr, false,
2054 OpLoc,
Anders Carlsson9935ab92009-08-26 18:25:21 +00002055 MemberName,
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002056 MemberLoc));
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002057 }
Chris Lattner4b009652007-07-25 00:24:17 +00002058 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002059
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002060 // Handle field access to simple records. This also handles access to fields
2061 // of the ObjC 'id' struct.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002062 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00002063 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorc84d8932009-03-09 16:13:40 +00002064 if (RequireCompleteType(OpLoc, BaseType,
Anders Carlssona21e7872009-08-26 23:45:07 +00002065 PDiag(diag::err_typecheck_incomplete_tag)
2066 << BaseExpr->getSourceRange()))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002067 return ExprError();
2068
Douglas Gregorda61ad22009-08-06 03:17:00 +00002069 DeclContext *DC = RDecl;
2070 if (SS && SS->isSet()) {
2071 // If the member name was a qualified-id, look into the
2072 // nested-name-specifier.
2073 DC = computeDeclContext(*SS, false);
2074
2075 // FIXME: If DC is not computable, we should build a
2076 // CXXUnresolvedMemberExpr.
2077 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2078 }
2079
Steve Naroff2cb66382007-07-26 03:11:44 +00002080 // The record definition is complete, now make sure the member is valid.
Sebastian Redl8b769972009-01-19 00:08:26 +00002081 LookupResult Result
Anders Carlsson9935ab92009-08-26 18:25:21 +00002082 = LookupQualifiedName(DC, MemberName, LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002083
Douglas Gregor12431cb2009-08-06 05:28:30 +00002084 if (SS && SS->isSet()) {
Douglas Gregorda61ad22009-08-06 03:17:00 +00002085 QualType BaseTypeCanon
2086 = Context.getCanonicalType(BaseType).getUnqualifiedType();
2087 QualType MemberTypeCanon
2088 = Context.getCanonicalType(
2089 Context.getTypeDeclType(
2090 dyn_cast<TypeDecl>(Result.getAsDecl()->getDeclContext())));
2091
2092 if (BaseTypeCanon != MemberTypeCanon &&
2093 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2094 return ExprError(Diag(SS->getBeginLoc(),
2095 diag::err_not_direct_base_or_virtual)
2096 << MemberTypeCanon << BaseTypeCanon);
2097 }
2098
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002099 if (!Result)
Anders Carlsson4355a392009-08-30 00:54:35 +00002100 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member_deprecated)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002101 << MemberName << BaseExpr->getSourceRange());
Chris Lattner84ad8332009-03-31 08:18:48 +00002102 if (Result.isAmbiguous()) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002103 DiagnoseAmbiguousLookup(Result, MemberName, MemberLoc,
2104 BaseExpr->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00002105 return ExprError();
Chris Lattner84ad8332009-03-31 08:18:48 +00002106 }
2107
2108 NamedDecl *MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002109
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002110 // If the decl being referenced had an error, return an error for this
2111 // sub-expr without emitting another error, in order to avoid cascading
2112 // error cases.
2113 if (MemberDecl->isInvalidDecl())
2114 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002115
Douglas Gregoraa57e862009-02-18 21:56:37 +00002116 // Check the use of this field
2117 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2118 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002119
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002120 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00002121 // We may have found a field within an anonymous union or struct
2122 // (C++ [class.union]).
2123 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00002124 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00002125 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00002126
Douglas Gregor82d44772008-12-20 23:49:58 +00002127 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002128 QualType MemberType = FD->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002129 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
Douglas Gregor82d44772008-12-20 23:49:58 +00002130 MemberType = Ref->getPointeeType();
2131 else {
Mon P Wang04d89cb2009-07-22 03:08:17 +00002132 unsigned BaseAddrSpace = BaseType.getAddressSpace();
Douglas Gregor82d44772008-12-20 23:49:58 +00002133 unsigned combinedQualifiers =
2134 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002135 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00002136 combinedQualifiers &= ~QualType::Const;
2137 MemberType = MemberType.getQualifiedType(combinedQualifiers);
Mon P Wang04d89cb2009-07-22 03:08:17 +00002138 if (BaseAddrSpace != MemberType.getAddressSpace())
2139 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor82d44772008-12-20 23:49:58 +00002140 }
Eli Friedman76b49832008-02-06 22:48:16 +00002141
Douglas Gregorcad27f62009-06-22 23:06:13 +00002142 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanian843336e2009-07-29 19:40:11 +00002143 if (PerformObjectMemberConversion(BaseExpr, FD))
2144 return ExprError();
Douglas Gregore399ad42009-08-26 22:36:53 +00002145 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2146 FD, MemberLoc, MemberType));
Chris Lattner84ad8332009-03-31 08:18:48 +00002147 }
2148
Douglas Gregorcad27f62009-06-22 23:06:13 +00002149 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2150 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002151 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2152 Var, MemberLoc,
2153 Var->getType().getNonReferenceType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002154 }
2155 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2156 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002157 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2158 MemberFn, MemberLoc,
2159 MemberFn->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002160 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002161 if (FunctionTemplateDecl *FunTmpl
2162 = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2163 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregord33e3282009-09-01 00:37:14 +00002164
2165 if (HasExplicitTemplateArgs)
2166 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2167 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
2168 SS? SS->getRange() : SourceRange(),
2169 FunTmpl, MemberLoc, true,
2170 LAngleLoc, ExplicitTemplateArgs,
2171 NumExplicitTemplateArgs, RAngleLoc,
2172 Context.OverloadTy));
2173
Douglas Gregore399ad42009-08-26 22:36:53 +00002174 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2175 FunTmpl, MemberLoc,
2176 Context.OverloadTy));
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002177 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002178 if (OverloadedFunctionDecl *Ovl
Douglas Gregord33e3282009-09-01 00:37:14 +00002179 = dyn_cast<OverloadedFunctionDecl>(MemberDecl)) {
2180 if (HasExplicitTemplateArgs)
2181 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2182 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
2183 SS? SS->getRange() : SourceRange(),
2184 Ovl, MemberLoc, true,
2185 LAngleLoc, ExplicitTemplateArgs,
2186 NumExplicitTemplateArgs, RAngleLoc,
2187 Context.OverloadTy));
2188
Douglas Gregore399ad42009-08-26 22:36:53 +00002189 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2190 Ovl, MemberLoc, Context.OverloadTy));
Douglas Gregord33e3282009-09-01 00:37:14 +00002191 }
Douglas Gregorcad27f62009-06-22 23:06:13 +00002192 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2193 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregore399ad42009-08-26 22:36:53 +00002194 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2195 Enum, MemberLoc, Enum->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002196 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002197 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00002198 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002199 << MemberName << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00002200
Douglas Gregor82d44772008-12-20 23:49:58 +00002201 // We found a declaration kind that we didn't expect. This is a
2202 // generic error message that tells the user that she can't refer
2203 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00002204 return ExprError(Diag(MemberLoc,
2205 diag::err_typecheck_member_reference_unknown)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002206 << MemberName << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00002207 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002208
Steve Naroff329ec222009-07-10 23:34:53 +00002209 // Handle properties on ObjC 'Class' types.
Steve Naroff7982a642009-07-13 17:19:15 +00002210 if (OpKind == tok::period && BaseType->isObjCClassType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00002211 // Also must look for a getter name which uses property syntax.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002212 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2213 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002214 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2215 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2216 ObjCMethodDecl *Getter;
2217 // FIXME: need to also look locally in the implementation.
2218 if ((Getter = IFace->lookupClassMethod(Sel))) {
2219 // Check the use of this method.
2220 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2221 return ExprError();
2222 }
2223 // If we found a getter then this may be a valid dot-reference, we
2224 // will look for the matching setter, in case it is needed.
2225 Selector SetterSel =
2226 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson9935ab92009-08-26 18:25:21 +00002227 PP.getSelectorTable(), Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002228 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2229 if (!Setter) {
2230 // If this reference is in an @implementation, also check for 'private'
2231 // methods.
2232 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
2233 }
2234 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002235 if (!Setter)
2236 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff329ec222009-07-10 23:34:53 +00002237
2238 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2239 return ExprError();
2240
2241 if (Getter || Setter) {
2242 QualType PType;
2243
2244 if (Getter)
2245 PType = Getter->getResultType();
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002246 else
2247 // Get the expression type from Setter's incoming parameter.
2248 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00002249 // FIXME: we must check that the setter has property type.
Fariborz Jahanian128cdc52009-08-20 17:02:02 +00002250 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff329ec222009-07-10 23:34:53 +00002251 Setter, MemberLoc, BaseExpr));
2252 }
2253 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002254 << MemberName << BaseType);
Steve Naroff329ec222009-07-10 23:34:53 +00002255 }
2256 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002257 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2258 // (*Obj).ivar.
Steve Naroff329ec222009-07-10 23:34:53 +00002259 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2260 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
2261 const ObjCObjectPointerType *OPT = BaseType->getAsObjCObjectPointerType();
2262 const ObjCInterfaceType *IFaceT =
2263 OPT ? OPT->getInterfaceType() : BaseType->getAsObjCInterfaceType();
Steve Naroff4e743962009-07-16 00:25:06 +00002264 if (IFaceT) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002265 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2266
Steve Naroff4e743962009-07-16 00:25:06 +00002267 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2268 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson9935ab92009-08-26 18:25:21 +00002269 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Steve Naroff4e743962009-07-16 00:25:06 +00002270
2271 if (IV) {
2272 // If the decl being referenced had an error, return an error for this
2273 // sub-expr without emitting another error, in order to avoid cascading
2274 // error cases.
2275 if (IV->isInvalidDecl())
2276 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00002277
Steve Naroff4e743962009-07-16 00:25:06 +00002278 // Check whether we can reference this field.
2279 if (DiagnoseUseOfDecl(IV, MemberLoc))
2280 return ExprError();
2281 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2282 IV->getAccessControl() != ObjCIvarDecl::Package) {
2283 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2284 if (ObjCMethodDecl *MD = getCurMethodDecl())
2285 ClassOfMethodDecl = MD->getClassInterface();
2286 else if (ObjCImpDecl && getCurFunctionDecl()) {
2287 // Case of a c-function declared inside an objc implementation.
2288 // FIXME: For a c-style function nested inside an objc implementation
2289 // class, there is no implementation context available, so we pass
2290 // down the context as argument to this routine. Ideally, this context
2291 // need be passed down in the AST node and somehow calculated from the
2292 // AST for a function decl.
2293 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
2294 if (ObjCImplementationDecl *IMPD =
2295 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2296 ClassOfMethodDecl = IMPD->getClassInterface();
2297 else if (ObjCCategoryImplDecl* CatImplClass =
2298 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2299 ClassOfMethodDecl = CatImplClass->getClassInterface();
2300 }
2301
2302 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2303 if (ClassDeclared != IDecl ||
2304 ClassOfMethodDecl != ClassDeclared)
2305 Diag(MemberLoc, diag::error_private_ivar_access)
2306 << IV->getDeclName();
Mike Stump90fc78e2009-08-04 21:02:39 +00002307 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2308 // @protected
Steve Naroff4e743962009-07-16 00:25:06 +00002309 Diag(MemberLoc, diag::error_protected_ivar_access)
2310 << IV->getDeclName();
Steve Narofff9606572009-03-04 18:34:24 +00002311 }
Steve Naroff4e743962009-07-16 00:25:06 +00002312
2313 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2314 MemberLoc, BaseExpr,
2315 OpKind == tok::arrow));
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002316 }
Steve Naroff4e743962009-07-16 00:25:06 +00002317 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002318 << IDecl->getDeclName() << MemberName
Steve Naroff4e743962009-07-16 00:25:06 +00002319 << BaseExpr->getSourceRange());
Fariborz Jahanian09772392008-12-13 22:20:28 +00002320 }
Chris Lattnera57cf472008-07-21 04:28:12 +00002321 }
Steve Naroff7bffd372009-07-15 18:40:39 +00002322 // Handle properties on 'id' and qualified "id".
2323 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
2324 BaseType->isObjCQualifiedIdType())) {
2325 const ObjCObjectPointerType *QIdTy = BaseType->getAsObjCObjectPointerType();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002326 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Steve Naroff7bffd372009-07-15 18:40:39 +00002327
Steve Naroff329ec222009-07-10 23:34:53 +00002328 // Check protocols on qualified interfaces.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002329 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff329ec222009-07-10 23:34:53 +00002330 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2331 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2332 // Check the use of this declaration
2333 if (DiagnoseUseOfDecl(PD, MemberLoc))
2334 return ExprError();
2335
2336 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2337 MemberLoc, BaseExpr));
2338 }
2339 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2340 // Check the use of this method.
2341 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2342 return ExprError();
2343
2344 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
2345 OMD->getResultType(),
2346 OMD, OpLoc, MemberLoc,
2347 NULL, 0));
2348 }
2349 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002350
Steve Naroff329ec222009-07-10 23:34:53 +00002351 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002352 << MemberName << BaseType);
Steve Naroff329ec222009-07-10 23:34:53 +00002353 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002354 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2355 // pointer to a (potentially qualified) interface type.
Steve Naroff329ec222009-07-10 23:34:53 +00002356 const ObjCObjectPointerType *OPT;
2357 if (OpKind == tok::period &&
2358 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2359 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2360 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002361 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Steve Naroff329ec222009-07-10 23:34:53 +00002362
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002363 // Search for a declared property first.
Anders Carlsson9935ab92009-08-26 18:25:21 +00002364 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002365 // Check whether we can reference this property.
2366 if (DiagnoseUseOfDecl(PD, MemberLoc))
2367 return ExprError();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002368 QualType ResTy = PD->getType();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002369 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002370 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian80ccaa92009-05-08 20:20:55 +00002371 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2372 ResTy = Getter->getResultType();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002373 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner51f6fb32009-02-16 18:35:08 +00002374 MemberLoc, BaseExpr));
2375 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002376 // Check protocols on qualified interfaces.
Steve Naroff8194a542009-07-20 17:56:53 +00002377 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2378 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002379 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002380 // Check whether we can reference this property.
2381 if (DiagnoseUseOfDecl(PD, MemberLoc))
2382 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00002383
Steve Naroff774e4152009-01-21 00:14:39 +00002384 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002385 MemberLoc, BaseExpr));
2386 }
Steve Naroff329ec222009-07-10 23:34:53 +00002387 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2388 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002389 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Steve Naroff329ec222009-07-10 23:34:53 +00002390 // Check whether we can reference this property.
2391 if (DiagnoseUseOfDecl(PD, MemberLoc))
2392 return ExprError();
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002393
Steve Naroff329ec222009-07-10 23:34:53 +00002394 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2395 MemberLoc, BaseExpr));
2396 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002397 // If that failed, look for an "implicit" property by seeing if the nullary
2398 // selector is implemented.
2399
2400 // FIXME: The logic for looking up nullary and unary selectors should be
2401 // shared with the code in ActOnInstanceMessage.
2402
Anders Carlsson9935ab92009-08-26 18:25:21 +00002403 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002404 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002405
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002406 // If this reference is in an @implementation, check for 'private' methods.
2407 if (!Getter)
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002408 Getter = FindMethodInNestedImplementations(IFace, Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002409
Steve Naroff04151f32008-10-22 19:16:27 +00002410 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002411 if (!Getter)
2412 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002413 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002414 // Check if we can reference this property.
2415 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2416 return ExprError();
Steve Naroffdede0c92009-03-11 13:48:17 +00002417 }
2418 // If we found a getter then this may be a valid dot-reference, we
2419 // will look for the matching setter, in case it is needed.
2420 Selector SetterSel =
2421 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson9935ab92009-08-26 18:25:21 +00002422 PP.getSelectorTable(), Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002423 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002424 if (!Setter) {
2425 // If this reference is in an @implementation, also check for 'private'
2426 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002427 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002428 }
2429 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002430 if (!Setter)
2431 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002432
Steve Naroffdede0c92009-03-11 13:48:17 +00002433 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2434 return ExprError();
2435
2436 if (Getter || Setter) {
2437 QualType PType;
2438
2439 if (Getter)
2440 PType = Getter->getResultType();
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002441 else
2442 // Get the expression type from Setter's incoming parameter.
2443 PType = (*(Setter->param_end() -1))->getType();
Steve Naroffdede0c92009-03-11 13:48:17 +00002444 // FIXME: we must check that the setter has property type.
Fariborz Jahanian128cdc52009-08-20 17:02:02 +00002445 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroffdede0c92009-03-11 13:48:17 +00002446 Setter, MemberLoc, BaseExpr));
2447 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002448 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson9935ab92009-08-26 18:25:21 +00002449 << MemberName << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00002450 }
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002451
Steve Naroff29d293b2009-07-24 17:54:45 +00002452 // Handle the following exceptional case (*Obj).isa.
2453 if (OpKind == tok::period &&
2454 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson9935ab92009-08-26 18:25:21 +00002455 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroff29d293b2009-07-24 17:54:45 +00002456 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2457 Context.getObjCIdType()));
2458
Chris Lattnera57cf472008-07-21 04:28:12 +00002459 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00002460 if (BaseType->isExtVectorType()) {
Anders Carlsson9935ab92009-08-26 18:25:21 +00002461 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnera57cf472008-07-21 04:28:12 +00002462 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2463 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00002464 return ExprError();
Anders Carlsson9935ab92009-08-26 18:25:21 +00002465 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff774e4152009-01-21 00:14:39 +00002466 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00002467 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002468
Douglas Gregor762da552009-03-27 06:00:30 +00002469 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2470 << BaseType << BaseExpr->getSourceRange();
2471
2472 // If the user is trying to apply -> or . to a function or function
2473 // pointer, it's probably because they forgot parentheses to call
2474 // the function. Suggest the addition of those parentheses.
2475 if (BaseType == Context.OverloadTy ||
2476 BaseType->isFunctionType() ||
2477 (BaseType->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002478 BaseType->getAs<PointerType>()->isFunctionType())) {
Douglas Gregor762da552009-03-27 06:00:30 +00002479 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2480 Diag(Loc, diag::note_member_reference_needs_call)
2481 << CodeModificationHint::CreateInsertion(Loc, "()");
2482 }
2483
2484 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00002485}
2486
Anders Carlsson9935ab92009-08-26 18:25:21 +00002487Action::OwningExprResult
2488Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2489 tok::TokenKind OpKind, SourceLocation MemberLoc,
2490 IdentifierInfo &Member,
2491 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
2492 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, MemberLoc,
2493 DeclarationName(&Member), ObjCImpDecl, SS);
2494}
2495
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002496Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2497 FunctionDecl *FD,
2498 ParmVarDecl *Param) {
2499 if (Param->hasUnparsedDefaultArg()) {
2500 Diag (CallLoc,
2501 diag::err_use_of_default_argument_to_function_declared_later) <<
2502 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
2503 Diag(UnparsedDefaultArgLocs[Param],
2504 diag::note_default_argument_declared_here);
2505 } else {
2506 if (Param->hasUninstantiatedDefaultArg()) {
2507 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2508
2509 // Instantiate the expression.
Douglas Gregor8dbd0382009-08-28 20:31:08 +00002510 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002511
2512 // FIXME: We should really make a new InstantiatingTemplate ctor
2513 // that has a better message - right now we're just piggy-backing
2514 // off the "default template argument" error message.
2515 InstantiatingTemplate Inst(*this, CallLoc, FD->getPrimaryTemplate(),
Douglas Gregor8dbd0382009-08-28 20:31:08 +00002516 ArgList.getInnermost().getFlatArgumentList(),
2517 ArgList.getInnermost().flat_size());
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002518
John McCall0ba26ee2009-08-25 22:02:44 +00002519 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002520 if (Result.isInvalid())
2521 return ExprError();
2522
2523 if (SetParamDefaultArgument(Param, move(Result),
2524 /*FIXME:EqualLoc*/
2525 UninstExpr->getSourceRange().getBegin()))
2526 return ExprError();
2527 }
2528
2529 Expr *DefaultExpr = Param->getDefaultArg();
2530
2531 // If the default expression creates temporaries, we need to
2532 // push them to the current stack of expression temporaries so they'll
2533 // be properly destroyed.
2534 if (CXXExprWithTemporaries *E
2535 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
2536 assert(!E->shouldDestroyTemporaries() &&
2537 "Can't destroy temporaries in a default argument expr!");
2538 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2539 ExprTemporaries.push_back(E->getTemporary(I));
2540 }
2541 }
2542
2543 // We already type-checked the argument, so we know it works.
2544 return Owned(CXXDefaultArgExpr::Create(Context, Param));
2545}
2546
Douglas Gregor3257fb52008-12-22 05:46:06 +00002547/// ConvertArgumentsForCall - Converts the arguments specified in
2548/// Args/NumArgs to the parameter types of the function FDecl with
2549/// function prototype Proto. Call is the call expression itself, and
2550/// Fn is the function expression. For a C++ member function, this
2551/// routine does not attempt to convert the object argument. Returns
2552/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00002553bool
2554Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002555 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002556 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002557 Expr **Args, unsigned NumArgs,
2558 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00002559 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00002560 // assignment, to the types of the corresponding parameter, ...
2561 unsigned NumArgsInProto = Proto->getNumArgs();
2562 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002563 bool Invalid = false;
2564
Douglas Gregor3257fb52008-12-22 05:46:06 +00002565 // If too few arguments are available (and we don't have default
2566 // arguments for the remaining parameters), don't make the call.
2567 if (NumArgs < NumArgsInProto) {
2568 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2569 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2570 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2571 // Use default arguments for missing arguments
2572 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00002573 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002574 }
2575
2576 // If too many are passed and not variadic, error on the extras and drop
2577 // them.
2578 if (NumArgs > NumArgsInProto) {
2579 if (!Proto->isVariadic()) {
2580 Diag(Args[NumArgsInProto]->getLocStart(),
2581 diag::err_typecheck_call_too_many_args)
2582 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2583 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2584 Args[NumArgs-1]->getLocEnd());
2585 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002586 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002587 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002588 }
2589 NumArgsToCheck = NumArgsInProto;
2590 }
Mike Stump9afab102009-02-19 03:04:26 +00002591
Douglas Gregor3257fb52008-12-22 05:46:06 +00002592 // Continue to check argument types (even if we have too few/many args).
2593 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2594 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00002595
Douglas Gregor3257fb52008-12-22 05:46:06 +00002596 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002597 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002598 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002599
Eli Friedman83dec9e2009-03-22 22:00:50 +00002600 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2601 ProtoArgType,
Anders Carlssona21e7872009-08-26 23:45:07 +00002602 PDiag(diag::err_call_incomplete_argument)
2603 << Arg->getSourceRange()))
Eli Friedman83dec9e2009-03-22 22:00:50 +00002604 return true;
2605
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002606 // Pass the argument.
2607 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2608 return true;
Anders Carlssona116e6e2009-06-12 16:51:40 +00002609 } else {
Anders Carlsson60eb3be2009-08-25 02:29:20 +00002610 ParmVarDecl *Param = FDecl->getParamDecl(i);
Anders Carlsson0ab9db22009-08-25 03:49:14 +00002611
2612 OwningExprResult ArgExpr =
2613 BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(),
2614 FDecl, Param);
2615 if (ArgExpr.isInvalid())
2616 return true;
2617
2618 Arg = ArgExpr.takeAs<Expr>();
Anders Carlssona116e6e2009-06-12 16:51:40 +00002619 }
2620
Douglas Gregor3257fb52008-12-22 05:46:06 +00002621 Call->setArg(i, Arg);
2622 }
Mike Stump9afab102009-02-19 03:04:26 +00002623
Douglas Gregor3257fb52008-12-22 05:46:06 +00002624 // If this is a variadic call, handle args passed through "...".
2625 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002626 VariadicCallType CallType = VariadicFunction;
2627 if (Fn->getType()->isBlockPointerType())
2628 CallType = VariadicBlock; // Block
2629 else if (isa<MemberExpr>(Fn))
2630 CallType = VariadicMethod;
2631
Douglas Gregor3257fb52008-12-22 05:46:06 +00002632 // Promote the arguments (C99 6.5.2.2p7).
2633 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2634 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00002635 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002636 Call->setArg(i, Arg);
2637 }
2638 }
2639
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002640 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002641}
2642
Steve Naroff87d58b42007-09-16 03:34:24 +00002643/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002644/// This provides the location of the left/right parens and a list of comma
2645/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002646Action::OwningExprResult
2647Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2648 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002649 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002650 unsigned NumArgs = args.size();
Nate Begemane85f43d2009-08-10 23:49:36 +00002651
2652 // Since this might be a postfix expression, get rid of ParenListExprs.
2653 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
2654
Anders Carlssonc154a722009-05-01 19:30:39 +00002655 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl8b769972009-01-19 00:08:26 +00002656 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002657 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002658 FunctionDecl *FDecl = NULL;
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002659 NamedDecl *NDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002660 DeclarationName UnqualifiedName;
Nate Begemane85f43d2009-08-10 23:49:36 +00002661
Douglas Gregor3257fb52008-12-22 05:46:06 +00002662 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002663 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002664 // in which case we won't do any semantic analysis now.
Mike Stumpe127ae32009-05-16 07:39:55 +00002665 // FIXME: Will need to cache the results of name lookup (including ADL) in
2666 // Fn.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002667 bool Dependent = false;
2668 if (Fn->isTypeDependent())
2669 Dependent = true;
2670 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2671 Dependent = true;
2672
2673 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002674 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002675 Context.DependentTy, RParenLoc));
2676
2677 // Determine whether this is a call to an object (C++ [over.call.object]).
2678 if (Fn->getType()->isRecordType())
2679 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2680 CommaLocs, RParenLoc));
2681
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002682 // Determine whether this is a call to a member function.
Douglas Gregorb60eb752009-06-25 22:08:12 +00002683 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2684 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2685 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2686 isa<CXXMethodDecl>(MemDecl) ||
2687 (isa<FunctionTemplateDecl>(MemDecl) &&
2688 isa<CXXMethodDecl>(
2689 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redl8b769972009-01-19 00:08:26 +00002690 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2691 CommaLocs, RParenLoc));
Douglas Gregorb60eb752009-06-25 22:08:12 +00002692 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00002693 }
2694
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002695 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002696 // Also, in C++, keep track of whether we should perform argument-dependent
2697 // lookup and whether there were any explicitly-specified template arguments.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002698 Expr *FnExpr = Fn;
2699 bool ADL = true;
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002700 bool HasExplicitTemplateArgs = 0;
2701 const TemplateArgument *ExplicitTemplateArgs = 0;
2702 unsigned NumExplicitTemplateArgs = 0;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002703 while (true) {
2704 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2705 FnExpr = IcExpr->getSubExpr();
2706 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002707 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002708 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002709 ADL = false;
2710 FnExpr = PExpr->getSubExpr();
2711 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002712 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002713 == UnaryOperator::AddrOf) {
2714 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor28857752009-06-30 22:34:41 +00002715 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002716 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2717 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
Douglas Gregor28857752009-06-30 22:34:41 +00002718 NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl());
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002719 break;
Mike Stump9afab102009-02-19 03:04:26 +00002720 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002721 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2722 UnqualifiedName = DepName->getName();
2723 break;
Douglas Gregor28857752009-06-30 22:34:41 +00002724 } else if (TemplateIdRefExpr *TemplateIdRef
2725 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2726 NDecl = TemplateIdRef->getTemplateName().getAsTemplateDecl();
Douglas Gregor6631cb42009-07-29 18:26:50 +00002727 if (!NDecl)
2728 NDecl = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002729 HasExplicitTemplateArgs = true;
2730 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2731 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2732
2733 // C++ [temp.arg.explicit]p6:
2734 // [Note: For simple function names, argument dependent lookup (3.4.2)
2735 // applies even when the function name is not visible within the
2736 // scope of the call. This is because the call still has the syntactic
2737 // form of a function call (3.4.1). But when a function template with
2738 // explicit template arguments is used, the call does not have the
2739 // correct syntactic form unless there is a function template with
2740 // that name visible at the point of the call. If no such name is
2741 // visible, the call is not syntactically well-formed and
2742 // argument-dependent lookup does not apply. If some such name is
2743 // visible, argument dependent lookup applies and additional function
2744 // templates may be found in other namespaces.
2745 //
2746 // The summary of this paragraph is that, if we get to this point and the
2747 // template-id was not a qualified name, then argument-dependent lookup
2748 // is still possible.
2749 if (TemplateIdRef->getQualifier())
2750 ADL = false;
Douglas Gregor28857752009-06-30 22:34:41 +00002751 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002752 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002753 // Any kind of name that does not refer to a declaration (or
2754 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2755 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002756 break;
2757 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002758 }
Mike Stump9afab102009-02-19 03:04:26 +00002759
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002760 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregorb60eb752009-06-25 22:08:12 +00002761 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregor28857752009-06-30 22:34:41 +00002762 if (NDecl) {
2763 FDecl = dyn_cast<FunctionDecl>(NDecl);
2764 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
Douglas Gregorb60eb752009-06-25 22:08:12 +00002765 FDecl = FunctionTemplate->getTemplatedDecl();
2766 else
Douglas Gregor28857752009-06-30 22:34:41 +00002767 FDecl = dyn_cast<FunctionDecl>(NDecl);
2768 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002769 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002770
Douglas Gregorb60eb752009-06-25 22:08:12 +00002771 if (Ovl || FunctionTemplate ||
2772 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002773 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002774 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002775 ADL = false;
2776
Douglas Gregorfcb19192009-02-11 23:02:49 +00002777 // We don't perform ADL in C.
2778 if (!getLangOptions().CPlusPlus)
2779 ADL = false;
2780
Douglas Gregorb60eb752009-06-25 22:08:12 +00002781 if (Ovl || FunctionTemplate || ADL) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002782 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
2783 HasExplicitTemplateArgs,
2784 ExplicitTemplateArgs,
2785 NumExplicitTemplateArgs,
2786 LParenLoc, Args, NumArgs, CommaLocs,
2787 RParenLoc, ADL);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002788 if (!FDecl)
2789 return ExprError();
2790
2791 // Update Fn to refer to the actual function selected.
2792 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002793 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor28857752009-06-30 22:34:41 +00002794 = dyn_cast<QualifiedDeclRefExpr>(FnExpr))
Douglas Gregor1e589cc2009-03-26 23:50:42 +00002795 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2796 QDRExpr->getLocation(),
2797 false, false,
2798 QDRExpr->getQualifierRange(),
2799 QDRExpr->getQualifier());
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002800 else
Mike Stump9afab102009-02-19 03:04:26 +00002801 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002802 Fn->getSourceRange().getBegin());
2803 Fn->Destroy(Context);
2804 Fn = NewFn;
2805 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002806 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002807
2808 // Promote the function operand.
2809 UsualUnaryConversions(Fn);
2810
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002811 // Make the call expr early, before semantic checks. This guarantees cleanup
2812 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002813 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2814 Args, NumArgs,
2815 Context.BoolTy,
2816 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002817
Steve Naroffd6163f32008-09-05 22:11:13 +00002818 const FunctionType *FuncT;
2819 if (!Fn->getType()->isBlockPointerType()) {
2820 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2821 // have type pointer to function".
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002822 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffd6163f32008-09-05 22:11:13 +00002823 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002824 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2825 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002826 FuncT = PT->getPointeeType()->getAsFunctionType();
2827 } else { // This is a block call.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002828 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
Steve Naroffd6163f32008-09-05 22:11:13 +00002829 getAsFunctionType();
2830 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002831 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002832 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2833 << Fn->getType() << Fn->getSourceRange());
2834
Eli Friedman83dec9e2009-03-22 22:00:50 +00002835 // Check for a valid return type
2836 if (!FuncT->getResultType()->isVoidType() &&
2837 RequireCompleteType(Fn->getSourceRange().getBegin(),
2838 FuncT->getResultType(),
Anders Carlssona21e7872009-08-26 23:45:07 +00002839 PDiag(diag::err_call_incomplete_return)
2840 << TheCall->getSourceRange()))
Eli Friedman83dec9e2009-03-22 22:00:50 +00002841 return ExprError();
2842
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002843 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002844 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002845
Douglas Gregor4fa58902009-02-26 23:50:07 +00002846 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002847 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002848 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002849 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002850 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002851 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002852
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002853 if (FDecl) {
2854 // Check if we have too few/too many template arguments, based
2855 // on our knowledge of the function definition.
2856 const FunctionDecl *Def = 0;
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00002857 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanf7ed7812009-06-01 09:24:59 +00002858 const FunctionProtoType *Proto =
2859 Def->getType()->getAsFunctionProtoType();
2860 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2861 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2862 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2863 }
2864 }
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002865 }
2866
Steve Naroffdb65e052007-08-28 23:30:39 +00002867 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002868 for (unsigned i = 0; i != NumArgs; i++) {
2869 Expr *Arg = Args[i];
2870 DefaultArgumentPromotion(Arg);
Eli Friedman83dec9e2009-03-22 22:00:50 +00002871 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2872 Arg->getType(),
Anders Carlssona21e7872009-08-26 23:45:07 +00002873 PDiag(diag::err_call_incomplete_argument)
2874 << Arg->getSourceRange()))
Eli Friedman83dec9e2009-03-22 22:00:50 +00002875 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002876 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002877 }
Chris Lattner4b009652007-07-25 00:24:17 +00002878 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002879
Douglas Gregor3257fb52008-12-22 05:46:06 +00002880 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2881 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002882 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2883 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002884
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002885 // Check for sentinels
2886 if (NDecl)
2887 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Anders Carlsson7fb13802009-08-16 01:56:34 +00002888
Chris Lattner2e64c072007-08-10 20:18:51 +00002889 // Do special checking on direct calls to functions.
Anders Carlsson7fb13802009-08-16 01:56:34 +00002890 if (FDecl) {
2891 if (CheckFunctionCall(FDecl, TheCall.get()))
2892 return ExprError();
2893
2894 if (unsigned BuiltinID = FDecl->getBuiltinID(Context))
2895 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
2896 } else if (NDecl) {
2897 if (CheckBlockCall(NDecl, TheCall.get()))
2898 return ExprError();
2899 }
Chris Lattner2e64c072007-08-10 20:18:51 +00002900
Anders Carlsson54ad8a02009-08-16 03:06:32 +00002901 return MaybeBindToTemporary(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002902}
2903
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002904Action::OwningExprResult
2905Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2906 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002907 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00002908 //FIXME: Preserve type source info.
2909 QualType literalType = GetTypeFromParser(Ty);
Chris Lattner4b009652007-07-25 00:24:17 +00002910 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002911 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002912 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002913
Eli Friedman8c2173d2008-05-20 05:22:08 +00002914 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002915 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002916 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2917 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregored71c542009-05-21 23:48:18 +00002918 } else if (!literalType->isDependentType() &&
2919 RequireCompleteType(LParenLoc, literalType,
Anders Carlssona21e7872009-08-26 23:45:07 +00002920 PDiag(diag::err_typecheck_decl_incomplete_type)
2921 << SourceRange(LParenLoc,
2922 literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002923 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002924
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002925 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002926 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002927 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002928
Chris Lattnere5cb5862008-12-04 23:50:19 +00002929 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002930 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002931 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002932 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002933 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002934 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002935 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002936 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002937}
2938
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002939Action::OwningExprResult
2940Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002941 SourceLocation RBraceLoc) {
2942 unsigned NumInit = initlist.size();
2943 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002944
Steve Naroff0acc9c92007-09-15 18:49:24 +00002945 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002946 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002947
Mike Stump9afab102009-02-19 03:04:26 +00002948 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002949 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002950 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002951 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002952}
2953
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002954/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlc358b622009-07-29 13:50:23 +00002955bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00002956 CastExpr::CastKind& Kind,
2957 CXXMethodDecl *& ConversionDecl,
2958 bool FunctionalStyle) {
Sebastian Redl0e35d042009-07-25 15:41:38 +00002959 if (getLangOptions().CPlusPlus)
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00002960 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
2961 ConversionDecl);
Sebastian Redl0e35d042009-07-25 15:41:38 +00002962
Eli Friedman01e0f652009-08-15 19:02:19 +00002963 DefaultFunctionArrayConversion(castExpr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002964
2965 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2966 // type needs to be scalar.
2967 if (castType->isVoidType()) {
2968 // Cast to void allows any expr type.
2969 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002970 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2971 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2972 (castType->isStructureType() || castType->isUnionType())) {
2973 // GCC struct/union extension: allow cast to self.
Eli Friedman2b128322009-03-23 00:24:07 +00002974 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002975 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2976 << castType << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00002977 Kind = CastExpr::CK_NoOp;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002978 } else if (castType->isUnionType()) {
2979 // GCC cast to union extension
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002980 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002981 RecordDecl::field_iterator Field, FieldEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002982 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002983 Field != FieldEnd; ++Field) {
2984 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2985 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2986 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2987 << castExpr->getSourceRange();
2988 break;
2989 }
2990 }
2991 if (Field == FieldEnd)
2992 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2993 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00002994 Kind = CastExpr::CK_ToUnion;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002995 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002996 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002997 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002998 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002999 }
Mike Stump9afab102009-02-19 03:04:26 +00003000 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003001 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003002 return Diag(castExpr->getLocStart(),
3003 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003004 << castExpr->getType() << castExpr->getSourceRange();
Nate Begemanbd42e022009-06-26 00:50:28 +00003005 } else if (castType->isExtVectorType()) {
3006 if (CheckExtVectorCast(TyR, castType, castExpr->getType()))
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003007 return true;
3008 } else if (castType->isVectorType()) {
3009 if (CheckVectorCast(TyR, castType, castExpr->getType()))
3010 return true;
Nate Begemanbd42e022009-06-26 00:50:28 +00003011 } else if (castExpr->getType()->isVectorType()) {
3012 if (CheckVectorCast(TyR, castExpr->getType(), castType))
3013 return true;
Steve Naroffff6c8022009-03-04 15:11:40 +00003014 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroff49fd7ad2009-04-08 23:52:26 +00003015 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Eli Friedman970e56c2009-05-01 02:23:58 +00003016 } else if (!castType->isArithmeticType()) {
3017 QualType castExprType = castExpr->getType();
3018 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3019 return Diag(castExpr->getLocStart(),
3020 diag::err_cast_pointer_from_non_pointer_int)
3021 << castExprType << castExpr->getSourceRange();
3022 } else if (!castExpr->getType()->isArithmeticType()) {
3023 if (!castType->isIntegralType() && castType->isArithmeticType())
3024 return Diag(castExpr->getLocStart(),
3025 diag::err_cast_pointer_to_non_pointer_int)
3026 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003027 }
Fariborz Jahanian4862e872009-05-22 21:42:52 +00003028 if (isa<ObjCSelectorExpr>(castExpr))
3029 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003030 return false;
3031}
3032
Chris Lattnerd1f26b32007-12-20 00:44:32 +00003033bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003034 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00003035
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003036 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003037 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003038 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00003039 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003040 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00003041 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003042 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003043 } else
3044 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00003045 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003046 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00003047
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003048 return false;
3049}
3050
Nate Begemanbd42e022009-06-26 00:50:28 +00003051bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) {
3052 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
3053
Nate Begeman9e063702009-06-27 22:05:55 +00003054 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3055 // an ExtVectorType.
Nate Begemanbd42e022009-06-26 00:50:28 +00003056 if (SrcTy->isVectorType()) {
3057 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3058 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3059 << DestTy << SrcTy << R;
3060 return false;
3061 }
3062
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003063 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanbd42e022009-06-26 00:50:28 +00003064 // conversion will take place first from scalar to elt type, and then
3065 // splat from elt type to vector.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003066 if (SrcTy->isPointerType())
3067 return Diag(R.getBegin(),
3068 diag::err_invalid_conversion_between_vector_and_scalar)
3069 << DestTy << SrcTy << R;
Nate Begemanbd42e022009-06-26 00:50:28 +00003070 return false;
3071}
3072
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003073Action::OwningExprResult
Nate Begemane85f43d2009-08-10 23:49:36 +00003074Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003075 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlsson9583fa72009-08-07 22:21:05 +00003076 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3077
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003078 assert((Ty != 0) && (Op.get() != 0) &&
3079 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00003080
Nate Begemane85f43d2009-08-10 23:49:36 +00003081 Expr *castExpr = (Expr *)Op.get();
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00003082 //FIXME: Preserve type source info.
3083 QualType castType = GetTypeFromParser(Ty);
Nate Begemane85f43d2009-08-10 23:49:36 +00003084
3085 // If the Expr being casted is a ParenListExpr, handle it specially.
3086 if (isa<ParenListExpr>(castExpr))
3087 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00003088 CXXMethodDecl *ConversionDecl = 0;
Anders Carlsson9583fa72009-08-07 22:21:05 +00003089 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00003090 Kind, ConversionDecl))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003091 return ExprError();
Fariborz Jahanianec172132009-08-29 19:15:16 +00003092 if (ConversionDecl) {
3093 // encounterred a c-style cast requiring a conversion function.
3094 if (CXXConversionDecl *CD = dyn_cast<CXXConversionDecl>(ConversionDecl)) {
3095 castExpr =
3096 new (Context) CXXFunctionalCastExpr(castType.getNonReferenceType(),
3097 castType, LParenLoc,
3098 CastExpr::CK_UserDefinedConversion,
3099 castExpr, CD,
3100 RParenLoc);
3101 Kind = CastExpr::CK_UserDefinedConversion;
3102 }
3103 // FIXME. AST for when dealing with conversion functions (FunctionDecl).
3104 }
Nate Begemane85f43d2009-08-10 23:49:36 +00003105
3106 Op.release();
Sebastian Redl0e35d042009-07-25 15:41:38 +00003107 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Anders Carlsson9583fa72009-08-07 22:21:05 +00003108 Kind, castExpr, castType,
3109 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00003110}
3111
Nate Begemane85f43d2009-08-10 23:49:36 +00003112/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3113/// of comma binary operators.
3114Action::OwningExprResult
3115Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3116 Expr *expr = EA.takeAs<Expr>();
3117 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3118 if (!E)
3119 return Owned(expr);
3120
3121 OwningExprResult Result(*this, E->getExpr(0));
3122
3123 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3124 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3125 Owned(E->getExpr(i)));
3126
3127 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3128}
3129
3130Action::OwningExprResult
3131Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3132 SourceLocation RParenLoc, ExprArg Op,
3133 QualType Ty) {
3134 ParenListExpr *PE = (ParenListExpr *)Op.get();
3135
3136 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
3137 // then handle it as such.
3138 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3139 if (PE->getNumExprs() == 0) {
3140 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3141 return ExprError();
3142 }
3143
3144 llvm::SmallVector<Expr *, 8> initExprs;
3145 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3146 initExprs.push_back(PE->getExpr(i));
3147
3148 // FIXME: This means that pretty-printing the final AST will produce curly
3149 // braces instead of the original commas.
3150 Op.release();
3151 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
3152 initExprs.size(), RParenLoc);
3153 E->setType(Ty);
3154 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
3155 Owned(E));
3156 } else {
3157 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
3158 // sequence of BinOp comma operators.
3159 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3160 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3161 }
3162}
3163
3164Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3165 SourceLocation R,
3166 MultiExprArg Val) {
3167 unsigned nexprs = Val.size();
3168 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3169 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3170 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3171 return Owned(expr);
3172}
3173
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003174/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3175/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00003176/// C99 6.5.15
3177QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3178 SourceLocation QuestionLoc) {
Sebastian Redlbd261962009-04-16 17:51:27 +00003179 // C++ is sufficiently different to merit its own checker.
3180 if (getLangOptions().CPlusPlus)
3181 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3182
Chris Lattnere2897262009-02-18 04:28:32 +00003183 UsualUnaryConversions(Cond);
3184 UsualUnaryConversions(LHS);
3185 UsualUnaryConversions(RHS);
3186 QualType CondTy = Cond->getType();
3187 QualType LHSTy = LHS->getType();
3188 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003189
3190 // first, check the condition.
Sebastian Redlbd261962009-04-16 17:51:27 +00003191 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3192 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3193 << CondTy;
3194 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003195 }
Mike Stump9afab102009-02-19 03:04:26 +00003196
Chris Lattner992ae932008-01-06 22:42:25 +00003197 // Now check the two expressions.
Nate Begemane85f43d2009-08-10 23:49:36 +00003198 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3199 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003200
Chris Lattner992ae932008-01-06 22:42:25 +00003201 // If both operands have arithmetic type, do the usual arithmetic conversions
3202 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00003203 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3204 UsualArithmeticConversions(LHS, RHS);
3205 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003206 }
Mike Stump9afab102009-02-19 03:04:26 +00003207
Chris Lattner992ae932008-01-06 22:42:25 +00003208 // If both operands are the same structure or union type, the result is that
3209 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003210 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3211 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner98a425c2007-11-26 01:40:58 +00003212 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003213 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00003214 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00003215 return LHSTy.getUnqualifiedType();
Eli Friedman2b128322009-03-23 00:24:07 +00003216 // FIXME: Type of conditional expression must be complete in C mode.
Chris Lattner4b009652007-07-25 00:24:17 +00003217 }
Mike Stump9afab102009-02-19 03:04:26 +00003218
Chris Lattner992ae932008-01-06 22:42:25 +00003219 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00003220 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00003221 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3222 if (!LHSTy->isVoidType())
3223 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3224 << RHS->getSourceRange();
3225 if (!RHSTy->isVoidType())
3226 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3227 << LHS->getSourceRange();
3228 ImpCastExprToType(LHS, Context.VoidTy);
3229 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00003230 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00003231 }
Steve Naroff12ebf272008-01-08 01:11:38 +00003232 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3233 // the type of the other operand."
Steve Naroff79ae19a2009-07-14 18:25:06 +00003234 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003235 RHS->isNullPointerConstant(Context)) {
3236 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
3237 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003238 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00003239 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003240 LHS->isNullPointerConstant(Context)) {
3241 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
3242 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003243 }
David Chisnall44663db2009-08-17 16:35:33 +00003244 // Handle things like Class and struct objc_class*. Here we case the result
3245 // to the pseudo-builtin, because that will be implicitly cast back to the
3246 // redefinition type if an attempt is made to access its fields.
3247 if (LHSTy->isObjCClassType() &&
3248 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3249 ImpCastExprToType(RHS, LHSTy);
3250 return LHSTy;
3251 }
3252 if (RHSTy->isObjCClassType() &&
3253 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3254 ImpCastExprToType(LHS, RHSTy);
3255 return RHSTy;
3256 }
3257 // And the same for struct objc_object* / id
3258 if (LHSTy->isObjCIdType() &&
3259 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3260 ImpCastExprToType(RHS, LHSTy);
3261 return LHSTy;
3262 }
3263 if (RHSTy->isObjCIdType() &&
3264 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3265 ImpCastExprToType(LHS, RHSTy);
3266 return RHSTy;
3267 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003268 // Handle block pointer types.
3269 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3270 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3271 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3272 QualType destType = Context.getPointerType(Context.VoidTy);
3273 ImpCastExprToType(LHS, destType);
3274 ImpCastExprToType(RHS, destType);
3275 return destType;
3276 }
3277 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3278 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3279 return QualType();
Mike Stumpe97a8542009-05-07 03:14:14 +00003280 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003281 // We have 2 block pointer types.
3282 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3283 // Two identical block pointer types are always compatible.
Mike Stumpe97a8542009-05-07 03:14:14 +00003284 return LHSTy;
3285 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003286 // The block pointer types aren't identical, continue checking.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003287 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3288 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003289
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003290 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3291 rhptee.getUnqualifiedType())) {
Mike Stumpe97a8542009-05-07 03:14:14 +00003292 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3293 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3294 // In this situation, we assume void* type. No especially good
3295 // reason, but this is what gcc does, and we do have to pick
3296 // to get a consistent AST.
3297 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3298 ImpCastExprToType(LHS, incompatTy);
3299 ImpCastExprToType(RHS, incompatTy);
3300 return incompatTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003301 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003302 // The block pointer types are compatible.
3303 ImpCastExprToType(LHS, LHSTy);
3304 ImpCastExprToType(RHS, LHSTy);
Steve Naroff6ba22682009-04-08 17:05:15 +00003305 return LHSTy;
3306 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003307 // Check constraints for Objective-C object pointers types.
Steve Naroff329ec222009-07-10 23:34:53 +00003308 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003309
3310 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3311 // Two identical object pointer types are always compatible.
3312 return LHSTy;
3313 }
Steve Naroff329ec222009-07-10 23:34:53 +00003314 const ObjCObjectPointerType *LHSOPT = LHSTy->getAsObjCObjectPointerType();
3315 const ObjCObjectPointerType *RHSOPT = RHSTy->getAsObjCObjectPointerType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003316 QualType compositeType = LHSTy;
3317
3318 // If both operands are interfaces and either operand can be
3319 // assigned to the other, use that type as the composite
3320 // type. This allows
3321 // xxx ? (A*) a : (B*) b
3322 // where B is a subclass of A.
3323 //
3324 // Additionally, as for assignment, if either type is 'id'
3325 // allow silent coercion. Finally, if the types are
3326 // incompatible then make sure to use 'id' as the composite
3327 // type so the result is acceptable for sending messages to.
3328
3329 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3330 // It could return the composite type.
Steve Naroff329ec222009-07-10 23:34:53 +00003331 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahanian2e006d22009-08-22 22:27:17 +00003332 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003333 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahanian2e006d22009-08-22 22:27:17 +00003334 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003335 } else if ((LHSTy->isObjCQualifiedIdType() ||
3336 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff99eb86b2009-07-23 01:01:38 +00003337 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Steve Naroff329ec222009-07-10 23:34:53 +00003338 // Need to handle "id<xx>" explicitly.
3339 // GCC allows qualified id and any Objective-C type to devolve to
3340 // id. Currently localizing to here until clear this should be
3341 // part of ObjCQualifiedIdTypesAreCompatible.
3342 compositeType = Context.getObjCIdType();
3343 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003344 compositeType = Context.getObjCIdType();
3345 } else {
3346 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3347 << LHSTy << RHSTy
3348 << LHS->getSourceRange() << RHS->getSourceRange();
3349 QualType incompatTy = Context.getObjCIdType();
3350 ImpCastExprToType(LHS, incompatTy);
3351 ImpCastExprToType(RHS, incompatTy);
3352 return incompatTy;
3353 }
3354 // The object pointer types are compatible.
3355 ImpCastExprToType(LHS, compositeType);
3356 ImpCastExprToType(RHS, compositeType);
3357 return compositeType;
3358 }
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003359 // Check Objective-C object pointer types and 'void *'
3360 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003361 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003362 QualType rhptee = RHSTy->getAsObjCObjectPointerType()->getPointeeType();
3363 QualType destPointee = lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3364 QualType destType = Context.getPointerType(destPointee);
3365 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3366 ImpCastExprToType(RHS, destType); // promote to void*
3367 return destType;
3368 }
3369 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
3370 QualType lhptee = LHSTy->getAsObjCObjectPointerType()->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003371 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003372 QualType destPointee = rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3373 QualType destType = Context.getPointerType(destPointee);
3374 ImpCastExprToType(RHS, destType); // add qualifiers if necessary
3375 ImpCastExprToType(LHS, destType); // promote to void*
3376 return destType;
3377 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003378 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3379 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3380 // get the "pointed to" types
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003381 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3382 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003383
3384 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3385 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3386 // Figure out necessary qualifiers (C99 6.5.15p6)
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 (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3394 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3395 QualType destType = Context.getPointerType(destPointee);
3396 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3397 ImpCastExprToType(RHS, destType); // promote to void*
3398 return destType;
3399 }
3400
3401 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3402 // Two identical pointer types are always compatible.
3403 return LHSTy;
3404 }
3405 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3406 rhptee.getUnqualifiedType())) {
3407 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3408 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3409 // In this situation, we assume void* type. No especially good
3410 // reason, but this is what gcc does, and we do have to pick
3411 // to get a consistent AST.
3412 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3413 ImpCastExprToType(LHS, incompatTy);
3414 ImpCastExprToType(RHS, incompatTy);
3415 return incompatTy;
3416 }
3417 // The pointer types are compatible.
3418 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3419 // differently qualified versions of compatible types, the result type is
3420 // a pointer to an appropriately qualified version of the *composite*
3421 // type.
3422 // FIXME: Need to calculate the composite type.
3423 // FIXME: Need to add qualifiers
3424 ImpCastExprToType(LHS, LHSTy);
3425 ImpCastExprToType(RHS, LHSTy);
3426 return LHSTy;
3427 }
3428
3429 // GCC compatibility: soften pointer/integer mismatch.
3430 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3431 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3432 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3433 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3434 return RHSTy;
3435 }
3436 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3437 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3438 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3439 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3440 return LHSTy;
3441 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00003442
Chris Lattner992ae932008-01-06 22:42:25 +00003443 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00003444 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3445 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003446 return QualType();
3447}
3448
Steve Naroff87d58b42007-09-16 03:34:24 +00003449/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00003450/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003451Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3452 SourceLocation ColonLoc,
3453 ExprArg Cond, ExprArg LHS,
3454 ExprArg RHS) {
3455 Expr *CondExpr = (Expr *) Cond.get();
3456 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00003457
3458 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3459 // was the condition.
3460 bool isLHSNull = LHSExpr == 0;
3461 if (isLHSNull)
3462 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003463
3464 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00003465 RHSExpr, QuestionLoc);
3466 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003467 return ExprError();
3468
3469 Cond.release();
3470 LHS.release();
3471 RHS.release();
Douglas Gregor34619872009-08-26 14:37:04 +00003472 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff774e4152009-01-21 00:14:39 +00003473 isLHSNull ? 0 : LHSExpr,
Douglas Gregor34619872009-08-26 14:37:04 +00003474 ColonLoc, RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00003475}
3476
Chris Lattner4b009652007-07-25 00:24:17 +00003477// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00003478// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00003479// routine is it effectively iqnores the qualifiers on the top level pointee.
3480// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3481// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00003482Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003483Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3484 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003485
David Chisnall44663db2009-08-17 16:35:33 +00003486 if ((lhsType->isObjCClassType() &&
3487 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3488 (rhsType->isObjCClassType() &&
3489 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3490 return Compatible;
3491 }
3492
Chris Lattner4b009652007-07-25 00:24:17 +00003493 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003494 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3495 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003496
Chris Lattner4b009652007-07-25 00:24:17 +00003497 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003498 lhptee = Context.getCanonicalType(lhptee);
3499 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00003500
Chris Lattner005ed752008-01-04 18:04:52 +00003501 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003502
3503 // C99 6.5.16.1p1: This following citation is common to constraints
3504 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3505 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00003506 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003507 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00003508 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00003509
Mike Stump9afab102009-02-19 03:04:26 +00003510 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3511 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00003512 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00003513 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003514 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003515 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00003516
Chris Lattner4ca3d772008-01-03 22:56:36 +00003517 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003518 assert(rhptee->isFunctionType());
3519 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003520 }
Mike Stump9afab102009-02-19 03:04:26 +00003521
Chris Lattner4ca3d772008-01-03 22:56:36 +00003522 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003523 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003524 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003525
3526 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003527 assert(lhptee->isFunctionType());
3528 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003529 }
Mike Stump9afab102009-02-19 03:04:26 +00003530 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00003531 // unqualified versions of compatible types, ...
Eli Friedman6ca28cb2009-03-22 23:59:44 +00003532 lhptee = lhptee.getUnqualifiedType();
3533 rhptee = rhptee.getUnqualifiedType();
3534 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3535 // Check if the pointee types are compatible ignoring the sign.
3536 // We explicitly check for char so that we catch "char" vs
3537 // "unsigned char" on systems where "char" is unsigned.
3538 if (lhptee->isCharType()) {
3539 lhptee = Context.UnsignedCharTy;
3540 } else if (lhptee->isSignedIntegerType()) {
3541 lhptee = Context.getCorrespondingUnsignedType(lhptee);
3542 }
3543 if (rhptee->isCharType()) {
3544 rhptee = Context.UnsignedCharTy;
3545 } else if (rhptee->isSignedIntegerType()) {
3546 rhptee = Context.getCorrespondingUnsignedType(rhptee);
3547 }
3548 if (lhptee == rhptee) {
3549 // Types are compatible ignoring the sign. Qualifier incompatibility
3550 // takes priority over sign incompatibility because the sign
3551 // warning can be disabled.
3552 if (ConvTy != Compatible)
3553 return ConvTy;
3554 return IncompatiblePointerSign;
3555 }
3556 // General pointer incompatibility takes priority over qualifiers.
3557 return IncompatiblePointer;
3558 }
Chris Lattner005ed752008-01-04 18:04:52 +00003559 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003560}
3561
Steve Naroff3454b6c2008-09-04 15:10:53 +00003562/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3563/// block pointer types are compatible or whether a block and normal pointer
3564/// are compatible. It is more restrict than comparing two function pointer
3565// types.
Mike Stump9afab102009-02-19 03:04:26 +00003566Sema::AssignConvertType
3567Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00003568 QualType rhsType) {
3569 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003570
Steve Naroff3454b6c2008-09-04 15:10:53 +00003571 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003572 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3573 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003574
Steve Naroff3454b6c2008-09-04 15:10:53 +00003575 // make sure we operate on the canonical type
3576 lhptee = Context.getCanonicalType(lhptee);
3577 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00003578
Steve Naroff3454b6c2008-09-04 15:10:53 +00003579 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003580
Steve Naroff3454b6c2008-09-04 15:10:53 +00003581 // For blocks we enforce that qualifiers are identical.
3582 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3583 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00003584
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00003585 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00003586 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003587 return ConvTy;
3588}
3589
Mike Stump9afab102009-02-19 03:04:26 +00003590/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3591/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00003592/// pointers. Here are some objectionable examples that GCC considers warnings:
3593///
3594/// int a, *pint;
3595/// short *pshort;
3596/// struct foo *pfoo;
3597///
3598/// pint = pshort; // warning: assignment from incompatible pointer type
3599/// a = pint; // warning: assignment makes integer from pointer without a cast
3600/// pint = a; // warning: assignment makes pointer from integer without a cast
3601/// pint = pfoo; // warning: assignment from incompatible pointer type
3602///
3603/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00003604/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00003605///
Chris Lattner005ed752008-01-04 18:04:52 +00003606Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003607Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00003608 // Get canonical types. We're not formatting these types, just comparing
3609 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003610 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3611 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00003612
3613 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00003614 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00003615
David Chisnall44663db2009-08-17 16:35:33 +00003616 if ((lhsType->isObjCClassType() &&
3617 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3618 (rhsType->isObjCClassType() &&
3619 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3620 return Compatible;
3621 }
3622
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003623 // If the left-hand side is a reference type, then we are in a
3624 // (rare!) case where we've allowed the use of references in C,
3625 // e.g., as a parameter type in a built-in function. In this case,
3626 // just make sure that the type referenced is compatible with the
3627 // right-hand side type. The caller is responsible for adjusting
3628 // lhsType so that the resulting expression does not have reference
3629 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003630 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003631 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00003632 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003633 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003634 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003635 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3636 // to the same ExtVector type.
3637 if (lhsType->isExtVectorType()) {
3638 if (rhsType->isExtVectorType())
3639 return lhsType == rhsType ? Compatible : Incompatible;
3640 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3641 return Compatible;
3642 }
3643
Nate Begemanc5f0f652008-07-14 18:02:46 +00003644 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003645 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00003646 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00003647 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003648 if (getLangOptions().LaxVectorConversions &&
3649 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003650 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00003651 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003652 }
3653 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00003654 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003655
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003656 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00003657 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003658
Chris Lattner390564e2008-04-07 06:49:41 +00003659 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003660 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003661 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003662
Chris Lattner390564e2008-04-07 06:49:41 +00003663 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003664 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003665
Steve Naroff8194a542009-07-20 17:56:53 +00003666 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003667 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003668 if (lhsType->isVoidPointerType()) // an exception to the rule.
3669 return Compatible;
3670 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003671 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003672 if (rhsType->getAs<BlockPointerType>()) {
3673 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003674 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00003675
3676 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003677 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003678 return Compatible;
3679 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003680 return Incompatible;
3681 }
3682
3683 if (isa<BlockPointerType>(lhsType)) {
3684 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00003685 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00003686
Steve Naroffa982c712008-09-29 18:10:17 +00003687 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003688 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003689 return Compatible;
3690
Steve Naroff3454b6c2008-09-04 15:10:53 +00003691 if (rhsType->isBlockPointerType())
3692 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003693
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003694 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff3454b6c2008-09-04 15:10:53 +00003695 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003696 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003697 }
Chris Lattner1853da22008-01-04 23:18:45 +00003698 return Incompatible;
3699 }
3700
Steve Naroff329ec222009-07-10 23:34:53 +00003701 if (isa<ObjCObjectPointerType>(lhsType)) {
3702 if (rhsType->isIntegerType())
3703 return IntToPointer;
Steve Naroff8194a542009-07-20 17:56:53 +00003704
3705 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003706 if (isa<PointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003707 if (rhsType->isVoidPointerType()) // an exception to the rule.
3708 return Compatible;
3709 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003710 }
3711 if (rhsType->isObjCObjectPointerType()) {
Steve Naroff7bffd372009-07-15 18:40:39 +00003712 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3713 return Compatible;
Steve Naroff8194a542009-07-20 17:56:53 +00003714 if (Context.typesAreCompatible(lhsType, rhsType))
3715 return Compatible;
Steve Naroff99eb86b2009-07-23 01:01:38 +00003716 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3717 return IncompatibleObjCQualifiedId;
Steve Naroff8194a542009-07-20 17:56:53 +00003718 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003719 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003720 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff329ec222009-07-10 23:34:53 +00003721 if (RHSPT->getPointeeType()->isVoidType())
3722 return Compatible;
3723 }
3724 // Treat block pointers as objects.
3725 if (rhsType->isBlockPointerType())
3726 return Compatible;
3727 return Incompatible;
3728 }
Chris Lattner390564e2008-04-07 06:49:41 +00003729 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003730 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00003731 if (lhsType == Context.BoolTy)
3732 return Compatible;
3733
3734 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003735 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00003736
Mike Stump9afab102009-02-19 03:04:26 +00003737 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003738 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003739
3740 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003741 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003742 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003743 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003744 }
Steve Naroff329ec222009-07-10 23:34:53 +00003745 if (isa<ObjCObjectPointerType>(rhsType)) {
3746 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3747 if (lhsType == Context.BoolTy)
3748 return Compatible;
3749
3750 if (lhsType->isIntegerType())
3751 return PointerToInt;
3752
Steve Naroff8194a542009-07-20 17:56:53 +00003753 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003754 if (isa<PointerType>(lhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003755 if (lhsType->isVoidPointerType()) // an exception to the rule.
3756 return Compatible;
3757 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003758 }
3759 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003760 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff329ec222009-07-10 23:34:53 +00003761 return Compatible;
3762 return Incompatible;
3763 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003764
Chris Lattner1853da22008-01-04 23:18:45 +00003765 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00003766 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003767 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00003768 }
3769 return Incompatible;
3770}
3771
Douglas Gregor144b06c2009-04-29 22:16:16 +00003772/// \brief Constructs a transparent union from an expression that is
3773/// used to initialize the transparent union.
3774static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3775 QualType UnionType, FieldDecl *Field) {
3776 // Build an initializer list that designates the appropriate member
3777 // of the transparent union.
3778 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3779 &E, 1,
3780 SourceLocation());
3781 Initializer->setType(UnionType);
3782 Initializer->setInitializedFieldInUnion(Field);
3783
3784 // Build a compound literal constructing a value of the transparent
3785 // union type from this initializer list.
3786 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3787 false);
3788}
3789
3790Sema::AssignConvertType
3791Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3792 QualType FromType = rExpr->getType();
3793
3794 // If the ArgType is a Union type, we want to handle a potential
3795 // transparent_union GCC extension.
3796 const RecordType *UT = ArgType->getAsUnionType();
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003797 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor144b06c2009-04-29 22:16:16 +00003798 return Incompatible;
3799
3800 // The field to initialize within the transparent union.
3801 RecordDecl *UD = UT->getDecl();
3802 FieldDecl *InitField = 0;
3803 // It's compatible if the expression matches any of the fields.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003804 for (RecordDecl::field_iterator it = UD->field_begin(),
3805 itend = UD->field_end();
Douglas Gregor144b06c2009-04-29 22:16:16 +00003806 it != itend; ++it) {
3807 if (it->getType()->isPointerType()) {
3808 // If the transparent union contains a pointer type, we allow:
3809 // 1) void pointer
3810 // 2) null pointer constant
3811 if (FromType->isPointerType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003812 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor144b06c2009-04-29 22:16:16 +00003813 ImpCastExprToType(rExpr, it->getType());
3814 InitField = *it;
3815 break;
3816 }
3817
3818 if (rExpr->isNullPointerConstant(Context)) {
3819 ImpCastExprToType(rExpr, it->getType());
3820 InitField = *it;
3821 break;
3822 }
3823 }
3824
3825 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3826 == Compatible) {
3827 InitField = *it;
3828 break;
3829 }
3830 }
3831
3832 if (!InitField)
3833 return Incompatible;
3834
3835 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3836 return Compatible;
3837}
3838
Chris Lattner005ed752008-01-04 18:04:52 +00003839Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003840Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003841 if (getLangOptions().CPlusPlus) {
3842 if (!lhsType->isRecordType()) {
3843 // C++ 5.17p3: If the left operand is not of class type, the
3844 // expression is implicitly converted (C++ 4) to the
3845 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00003846 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3847 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003848 return Incompatible;
Chris Lattner79e9a422009-04-12 09:02:39 +00003849 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003850 }
3851
3852 // FIXME: Currently, we fall through and treat C++ classes like C
3853 // structures.
3854 }
3855
Steve Naroffcdee22d2007-11-27 17:58:44 +00003856 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3857 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00003858 if ((lhsType->isPointerType() ||
Steve Naroff329ec222009-07-10 23:34:53 +00003859 lhsType->isObjCObjectPointerType() ||
Mike Stump9afab102009-02-19 03:04:26 +00003860 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00003861 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003862 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00003863 return Compatible;
3864 }
Mike Stump9afab102009-02-19 03:04:26 +00003865
Chris Lattner5f505bf2007-10-16 02:55:40 +00003866 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00003867 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00003868 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00003869 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00003870 //
Mike Stump9afab102009-02-19 03:04:26 +00003871 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00003872 if (!lhsType->isReferenceType())
3873 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00003874
Chris Lattner005ed752008-01-04 18:04:52 +00003875 Sema::AssignConvertType result =
3876 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00003877
Steve Naroff0f32f432007-08-24 22:33:52 +00003878 // C99 6.5.16.1p2: The value of the right operand is converted to the
3879 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003880 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3881 // so that we can use references in built-in functions even in C.
3882 // The getNonReferenceType() call makes sure that the resulting expression
3883 // does not have reference type.
Douglas Gregor144b06c2009-04-29 22:16:16 +00003884 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003885 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00003886 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00003887}
3888
Chris Lattner1eafdea2008-11-18 01:30:42 +00003889QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003890 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003891 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003892 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00003893 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003894}
3895
Mike Stump9afab102009-02-19 03:04:26 +00003896inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00003897 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00003898 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00003899 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003900 QualType lhsType =
3901 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3902 QualType rhsType =
3903 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00003904
Nate Begemanc5f0f652008-07-14 18:02:46 +00003905 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00003906 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00003907 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00003908
Nate Begemanc5f0f652008-07-14 18:02:46 +00003909 // Handle the case of a vector & extvector type of the same size and element
3910 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00003911 if (getLangOptions().LaxVectorConversions) {
3912 // FIXME: Should we warn here?
3913 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003914 if (const VectorType *RV = rhsType->getAsVectorType())
3915 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00003916 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003917 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00003918 }
3919 }
3920 }
Mike Stump9afab102009-02-19 03:04:26 +00003921
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003922 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
3923 // swap back (so that we don't reverse the inputs to a subtract, for instance.
3924 bool swapped = false;
3925 if (rhsType->isExtVectorType()) {
3926 swapped = true;
3927 std::swap(rex, lex);
3928 std::swap(rhsType, lhsType);
3929 }
3930
Nate Begemanf1695892009-06-28 19:12:57 +00003931 // Handle the case of an ext vector and scalar.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003932 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) {
3933 QualType EltTy = LV->getElementType();
3934 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
3935 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00003936 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003937 if (swapped) std::swap(rex, lex);
3938 return lhsType;
3939 }
3940 }
3941 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
3942 rhsType->isRealFloatingType()) {
3943 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00003944 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003945 if (swapped) std::swap(rex, lex);
3946 return lhsType;
3947 }
Nate Begemanec2d1062007-12-30 02:59:45 +00003948 }
3949 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003950
Nate Begemanf1695892009-06-28 19:12:57 +00003951 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner70b93d82008-11-18 22:52:51 +00003952 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003953 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003954 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003955 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00003956}
3957
Chris Lattner4b009652007-07-25 00:24:17 +00003958inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003959 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003960{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00003961 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003962 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003963
Steve Naroff8f708362007-08-24 19:07:16 +00003964 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003965
Chris Lattner4b009652007-07-25 00:24:17 +00003966 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00003967 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003968 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003969}
3970
3971inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003972 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003973{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00003974 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3975 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3976 return CheckVectorOperands(Loc, lex, rex);
3977 return InvalidOperands(Loc, lex, rex);
3978 }
Chris Lattner4b009652007-07-25 00:24:17 +00003979
Steve Naroff8f708362007-08-24 19:07:16 +00003980 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003981
Chris Lattner4b009652007-07-25 00:24:17 +00003982 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003983 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003984 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003985}
3986
3987inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Eli Friedman3cd92882009-03-28 01:22:36 +00003988 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
Chris Lattner4b009652007-07-25 00:24:17 +00003989{
Eli Friedman3cd92882009-03-28 01:22:36 +00003990 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3991 QualType compType = CheckVectorOperands(Loc, lex, rex);
3992 if (CompLHSTy) *CompLHSTy = compType;
3993 return compType;
3994 }
Chris Lattner4b009652007-07-25 00:24:17 +00003995
Eli Friedman3cd92882009-03-28 01:22:36 +00003996 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003997
Chris Lattner4b009652007-07-25 00:24:17 +00003998 // handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00003999 if (lex->getType()->isArithmeticType() &&
4000 rex->getType()->isArithmeticType()) {
4001 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00004002 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00004003 }
Chris Lattner4b009652007-07-25 00:24:17 +00004004
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004005 // Put any potential pointer into PExp
4006 Expr* PExp = lex, *IExp = rex;
Steve Naroff79ae19a2009-07-14 18:25:06 +00004007 if (IExp->getType()->isAnyPointerType())
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004008 std::swap(PExp, IExp);
4009
Steve Naroff79ae19a2009-07-14 18:25:06 +00004010 if (PExp->getType()->isAnyPointerType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00004011
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004012 if (IExp->getType()->isIntegerType()) {
Steve Naroff18b38122009-07-13 21:20:41 +00004013 QualType PointeeTy = PExp->getType()->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00004014
Chris Lattner184f92d2009-04-24 23:50:08 +00004015 // Check for arithmetic on pointers to incomplete types.
4016 if (PointeeTy->isVoidType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00004017 if (getLangOptions().CPlusPlus) {
4018 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner8ba580c2008-11-19 05:08:23 +00004019 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004020 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004021 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004022
4023 // GNU extension: arithmetic on pointer to void
4024 Diag(Loc, diag::ext_gnu_void_ptr)
4025 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner184f92d2009-04-24 23:50:08 +00004026 } else if (PointeeTy->isFunctionType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00004027 if (getLangOptions().CPlusPlus) {
4028 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4029 << lex->getType() << lex->getSourceRange();
4030 return QualType();
4031 }
4032
4033 // GNU extension: arithmetic on pointer to function
4034 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4035 << lex->getType() << lex->getSourceRange();
Steve Naroff3fc227b2009-07-13 21:32:29 +00004036 } else {
Steve Naroff18b38122009-07-13 21:20:41 +00004037 // Check if we require a complete type.
4038 if (((PExp->getType()->isPointerType() &&
Steve Naroff3fc227b2009-07-13 21:32:29 +00004039 !PExp->getType()->isDependentType()) ||
Steve Naroff18b38122009-07-13 21:20:41 +00004040 PExp->getType()->isObjCObjectPointerType()) &&
4041 RequireCompleteType(Loc, PointeeTy,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004042 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4043 << PExp->getSourceRange()
4044 << PExp->getType()))
Steve Naroff18b38122009-07-13 21:20:41 +00004045 return QualType();
4046 }
Chris Lattner184f92d2009-04-24 23:50:08 +00004047 // Diagnose bad cases where we step over interface counts.
4048 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4049 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4050 << PointeeTy << PExp->getSourceRange();
4051 return QualType();
4052 }
4053
Eli Friedman3cd92882009-03-28 01:22:36 +00004054 if (CompLHSTy) {
Eli Friedman1931cc82009-08-20 04:21:42 +00004055 QualType LHSTy = Context.isPromotableBitField(lex);
4056 if (LHSTy.isNull()) {
4057 LHSTy = lex->getType();
4058 if (LHSTy->isPromotableIntegerType())
4059 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004060 }
Eli Friedman3cd92882009-03-28 01:22:36 +00004061 *CompLHSTy = LHSTy;
4062 }
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004063 return PExp->getType();
4064 }
4065 }
4066
Chris Lattner1eafdea2008-11-18 01:30:42 +00004067 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004068}
4069
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004070// C99 6.5.6
4071QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman3cd92882009-03-28 01:22:36 +00004072 SourceLocation Loc, QualType* CompLHSTy) {
4073 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4074 QualType compType = CheckVectorOperands(Loc, lex, rex);
4075 if (CompLHSTy) *CompLHSTy = compType;
4076 return compType;
4077 }
Mike Stump9afab102009-02-19 03:04:26 +00004078
Eli Friedman3cd92882009-03-28 01:22:36 +00004079 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump9afab102009-02-19 03:04:26 +00004080
Chris Lattnerf6da2912007-12-09 21:53:25 +00004081 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00004082
Chris Lattnerf6da2912007-12-09 21:53:25 +00004083 // Handle the common case first (both operands are arithmetic).
Mike Stumpea3d74e2009-05-07 18:43:07 +00004084 if (lex->getType()->isArithmeticType()
4085 && rex->getType()->isArithmeticType()) {
Eli Friedman3cd92882009-03-28 01:22:36 +00004086 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00004087 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00004088 }
Steve Naroff329ec222009-07-10 23:34:53 +00004089
Chris Lattnerf6da2912007-12-09 21:53:25 +00004090 // Either ptr - int or ptr - ptr.
Steve Naroff79ae19a2009-07-14 18:25:06 +00004091 if (lex->getType()->isAnyPointerType()) {
Steve Naroff7982a642009-07-13 17:19:15 +00004092 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004093
Douglas Gregor05e28f62009-03-24 19:52:54 +00004094 // The LHS must be an completely-defined object type.
Douglas Gregorb3193242009-01-23 00:36:41 +00004095
Douglas Gregor05e28f62009-03-24 19:52:54 +00004096 bool ComplainAboutVoid = false;
4097 Expr *ComplainAboutFunc = 0;
4098 if (lpointee->isVoidType()) {
4099 if (getLangOptions().CPlusPlus) {
4100 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4101 << lex->getSourceRange() << rex->getSourceRange();
4102 return QualType();
4103 }
4104
4105 // GNU C extension: arithmetic on pointer to void
4106 ComplainAboutVoid = true;
4107 } else if (lpointee->isFunctionType()) {
4108 if (getLangOptions().CPlusPlus) {
4109 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004110 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004111 return QualType();
4112 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004113
4114 // GNU C extension: arithmetic on pointer to function
4115 ComplainAboutFunc = lex;
4116 } else if (!lpointee->isDependentType() &&
4117 RequireCompleteType(Loc, lpointee,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004118 PDiag(diag::err_typecheck_sub_ptr_object)
4119 << lex->getSourceRange()
4120 << lex->getType()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00004121 return QualType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004122
Chris Lattner184f92d2009-04-24 23:50:08 +00004123 // Diagnose bad cases where we step over interface counts.
4124 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4125 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4126 << lpointee << lex->getSourceRange();
4127 return QualType();
4128 }
4129
Chris Lattnerf6da2912007-12-09 21:53:25 +00004130 // The result type of a pointer-int computation is the pointer type.
Douglas Gregor05e28f62009-03-24 19:52:54 +00004131 if (rex->getType()->isIntegerType()) {
4132 if (ComplainAboutVoid)
4133 Diag(Loc, diag::ext_gnu_void_ptr)
4134 << lex->getSourceRange() << rex->getSourceRange();
4135 if (ComplainAboutFunc)
4136 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4137 << ComplainAboutFunc->getType()
4138 << ComplainAboutFunc->getSourceRange();
4139
Eli Friedman3cd92882009-03-28 01:22:36 +00004140 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004141 return lex->getType();
Douglas Gregor05e28f62009-03-24 19:52:54 +00004142 }
Mike Stump9afab102009-02-19 03:04:26 +00004143
Chris Lattnerf6da2912007-12-09 21:53:25 +00004144 // Handle pointer-pointer subtractions.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004145 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman50727042008-02-08 01:19:44 +00004146 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004147
Douglas Gregor05e28f62009-03-24 19:52:54 +00004148 // RHS must be a completely-type object type.
4149 // Handle the GNU void* extension.
4150 if (rpointee->isVoidType()) {
4151 if (getLangOptions().CPlusPlus) {
4152 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4153 << lex->getSourceRange() << rex->getSourceRange();
4154 return QualType();
4155 }
Mike Stump9afab102009-02-19 03:04:26 +00004156
Douglas Gregor05e28f62009-03-24 19:52:54 +00004157 ComplainAboutVoid = true;
4158 } else if (rpointee->isFunctionType()) {
4159 if (getLangOptions().CPlusPlus) {
4160 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004161 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004162 return QualType();
4163 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004164
4165 // GNU extension: arithmetic on pointer to function
4166 if (!ComplainAboutFunc)
4167 ComplainAboutFunc = rex;
4168 } else if (!rpointee->isDependentType() &&
4169 RequireCompleteType(Loc, rpointee,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004170 PDiag(diag::err_typecheck_sub_ptr_object)
4171 << rex->getSourceRange()
4172 << rex->getType()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00004173 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004174
Eli Friedman143ddc92009-05-16 13:54:38 +00004175 if (getLangOptions().CPlusPlus) {
4176 // Pointee types must be the same: C++ [expr.add]
4177 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4178 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4179 << lex->getType() << rex->getType()
4180 << lex->getSourceRange() << rex->getSourceRange();
4181 return QualType();
4182 }
4183 } else {
4184 // Pointee types must be compatible C99 6.5.6p3
4185 if (!Context.typesAreCompatible(
4186 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4187 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4188 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4189 << lex->getType() << rex->getType()
4190 << lex->getSourceRange() << rex->getSourceRange();
4191 return QualType();
4192 }
Chris Lattnerf6da2912007-12-09 21:53:25 +00004193 }
Mike Stump9afab102009-02-19 03:04:26 +00004194
Douglas Gregor05e28f62009-03-24 19:52:54 +00004195 if (ComplainAboutVoid)
4196 Diag(Loc, diag::ext_gnu_void_ptr)
4197 << lex->getSourceRange() << rex->getSourceRange();
4198 if (ComplainAboutFunc)
4199 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4200 << ComplainAboutFunc->getType()
4201 << ComplainAboutFunc->getSourceRange();
Eli Friedman3cd92882009-03-28 01:22:36 +00004202
4203 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004204 return Context.getPointerDiffType();
4205 }
4206 }
Mike Stump9afab102009-02-19 03:04:26 +00004207
Chris Lattner1eafdea2008-11-18 01:30:42 +00004208 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004209}
4210
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004211// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00004212QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004213 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00004214 // C99 6.5.7p2: Each of the operands shall have integer type.
4215 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004216 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00004217
Chris Lattner2c8bff72007-12-12 05:47:28 +00004218 // Shifts don't perform usual arithmetic conversions, they just do integer
4219 // promotions on each operand. C99 6.5.7p3
Eli Friedman1931cc82009-08-20 04:21:42 +00004220 QualType LHSTy = Context.isPromotableBitField(lex);
4221 if (LHSTy.isNull()) {
4222 LHSTy = lex->getType();
4223 if (LHSTy->isPromotableIntegerType())
4224 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004225 }
Chris Lattnerbb19bc42007-12-13 07:28:16 +00004226 if (!isCompAssign)
Eli Friedman3cd92882009-03-28 01:22:36 +00004227 ImpCastExprToType(lex, LHSTy);
4228
Chris Lattner2c8bff72007-12-12 05:47:28 +00004229 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004230
Ryan Flynnf109fff2009-08-07 16:20:20 +00004231 // Sanity-check shift operands
4232 llvm::APSInt Right;
4233 // Check right/shifter operand
4234 if (rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynna5e76932009-08-08 19:18:23 +00004235 if (Right.isNegative())
Ryan Flynnf109fff2009-08-07 16:20:20 +00004236 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4237 else {
4238 llvm::APInt LeftBits(Right.getBitWidth(),
4239 Context.getTypeSize(lex->getType()));
4240 if (Right.uge(LeftBits))
4241 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4242 }
4243 }
4244
Chris Lattner2c8bff72007-12-12 05:47:28 +00004245 // "The type of the result is that of the promoted left operand."
Eli Friedman3cd92882009-03-28 01:22:36 +00004246 return LHSTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004247}
4248
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004249// C99 6.5.8, C++ [expr.rel]
Chris Lattner1eafdea2008-11-18 01:30:42 +00004250QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor1f12c352009-04-06 18:45:53 +00004251 unsigned OpaqueOpc, bool isRelational) {
4252 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4253
Nate Begemanc5f0f652008-07-14 18:02:46 +00004254 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004255 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00004256
Chris Lattner254f3bc2007-08-26 01:18:55 +00004257 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00004258 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4259 UsualArithmeticConversions(lex, rex);
4260 else {
4261 UsualUnaryConversions(lex);
4262 UsualUnaryConversions(rex);
4263 }
Chris Lattner4b009652007-07-25 00:24:17 +00004264 QualType lType = lex->getType();
4265 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004266
Mike Stumpea3d74e2009-05-07 18:43:07 +00004267 if (!lType->isFloatingType()
4268 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004269 // For non-floating point types, check for self-comparisons of the form
4270 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4271 // often indicate logic errors in the program.
Ted Kremenek264b5cb2009-03-20 19:57:37 +00004272 // NOTE: Don't warn about comparisons of enum constants. These can arise
4273 // from macro expansions, and are usually quite deliberate.
Chris Lattner4e479f92009-03-08 19:39:53 +00004274 Expr *LHSStripped = lex->IgnoreParens();
4275 Expr *RHSStripped = rex->IgnoreParens();
4276 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4277 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekf042dc62009-03-20 18:35:45 +00004278 if (DRL->getDecl() == DRR->getDecl() &&
4279 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump9afab102009-02-19 03:04:26 +00004280 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner4e479f92009-03-08 19:39:53 +00004281
4282 if (isa<CastExpr>(LHSStripped))
4283 LHSStripped = LHSStripped->IgnoreParenCasts();
4284 if (isa<CastExpr>(RHSStripped))
4285 RHSStripped = RHSStripped->IgnoreParenCasts();
4286
4287 // Warn about comparisons against a string constant (unless the other
4288 // operand is null), the user probably wants strcmp.
Douglas Gregor1f12c352009-04-06 18:45:53 +00004289 Expr *literalString = 0;
4290 Expr *literalStringStripped = 0;
Chris Lattner4e479f92009-03-08 19:39:53 +00004291 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00004292 !RHSStripped->isNullPointerConstant(Context)) {
4293 literalString = lex;
4294 literalStringStripped = LHSStripped;
Mike Stump90fc78e2009-08-04 21:02:39 +00004295 } else if ((isa<StringLiteral>(RHSStripped) ||
4296 isa<ObjCEncodeExpr>(RHSStripped)) &&
4297 !LHSStripped->isNullPointerConstant(Context)) {
Douglas Gregor1f12c352009-04-06 18:45:53 +00004298 literalString = rex;
4299 literalStringStripped = RHSStripped;
4300 }
4301
4302 if (literalString) {
4303 std::string resultComparison;
4304 switch (Opc) {
4305 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4306 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4307 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4308 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4309 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4310 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4311 default: assert(false && "Invalid comparison operator");
4312 }
4313 Diag(Loc, diag::warn_stringcompare)
4314 << isa<ObjCEncodeExpr>(literalStringStripped)
4315 << literalString->getSourceRange()
Douglas Gregor3faaa812009-04-01 23:51:29 +00004316 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4317 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4318 "strcmp(")
4319 << CodeModificationHint::CreateInsertion(
4320 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor1f12c352009-04-06 18:45:53 +00004321 resultComparison);
4322 }
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00004323 }
Mike Stump9afab102009-02-19 03:04:26 +00004324
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004325 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner4e479f92009-03-08 19:39:53 +00004326 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004327
Chris Lattner254f3bc2007-08-26 01:18:55 +00004328 if (isRelational) {
4329 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004330 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004331 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00004332 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00004333 if (lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004334 assert(rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004335 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00004336 }
Mike Stump9afab102009-02-19 03:04:26 +00004337
Chris Lattner254f3bc2007-08-26 01:18:55 +00004338 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004339 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004340 }
Mike Stump9afab102009-02-19 03:04:26 +00004341
Chris Lattner22be8422007-08-26 01:10:14 +00004342 bool LHSIsNull = lex->isNullPointerConstant(Context);
4343 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00004344
Chris Lattner254f3bc2007-08-26 01:18:55 +00004345 // All of the following pointer related warnings are GCC extensions, except
4346 // when handling null pointer constants. One day, we can consider making them
4347 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00004348 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00004349 QualType LCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004350 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00004351 QualType RCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004352 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00004353
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004354 if (getLangOptions().CPlusPlus) {
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004355 if (LCanPointeeTy == RCanPointeeTy)
4356 return ResultTy;
4357
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004358 // C++ [expr.rel]p2:
4359 // [...] Pointer conversions (4.10) and qualification
4360 // conversions (4.4) are performed on pointer operands (or on
4361 // a pointer operand and a null pointer constant) to bring
4362 // them to their composite pointer type. [...]
4363 //
Douglas Gregor70be4db2009-08-24 17:42:35 +00004364 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004365 // comparisons of pointers.
Douglas Gregorcf651d22009-05-05 04:50:50 +00004366 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004367 if (T.isNull()) {
4368 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4369 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4370 return QualType();
4371 }
4372
4373 ImpCastExprToType(lex, T);
4374 ImpCastExprToType(rex, T);
4375 return ResultTy;
4376 }
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004377 // C99 6.5.9p2 and C99 6.5.8p2
4378 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4379 RCanPointeeTy.getUnqualifiedType())) {
4380 // Valid unless a relational comparison of function pointers
4381 if (isRelational && LCanPointeeTy->isFunctionType()) {
4382 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4383 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4384 }
4385 } else if (!isRelational &&
4386 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4387 // Valid unless comparison between non-null pointer and function pointer
4388 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4389 && !LHSIsNull && !RHSIsNull) {
4390 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4391 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4392 }
4393 } else {
4394 // Invalid
Chris Lattner70b93d82008-11-18 22:52:51 +00004395 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004396 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004397 }
Eli Friedman02fdbfe2009-08-23 00:27:47 +00004398 if (LCanPointeeTy != RCanPointeeTy)
4399 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004400 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004401 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004402
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004403 if (getLangOptions().CPlusPlus) {
Douglas Gregor70be4db2009-08-24 17:42:35 +00004404 // Comparison of pointers with null pointer constants and equality
4405 // comparisons of member pointers to null pointer constants.
4406 if (RHSIsNull &&
4407 (lType->isPointerType() ||
4408 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson9a385522009-08-24 18:03:14 +00004409 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004410 return ResultTy;
4411 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004412 if (LHSIsNull &&
4413 (rType->isPointerType() ||
4414 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson9a385522009-08-24 18:03:14 +00004415 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004416 return ResultTy;
4417 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004418
4419 // Comparison of member pointers.
4420 if (!isRelational &&
4421 lType->isMemberPointerType() && rType->isMemberPointerType()) {
4422 // C++ [expr.eq]p2:
4423 // In addition, pointers to members can be compared, or a pointer to
4424 // member and a null pointer constant. Pointer to member conversions
4425 // (4.11) and qualification conversions (4.4) are performed to bring
4426 // them to a common type. If one operand is a null pointer constant,
4427 // the common type is the type of the other operand. Otherwise, the
4428 // common type is a pointer to member type similar (4.4) to the type
4429 // of one of the operands, with a cv-qualification signature (4.4)
4430 // that is the union of the cv-qualification signatures of the operand
4431 // types.
4432 QualType T = FindCompositePointerType(lex, rex);
4433 if (T.isNull()) {
4434 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4435 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4436 return QualType();
4437 }
4438
4439 ImpCastExprToType(lex, T);
4440 ImpCastExprToType(rex, T);
4441 return ResultTy;
4442 }
4443
4444 // Comparison of nullptr_t with itself.
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004445 if (lType->isNullPtrType() && rType->isNullPtrType())
4446 return ResultTy;
4447 }
Douglas Gregor70be4db2009-08-24 17:42:35 +00004448
Steve Naroff3454b6c2008-09-04 15:10:53 +00004449 // Handle block pointer types.
Mike Stumpe97a8542009-05-07 03:14:14 +00004450 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004451 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4452 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004453
Steve Naroff3454b6c2008-09-04 15:10:53 +00004454 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00004455 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004456 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004457 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00004458 }
4459 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004460 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004461 }
Steve Narofff85d66c2008-09-28 01:11:11 +00004462 // Allow block pointers to be compared with null pointer constants.
Mike Stumpe97a8542009-05-07 03:14:14 +00004463 if (!isRelational
4464 && ((lType->isBlockPointerType() && rType->isPointerType())
4465 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Narofff85d66c2008-09-28 01:11:11 +00004466 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004467 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004468 ->getPointeeType()->isVoidType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004469 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004470 ->getPointeeType()->isVoidType())))
4471 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4472 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00004473 }
4474 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004475 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00004476 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00004477
Steve Naroff329ec222009-07-10 23:34:53 +00004478 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00004479 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004480 const PointerType *LPT = lType->getAs<PointerType>();
4481 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump9afab102009-02-19 03:04:26 +00004482 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004483 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004484 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004485 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004486
Steve Naroff030fcda2008-11-17 19:49:16 +00004487 if (!LPtrToVoid && !RPtrToVoid &&
4488 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004489 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004490 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00004491 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00004492 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004493 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00004494 }
Steve Naroff329ec222009-07-10 23:34:53 +00004495 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004496 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff329ec222009-07-10 23:34:53 +00004497 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4498 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff936c4362008-06-03 14:04:54 +00004499 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004500 return ResultTy;
Steve Naroff936c4362008-06-03 14:04:54 +00004501 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00004502 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004503 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner124569f2009-08-23 00:03:44 +00004504 unsigned DiagID = 0;
4505 if (RHSIsNull) {
4506 if (isRelational)
4507 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4508 } else if (isRelational)
4509 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4510 else
4511 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
4512
4513 if (DiagID) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004514 Diag(Loc, DiagID)
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004515 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner8b88b142009-08-22 18:58:31 +00004516 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004517 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004518 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004519 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004520 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner124569f2009-08-23 00:03:44 +00004521 unsigned DiagID = 0;
4522 if (LHSIsNull) {
4523 if (isRelational)
4524 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4525 } else if (isRelational)
4526 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4527 else
4528 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Chris Lattner8b88b142009-08-22 18:58:31 +00004529
Chris Lattner124569f2009-08-23 00:03:44 +00004530 if (DiagID) {
Chris Lattner8b88b142009-08-22 18:58:31 +00004531 Diag(Loc, DiagID)
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004532 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner8b88b142009-08-22 18:58:31 +00004533 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004534 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004535 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004536 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00004537 // Handle block pointers.
Mike Stumpea3d74e2009-05-07 18:43:07 +00004538 if (!isRelational && RHSIsNull
4539 && lType->isBlockPointerType() && rType->isIntegerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004540 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004541 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004542 }
Mike Stumpea3d74e2009-05-07 18:43:07 +00004543 if (!isRelational && LHSIsNull
4544 && lType->isIntegerType() && rType->isBlockPointerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004545 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004546 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004547 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00004548 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004549}
4550
Nate Begemanc5f0f652008-07-14 18:02:46 +00004551/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00004552/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004553/// like a scalar comparison, a vector comparison produces a vector of integer
4554/// types.
4555QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00004556 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004557 bool isRelational) {
4558 // Check to make sure we're operating on vectors of the same type and width,
4559 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004560 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004561 if (vType.isNull())
4562 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00004563
Nate Begemanc5f0f652008-07-14 18:02:46 +00004564 QualType lType = lex->getType();
4565 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004566
Nate Begemanc5f0f652008-07-14 18:02:46 +00004567 // For non-floating point types, check for self-comparisons of the form
4568 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4569 // often indicate logic errors in the program.
4570 if (!lType->isFloatingType()) {
4571 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4572 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4573 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00004574 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004575 }
Mike Stump9afab102009-02-19 03:04:26 +00004576
Nate Begemanc5f0f652008-07-14 18:02:46 +00004577 // Check for comparisons of floating point operands using != and ==.
4578 if (!isRelational && lType->isFloatingType()) {
4579 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004580 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004581 }
Mike Stump9afab102009-02-19 03:04:26 +00004582
Nate Begemanc5f0f652008-07-14 18:02:46 +00004583 // Return the type for the comparison, which is the same as vector type for
4584 // integer vectors, or an integer type of identical size and number of
4585 // elements for floating point vectors.
4586 if (lType->isIntegerType())
4587 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00004588
Nate Begemanc5f0f652008-07-14 18:02:46 +00004589 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00004590 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00004591 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00004592 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner10687e32009-03-31 07:46:52 +00004593 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begemand6d2f772009-01-18 03:20:47 +00004594 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4595
Mike Stump9afab102009-02-19 03:04:26 +00004596 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00004597 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00004598 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4599}
4600
Chris Lattner4b009652007-07-25 00:24:17 +00004601inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004602 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004603{
4604 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004605 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004606
Steve Naroff8f708362007-08-24 19:07:16 +00004607 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004608
Chris Lattner4b009652007-07-25 00:24:17 +00004609 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00004610 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004611 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004612}
4613
4614inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00004615 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00004616{
4617 UsualUnaryConversions(lex);
4618 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004619
Eli Friedmanbea3f842008-05-13 20:16:47 +00004620 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00004621 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004622 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004623}
4624
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004625/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4626/// is a read-only property; return true if so. A readonly property expression
4627/// depends on various declarations and thus must be treated specially.
4628///
Mike Stump9afab102009-02-19 03:04:26 +00004629static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004630{
4631 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4632 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4633 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4634 QualType BaseType = PropExpr->getBase()->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00004635 if (const ObjCObjectPointerType *OPT =
4636 BaseType->getAsObjCInterfacePointerType())
4637 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4638 if (S.isPropertyReadonly(PDecl, IFace))
4639 return true;
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004640 }
4641 }
4642 return false;
4643}
4644
Chris Lattner4c2642c2008-11-18 01:22:49 +00004645/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4646/// emit an error and return true. If so, return false.
4647static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004648 SourceLocation OrigLoc = Loc;
4649 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4650 &Loc);
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004651 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4652 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004653 if (IsLV == Expr::MLV_Valid)
4654 return false;
Mike Stump9afab102009-02-19 03:04:26 +00004655
Chris Lattner4c2642c2008-11-18 01:22:49 +00004656 unsigned Diag = 0;
4657 bool NeedType = false;
4658 switch (IsLV) { // C99 6.5.16p2
4659 default: assert(0 && "Unknown result from isModifiableLvalue!");
4660 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00004661 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004662 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4663 NeedType = true;
4664 break;
Mike Stump9afab102009-02-19 03:04:26 +00004665 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004666 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4667 NeedType = true;
4668 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00004669 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004670 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4671 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004672 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004673 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4674 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004675 case Expr::MLV_IncompleteType:
4676 case Expr::MLV_IncompleteVoidType:
Douglas Gregorc84d8932009-03-09 16:13:40 +00004677 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssona21e7872009-08-26 23:45:07 +00004678 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
4679 << E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00004680 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004681 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4682 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00004683 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004684 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4685 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00004686 case Expr::MLV_ReadonlyProperty:
4687 Diag = diag::error_readonly_property_assignment;
4688 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00004689 case Expr::MLV_NoSetterProperty:
4690 Diag = diag::error_nosetter_property_assignment;
4691 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004692 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00004693
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004694 SourceRange Assign;
4695 if (Loc != OrigLoc)
4696 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner4c2642c2008-11-18 01:22:49 +00004697 if (NeedType)
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004698 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004699 else
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004700 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004701 return true;
4702}
4703
4704
4705
4706// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00004707QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4708 SourceLocation Loc,
4709 QualType CompoundType) {
4710 // Verify that LHS is a modifiable lvalue, and emit error if not.
4711 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00004712 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00004713
4714 QualType LHSType = LHS->getType();
4715 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00004716
Chris Lattner005ed752008-01-04 18:04:52 +00004717 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004718 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00004719 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004720 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004721 // Special case of NSObject attributes on c-style pointer types.
4722 if (ConvTy == IncompatiblePointer &&
4723 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004724 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004725 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004726 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004727 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00004728
Chris Lattner34c85082008-08-21 18:04:13 +00004729 // If the RHS is a unary plus or minus, check to see if they = and + are
4730 // right next to each other. If so, the user may have typo'd "x =+ 4"
4731 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004732 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00004733 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4734 RHSCheck = ICE->getSubExpr();
4735 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4736 if ((UO->getOpcode() == UnaryOperator::Plus ||
4737 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00004738 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00004739 // Only if the two operators are exactly adjacent.
Chris Lattner55a17242009-03-08 06:51:10 +00004740 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4741 // And there is a space or other character before the subexpr of the
4742 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnerf1e5d4a2009-03-09 07:11:10 +00004743 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4744 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004745 Diag(Loc, diag::warn_not_compound_assign)
4746 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4747 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner55a17242009-03-08 06:51:10 +00004748 }
Chris Lattner34c85082008-08-21 18:04:13 +00004749 }
4750 } else {
4751 // Compound assignment "x += y"
Eli Friedmanb653af42009-05-16 05:56:02 +00004752 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00004753 }
Chris Lattner005ed752008-01-04 18:04:52 +00004754
Chris Lattner1eafdea2008-11-18 01:30:42 +00004755 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4756 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00004757 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004758
Chris Lattner4b009652007-07-25 00:24:17 +00004759 // C99 6.5.16p3: The type of an assignment expression is the type of the
4760 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00004761 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00004762 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4763 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004764 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004765 // operand.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004766 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00004767}
4768
Chris Lattner1eafdea2008-11-18 01:30:42 +00004769// C99 6.5.17
4770QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00004771 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004772 DefaultFunctionArrayConversion(RHS);
Eli Friedman2b128322009-03-23 00:24:07 +00004773
4774 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4775 // incomplete in C++).
4776
Chris Lattner1eafdea2008-11-18 01:30:42 +00004777 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00004778}
4779
4780/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4781/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004782QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4783 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004784 if (Op->isTypeDependent())
4785 return Context.DependentTy;
4786
Chris Lattnere65182c2008-11-21 07:05:48 +00004787 QualType ResType = Op->getType();
4788 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004789
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004790 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4791 // Decrement of bool is not allowed.
4792 if (!isInc) {
4793 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4794 return QualType();
4795 }
4796 // Increment of bool sets it to true, but is deprecated.
4797 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4798 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00004799 // OK!
Steve Naroff79ae19a2009-07-14 18:25:06 +00004800 } else if (ResType->isAnyPointerType()) {
4801 QualType PointeeTy = ResType->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00004802
Chris Lattnere65182c2008-11-21 07:05:48 +00004803 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff329ec222009-07-10 23:34:53 +00004804 if (PointeeTy->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004805 if (getLangOptions().CPlusPlus) {
4806 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4807 << Op->getSourceRange();
4808 return QualType();
4809 }
4810
4811 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00004812 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004813 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004814 if (getLangOptions().CPlusPlus) {
4815 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4816 << Op->getType() << Op->getSourceRange();
4817 return QualType();
4818 }
4819
4820 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004821 << ResType << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004822 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssonb5247af2009-08-26 22:59:12 +00004823 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4824 << Op->getSourceRange()
4825 << ResType))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004826 return QualType();
Fariborz Jahanian4738ac52009-07-16 17:59:14 +00004827 // Diagnose bad cases where we step over interface counts.
4828 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4829 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
4830 << PointeeTy << Op->getSourceRange();
4831 return QualType();
4832 }
Chris Lattnere65182c2008-11-21 07:05:48 +00004833 } else if (ResType->isComplexType()) {
4834 // C99 does not support ++/-- on complex types, we allow as an extension.
4835 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004836 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004837 } else {
4838 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004839 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004840 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00004841 }
Mike Stump9afab102009-02-19 03:04:26 +00004842 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00004843 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00004844 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00004845 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00004846 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00004847}
4848
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004849/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00004850/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004851/// where the declaration is needed for type checking. We only need to
4852/// handle cases when the expression references a function designator
4853/// or is an lvalue. Here are some examples:
4854/// - &(x) => x
4855/// - &*****f => f for f a function designator.
4856/// - &s.xx => s
4857/// - &s.zz[1].yy -> s, if zz is an array
4858/// - *(x + 1) -> x, if x is an array
4859/// - &"123"[2] -> 0
4860/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00004861static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00004862 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00004863 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00004864 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004865 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00004866 case Stmt::MemberExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004867 // If this is an arrow operator, the address is an offset from
4868 // the base's value, so the object the base refers to is
4869 // irrelevant.
Chris Lattner48d7f382008-04-02 04:24:33 +00004870 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00004871 return 0;
Eli Friedman93ecce22009-04-20 08:23:18 +00004872 // Otherwise, the expression refers to a part of the base
Chris Lattner48d7f382008-04-02 04:24:33 +00004873 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004874 case Stmt::ArraySubscriptExprClass: {
Mike Stumpe127ae32009-05-16 07:39:55 +00004875 // FIXME: This code shouldn't be necessary! We should catch the implicit
4876 // promotion of register arrays earlier.
Eli Friedman93ecce22009-04-20 08:23:18 +00004877 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4878 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4879 if (ICE->getSubExpr()->getType()->isArrayType())
4880 return getPrimaryDecl(ICE->getSubExpr());
4881 }
4882 return 0;
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004883 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004884 case Stmt::UnaryOperatorClass: {
4885 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00004886
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004887 switch(UO->getOpcode()) {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004888 case UnaryOperator::Real:
4889 case UnaryOperator::Imag:
4890 case UnaryOperator::Extension:
4891 return getPrimaryDecl(UO->getSubExpr());
4892 default:
4893 return 0;
4894 }
4895 }
Chris Lattner4b009652007-07-25 00:24:17 +00004896 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004897 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00004898 case Stmt::ImplicitCastExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004899 // If the result of an implicit cast is an l-value, we care about
4900 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner48d7f382008-04-02 04:24:33 +00004901 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00004902 default:
4903 return 0;
4904 }
4905}
4906
4907/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00004908/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00004909/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00004910/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00004911/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00004912/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00004913/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00004914QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman93ecce22009-04-20 08:23:18 +00004915 // Make sure to ignore parentheses in subsequent checks
4916 op = op->IgnoreParens();
4917
Douglas Gregore6be68a2008-12-17 22:52:20 +00004918 if (op->isTypeDependent())
4919 return Context.DependentTy;
4920
Steve Naroff9c6c3592008-01-13 17:10:08 +00004921 if (getLangOptions().C99) {
4922 // Implement C99-only parts of addressof rules.
4923 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
4924 if (uOp->getOpcode() == UnaryOperator::Deref)
4925 // Per C99 6.5.3.2, the address of a deref always returns a valid result
4926 // (assuming the deref expression is valid).
4927 return uOp->getSubExpr()->getType();
4928 }
4929 // Technically, there should be a check for array subscript
4930 // expressions here, but the result of one is always an lvalue anyway.
4931 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00004932 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00004933 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00004934
Eli Friedman14ab4c42009-05-16 23:27:50 +00004935 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
4936 // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004937 // The operand must be either an l-value or a function designator
Eli Friedman14ab4c42009-05-16 23:27:50 +00004938 if (!op->getType()->isFunctionType()) {
Chris Lattnera3249072007-11-16 17:46:48 +00004939 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00004940 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
4941 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004942 return QualType();
4943 }
Douglas Gregor531434b2009-05-02 02:18:30 +00004944 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004945 // The operand cannot be a bit-field
4946 Diag(OpLoc, diag::err_typecheck_address_of)
4947 << "bit-field" << op->getSourceRange();
Douglas Gregor82d44772008-12-20 23:49:58 +00004948 return QualType();
Nate Begemana9187ab2009-02-15 22:45:20 +00004949 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
4950 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman93ecce22009-04-20 08:23:18 +00004951 // The operand cannot be an element of a vector
Chris Lattner77d52da2008-11-20 06:06:08 +00004952 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00004953 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004954 return QualType();
Fariborz Jahanianb35984a2009-07-07 18:50:52 +00004955 } else if (isa<ObjCPropertyRefExpr>(op)) {
4956 // cannot take address of a property expression.
4957 Diag(OpLoc, diag::err_typecheck_address_of)
4958 << "property expression" << op->getSourceRange();
4959 return QualType();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004960 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00004961 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00004962 // with the register storage-class specifier.
4963 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
4964 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004965 Diag(OpLoc, diag::err_typecheck_address_of)
4966 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004967 return QualType();
4968 }
Douglas Gregor62f78762009-07-08 20:55:45 +00004969 } else if (isa<OverloadedFunctionDecl>(dcl) ||
4970 isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00004971 return Context.OverloadTy;
Anders Carlsson64371472009-07-08 21:45:58 +00004972 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor5b82d612008-12-10 21:26:49 +00004973 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00004974 // Could be a pointer to member, though, if there is an explicit
4975 // scope qualifier for the class.
4976 if (isa<QualifiedDeclRefExpr>(op)) {
4977 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson64371472009-07-08 21:45:58 +00004978 if (Ctx && Ctx->isRecord()) {
4979 if (FD->getType()->isReferenceType()) {
4980 Diag(OpLoc,
4981 diag::err_cannot_form_pointer_to_member_of_reference_type)
4982 << FD->getDeclName() << FD->getType();
4983 return QualType();
4984 }
4985
Sebastian Redl0c9da212009-02-03 20:19:35 +00004986 return Context.getMemberPointerType(op->getType(),
4987 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson64371472009-07-08 21:45:58 +00004988 }
Sebastian Redl0c9da212009-02-03 20:19:35 +00004989 }
Anders Carlssone9cc4c42009-05-16 21:43:42 +00004990 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopesdf239522008-12-16 22:58:26 +00004991 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00004992 // As above.
Anders Carlssone9cc4c42009-05-16 21:43:42 +00004993 if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
4994 return Context.getMemberPointerType(op->getType(),
4995 Context.getTypeDeclType(MD->getParent()).getTypePtr());
4996 } else if (!isa<FunctionDecl>(dcl))
Chris Lattner4b009652007-07-25 00:24:17 +00004997 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00004998 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00004999
Eli Friedman14ab4c42009-05-16 23:27:50 +00005000 if (lval == Expr::LV_IncompleteVoidType) {
5001 // Taking the address of a void variable is technically illegal, but we
5002 // allow it in cases which are otherwise valid.
5003 // Example: "extern void x; void* y = &x;".
5004 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5005 }
5006
Chris Lattner4b009652007-07-25 00:24:17 +00005007 // If the operand has type "type", the result has type "pointer to type".
5008 return Context.getPointerType(op->getType());
5009}
5010
Chris Lattnerda5c0872008-11-23 09:13:29 +00005011QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005012 if (Op->isTypeDependent())
5013 return Context.DependentTy;
5014
Chris Lattnerda5c0872008-11-23 09:13:29 +00005015 UsualUnaryConversions(Op);
5016 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00005017
Chris Lattnerda5c0872008-11-23 09:13:29 +00005018 // Note that per both C89 and C99, this is always legal, even if ptype is an
5019 // incomplete type or void. It would be possible to warn about dereferencing
5020 // a void pointer, but it's completely well-defined, and such a warning is
5021 // unlikely to catch any mistakes.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00005022 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff9c6c3592008-01-13 17:10:08 +00005023 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00005024
Steve Naroff329ec222009-07-10 23:34:53 +00005025 if (const ObjCObjectPointerType *OPT = Ty->getAsObjCObjectPointerType())
5026 return OPT->getPointeeType();
5027
Chris Lattner77d52da2008-11-20 06:06:08 +00005028 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00005029 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00005030 return QualType();
5031}
5032
5033static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5034 tok::TokenKind Kind) {
5035 BinaryOperator::Opcode Opc;
5036 switch (Kind) {
5037 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00005038 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5039 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00005040 case tok::star: Opc = BinaryOperator::Mul; break;
5041 case tok::slash: Opc = BinaryOperator::Div; break;
5042 case tok::percent: Opc = BinaryOperator::Rem; break;
5043 case tok::plus: Opc = BinaryOperator::Add; break;
5044 case tok::minus: Opc = BinaryOperator::Sub; break;
5045 case tok::lessless: Opc = BinaryOperator::Shl; break;
5046 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5047 case tok::lessequal: Opc = BinaryOperator::LE; break;
5048 case tok::less: Opc = BinaryOperator::LT; break;
5049 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5050 case tok::greater: Opc = BinaryOperator::GT; break;
5051 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5052 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5053 case tok::amp: Opc = BinaryOperator::And; break;
5054 case tok::caret: Opc = BinaryOperator::Xor; break;
5055 case tok::pipe: Opc = BinaryOperator::Or; break;
5056 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5057 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5058 case tok::equal: Opc = BinaryOperator::Assign; break;
5059 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5060 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5061 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5062 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5063 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5064 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5065 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5066 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5067 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5068 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5069 case tok::comma: Opc = BinaryOperator::Comma; break;
5070 }
5071 return Opc;
5072}
5073
5074static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5075 tok::TokenKind Kind) {
5076 UnaryOperator::Opcode Opc;
5077 switch (Kind) {
5078 default: assert(0 && "Unknown unary op!");
5079 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5080 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5081 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5082 case tok::star: Opc = UnaryOperator::Deref; break;
5083 case tok::plus: Opc = UnaryOperator::Plus; break;
5084 case tok::minus: Opc = UnaryOperator::Minus; break;
5085 case tok::tilde: Opc = UnaryOperator::Not; break;
5086 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00005087 case tok::kw___real: Opc = UnaryOperator::Real; break;
5088 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5089 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5090 }
5091 return Opc;
5092}
5093
Douglas Gregord7f915e2008-11-06 23:29:22 +00005094/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5095/// operator @p Opc at location @c TokLoc. This routine only supports
5096/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005097Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5098 unsigned Op,
5099 Expr *lhs, Expr *rhs) {
Eli Friedman3cd92882009-03-28 01:22:36 +00005100 QualType ResultTy; // Result type of the binary operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00005101 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman3cd92882009-03-28 01:22:36 +00005102 // The following two variables are used for compound assignment operators
5103 QualType CompLHSTy; // Type of LHS after promotions for computation
5104 QualType CompResultTy; // Type of computation result
Douglas Gregord7f915e2008-11-06 23:29:22 +00005105
5106 switch (Opc) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00005107 case BinaryOperator::Assign:
5108 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5109 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005110 case BinaryOperator::PtrMemD:
5111 case BinaryOperator::PtrMemI:
5112 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5113 Opc == BinaryOperator::PtrMemI);
5114 break;
5115 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005116 case BinaryOperator::Div:
5117 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5118 break;
5119 case BinaryOperator::Rem:
5120 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5121 break;
5122 case BinaryOperator::Add:
5123 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5124 break;
5125 case BinaryOperator::Sub:
5126 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5127 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005128 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005129 case BinaryOperator::Shr:
5130 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5131 break;
5132 case BinaryOperator::LE:
5133 case BinaryOperator::LT:
5134 case BinaryOperator::GE:
5135 case BinaryOperator::GT:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005136 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005137 break;
5138 case BinaryOperator::EQ:
5139 case BinaryOperator::NE:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005140 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005141 break;
5142 case BinaryOperator::And:
5143 case BinaryOperator::Xor:
5144 case BinaryOperator::Or:
5145 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5146 break;
5147 case BinaryOperator::LAnd:
5148 case BinaryOperator::LOr:
5149 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5150 break;
5151 case BinaryOperator::MulAssign:
5152 case BinaryOperator::DivAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005153 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5154 CompLHSTy = CompResultTy;
5155 if (!CompResultTy.isNull())
5156 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005157 break;
5158 case BinaryOperator::RemAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005159 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5160 CompLHSTy = CompResultTy;
5161 if (!CompResultTy.isNull())
5162 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005163 break;
5164 case BinaryOperator::AddAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005165 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5166 if (!CompResultTy.isNull())
5167 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005168 break;
5169 case BinaryOperator::SubAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005170 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5171 if (!CompResultTy.isNull())
5172 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005173 break;
5174 case BinaryOperator::ShlAssign:
5175 case BinaryOperator::ShrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005176 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5177 CompLHSTy = CompResultTy;
5178 if (!CompResultTy.isNull())
5179 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005180 break;
5181 case BinaryOperator::AndAssign:
5182 case BinaryOperator::XorAssign:
5183 case BinaryOperator::OrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005184 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5185 CompLHSTy = CompResultTy;
5186 if (!CompResultTy.isNull())
5187 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005188 break;
5189 case BinaryOperator::Comma:
5190 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5191 break;
5192 }
5193 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005194 return ExprError();
Eli Friedman3cd92882009-03-28 01:22:36 +00005195 if (CompResultTy.isNull())
Steve Naroff774e4152009-01-21 00:14:39 +00005196 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5197 else
5198 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman3cd92882009-03-28 01:22:36 +00005199 CompLHSTy, CompResultTy,
5200 OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00005201}
5202
Chris Lattner4b009652007-07-25 00:24:17 +00005203// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005204Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5205 tok::TokenKind Kind,
5206 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00005207 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005208 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Chris Lattner4b009652007-07-25 00:24:17 +00005209
Steve Naroff87d58b42007-09-16 03:34:24 +00005210 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5211 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00005212
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005213 if (getLangOptions().CPlusPlus &&
5214 (lhs->getType()->isOverloadableType() ||
5215 rhs->getType()->isOverloadableType())) {
5216 // Find all of the overloaded operators visible from this
5217 // point. We perform both an operator-name lookup from the local
5218 // scope and an argument-dependent lookup based on the types of
5219 // the arguments.
Douglas Gregor3fc092f2009-03-13 00:33:25 +00005220 FunctionSet Functions;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005221 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5222 if (OverOp != OO_None) {
5223 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5224 Functions);
5225 Expr *Args[2] = { lhs, rhs };
5226 DeclarationName OpName
5227 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5228 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregor70d26122008-11-12 17:17:38 +00005229 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005230
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005231 // Build the (potentially-overloaded, potentially-dependent)
5232 // binary operation.
5233 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005234 }
5235
Douglas Gregord7f915e2008-11-06 23:29:22 +00005236 // Build a built-in binary operation.
5237 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00005238}
5239
Douglas Gregorc78182d2009-03-13 23:49:33 +00005240Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
5241 unsigned OpcIn,
5242 ExprArg InputArg) {
5243 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005244
Mike Stumpe127ae32009-05-16 07:39:55 +00005245 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorc78182d2009-03-13 23:49:33 +00005246 Expr *Input = (Expr *)InputArg.get();
Chris Lattner4b009652007-07-25 00:24:17 +00005247 QualType resultType;
5248 switch (Opc) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00005249 case UnaryOperator::OffsetOf:
5250 assert(false && "Invalid unary operator");
5251 break;
5252
Chris Lattner4b009652007-07-25 00:24:17 +00005253 case UnaryOperator::PreInc:
5254 case UnaryOperator::PreDec:
Eli Friedman79341142009-07-22 22:25:00 +00005255 case UnaryOperator::PostInc:
5256 case UnaryOperator::PostDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00005257 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman79341142009-07-22 22:25:00 +00005258 Opc == UnaryOperator::PreInc ||
5259 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00005260 break;
Mike Stump9afab102009-02-19 03:04:26 +00005261 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00005262 resultType = CheckAddressOfOperand(Input, OpLoc);
5263 break;
Mike Stump9afab102009-02-19 03:04:26 +00005264 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00005265 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00005266 resultType = CheckIndirectionOperand(Input, OpLoc);
5267 break;
5268 case UnaryOperator::Plus:
5269 case UnaryOperator::Minus:
5270 UsualUnaryConversions(Input);
5271 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005272 if (resultType->isDependentType())
5273 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005274 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5275 break;
5276 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5277 resultType->isEnumeralType())
5278 break;
5279 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5280 Opc == UnaryOperator::Plus &&
5281 resultType->isPointerType())
5282 break;
5283
Sebastian Redl8b769972009-01-19 00:08:26 +00005284 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5285 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005286 case UnaryOperator::Not: // bitwise complement
5287 UsualUnaryConversions(Input);
5288 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005289 if (resultType->isDependentType())
5290 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00005291 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5292 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5293 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00005294 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00005295 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00005296 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00005297 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5298 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005299 break;
5300 case UnaryOperator::LNot: // logical negation
5301 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
5302 DefaultFunctionArrayConversion(Input);
5303 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005304 if (resultType->isDependentType())
5305 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005306 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00005307 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5308 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005309 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00005310 // In C++, it's bool. C++ 5.3.1p8
5311 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00005312 break;
Chris Lattner03931a72007-08-24 21:16:53 +00005313 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00005314 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00005315 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00005316 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005317 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00005318 resultType = Input->getType();
5319 break;
5320 }
5321 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00005322 return ExprError();
Douglas Gregorc78182d2009-03-13 23:49:33 +00005323
5324 InputArg.release();
Steve Naroff774e4152009-01-21 00:14:39 +00005325 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005326}
5327
Douglas Gregorc78182d2009-03-13 23:49:33 +00005328// Unary Operators. 'Tok' is the token for the operator.
5329Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5330 tok::TokenKind Op, ExprArg input) {
5331 Expr *Input = (Expr*)input.get();
5332 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5333
5334 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5335 // Find all of the overloaded operators visible from this
5336 // point. We perform both an operator-name lookup from the local
5337 // scope and an argument-dependent lookup based on the types of
5338 // the arguments.
5339 FunctionSet Functions;
5340 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5341 if (OverOp != OO_None) {
5342 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5343 Functions);
5344 DeclarationName OpName
5345 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5346 ArgumentDependentLookup(OpName, &Input, 1, Functions);
5347 }
5348
5349 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5350 }
5351
5352 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5353}
5354
Steve Naroff5cbb02f2007-09-16 14:56:35 +00005355/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005356Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5357 SourceLocation LabLoc,
5358 IdentifierInfo *LabelII) {
Chris Lattner4b009652007-07-25 00:24:17 +00005359 // Look up the record for this label identifier.
Chris Lattner2616d8c2009-04-18 20:01:55 +00005360 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00005361
Daniel Dunbar879788d2008-08-04 16:51:22 +00005362 // If we haven't seen this label yet, create a forward reference. It
5363 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffb88d81c2009-03-13 15:38:40 +00005364 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00005365 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00005366
Chris Lattner4b009652007-07-25 00:24:17 +00005367 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005368 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5369 Context.getPointerType(Context.VoidTy)));
Chris Lattner4b009652007-07-25 00:24:17 +00005370}
5371
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005372Sema::OwningExprResult
5373Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5374 SourceLocation RPLoc) { // "({..})"
5375 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner4b009652007-07-25 00:24:17 +00005376 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5377 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5378
Eli Friedmanbc941e12009-01-24 23:09:00 +00005379 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattneraa257592009-04-25 19:11:05 +00005380 if (isFileScope)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005381 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmanbc941e12009-01-24 23:09:00 +00005382
Chris Lattner4b009652007-07-25 00:24:17 +00005383 // FIXME: there are a variety of strange constraints to enforce here, for
5384 // example, it is not possible to goto into a stmt expression apparently.
5385 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00005386
Chris Lattner4b009652007-07-25 00:24:17 +00005387 // If there are sub stmts in the compound stmt, take the type of the last one
5388 // as the type of the stmtexpr.
5389 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00005390
Chris Lattner200964f2008-07-26 19:51:01 +00005391 if (!Compound->body_empty()) {
5392 Stmt *LastStmt = Compound->body_back();
5393 // If LastStmt is a label, skip down through into the body.
5394 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5395 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00005396
Chris Lattner200964f2008-07-26 19:51:01 +00005397 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00005398 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00005399 }
Mike Stump9afab102009-02-19 03:04:26 +00005400
Eli Friedman2b128322009-03-23 00:24:07 +00005401 // FIXME: Check that expression type is complete/non-abstract; statement
5402 // expressions are not lvalues.
5403
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005404 substmt.release();
5405 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005406}
Steve Naroff63bad2d2007-08-01 22:05:33 +00005407
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005408Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5409 SourceLocation BuiltinLoc,
5410 SourceLocation TypeLoc,
5411 TypeTy *argty,
5412 OffsetOfComponent *CompPtr,
5413 unsigned NumComponents,
5414 SourceLocation RPLoc) {
5415 // FIXME: This function leaks all expressions in the offset components on
5416 // error.
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005417 // FIXME: Preserve type source info.
5418 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005419 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00005420
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005421 bool Dependent = ArgTy->isDependentType();
5422
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005423 // We must have at least one component that refers to the type, and the first
5424 // one is known to be a field designator. Verify that the ArgTy represents
5425 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005426 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005427 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump9afab102009-02-19 03:04:26 +00005428
Eli Friedman2b128322009-03-23 00:24:07 +00005429 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5430 // with an incomplete type would be illegal.
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00005431
Eli Friedman342d9432009-02-27 06:44:11 +00005432 // Otherwise, create a null pointer as the base, and iteratively process
5433 // the offsetof designators.
5434 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5435 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005436 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman342d9432009-02-27 06:44:11 +00005437 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00005438
Chris Lattnerb37522e2007-08-31 21:49:13 +00005439 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5440 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00005441 // FIXME: This diagnostic isn't actually visible because the location is in
5442 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00005443 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00005444 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5445 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00005446
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005447 if (!Dependent) {
Eli Friedmanc24ae002009-05-03 21:22:18 +00005448 bool DidWarnAboutNonPOD = false;
Anders Carlsson68c926c2009-05-02 18:36:10 +00005449
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005450 // FIXME: Dependent case loses a lot of information here. And probably
5451 // leaks like a sieve.
5452 for (unsigned i = 0; i != NumComponents; ++i) {
5453 const OffsetOfComponent &OC = CompPtr[i];
5454 if (OC.isBrackets) {
5455 // Offset of an array sub-field. TODO: Should we allow vector elements?
5456 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5457 if (!AT) {
5458 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005459 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5460 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005461 }
5462
5463 // FIXME: C++: Verify that operator[] isn't overloaded.
5464
Eli Friedman342d9432009-02-27 06:44:11 +00005465 // Promote the array so it looks more like a normal array subscript
5466 // expression.
5467 DefaultFunctionArrayConversion(Res);
5468
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005469 // C99 6.5.2.1p1
5470 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005471 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005472 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005473 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner7264d212009-04-25 22:50:55 +00005474 diag::err_typecheck_subscript_not_integer)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005475 << Idx->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005476
5477 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5478 OC.LocEnd);
5479 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005480 }
Mike Stump9afab102009-02-19 03:04:26 +00005481
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00005482 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005483 if (!RC) {
5484 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005485 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5486 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005487 }
Chris Lattner2af6a802007-08-30 17:59:59 +00005488
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005489 // Get the decl corresponding to this.
5490 RecordDecl *RD = RC->getDecl();
Anders Carlsson356946e2009-05-01 23:20:30 +00005491 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson68c926c2009-05-02 18:36:10 +00005492 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonbbceaea2009-05-02 17:45:47 +00005493 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5494 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5495 << Res->getType());
Anders Carlsson68c926c2009-05-02 18:36:10 +00005496 DidWarnAboutNonPOD = true;
5497 }
Anders Carlsson356946e2009-05-01 23:20:30 +00005498 }
5499
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005500 FieldDecl *MemberDecl
5501 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
5502 LookupMemberName)
5503 .getAsDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005504 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005505 if (!MemberDecl)
Anders Carlsson4355a392009-08-30 00:54:35 +00005506 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member_deprecated)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005507 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump9afab102009-02-19 03:04:26 +00005508
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005509 // FIXME: C++: Verify that MemberDecl isn't a static field.
5510 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman35719da2009-04-26 20:50:44 +00005511 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonc154a722009-05-01 19:30:39 +00005512 Res = BuildAnonymousStructUnionMemberReference(
5513 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedman35719da2009-04-26 20:50:44 +00005514 } else {
5515 // MemberDecl->getType() doesn't get the right qualifiers, but it
5516 // doesn't matter here.
5517 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5518 MemberDecl->getType().getNonReferenceType());
5519 }
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005520 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005521 }
Mike Stump9afab102009-02-19 03:04:26 +00005522
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005523 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5524 Context.getSizeType(), BuiltinLoc));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005525}
5526
5527
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005528Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5529 TypeTy *arg1,TypeTy *arg2,
5530 SourceLocation RPLoc) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005531 // FIXME: Preserve type source info.
5532 QualType argT1 = GetTypeFromParser(arg1);
5533 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00005534
Steve Naroff63bad2d2007-08-01 22:05:33 +00005535 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00005536
Douglas Gregore6211502009-05-19 22:28:02 +00005537 if (getLangOptions().CPlusPlus) {
5538 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5539 << SourceRange(BuiltinLoc, RPLoc);
5540 return ExprError();
5541 }
5542
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005543 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5544 argT1, argT2, RPLoc));
Steve Naroff63bad2d2007-08-01 22:05:33 +00005545}
5546
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005547Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5548 ExprArg cond,
5549 ExprArg expr1, ExprArg expr2,
5550 SourceLocation RPLoc) {
5551 Expr *CondExpr = static_cast<Expr*>(cond.get());
5552 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5553 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump9afab102009-02-19 03:04:26 +00005554
Steve Naroff93c53012007-08-03 21:21:27 +00005555 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5556
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005557 QualType resType;
Douglas Gregordd4ae3f2009-05-19 22:43:30 +00005558 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005559 resType = Context.DependentTy;
5560 } else {
5561 // The conditional expression is required to be a constant expression.
5562 llvm::APSInt condEval(32);
5563 SourceLocation ExpLoc;
5564 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005565 return ExprError(Diag(ExpLoc,
5566 diag::err_typecheck_choose_expr_requires_constant)
5567 << CondExpr->getSourceRange());
Steve Naroff93c53012007-08-03 21:21:27 +00005568
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005569 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5570 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5571 }
5572
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005573 cond.release(); expr1.release(); expr2.release();
5574 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5575 resType, RPLoc));
Steve Naroff93c53012007-08-03 21:21:27 +00005576}
5577
Steve Naroff52a81c02008-09-03 18:15:37 +00005578//===----------------------------------------------------------------------===//
5579// Clang Extensions.
5580//===----------------------------------------------------------------------===//
5581
5582/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00005583void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005584 // Analyze block parameters.
5585 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00005586
Steve Naroff52a81c02008-09-03 18:15:37 +00005587 // Add BSI to CurBlock.
5588 BSI->PrevBlockInfo = CurBlock;
5589 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00005590
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005591 BSI->ReturnType = QualType();
Steve Naroff52a81c02008-09-03 18:15:37 +00005592 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00005593 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarc7ef2b92009-07-29 01:59:17 +00005594 BSI->hasPrototype = false;
Chris Lattnere7765e12009-04-19 05:28:12 +00005595 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5596 CurFunctionNeedsScopeChecking = false;
Mike Stump9afab102009-02-19 03:04:26 +00005597
Steve Naroff52059382008-10-10 01:28:17 +00005598 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00005599 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00005600}
5601
Mike Stumpc1fddff2009-02-04 22:31:32 +00005602void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpea3d74e2009-05-07 18:43:07 +00005603 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stumpc1fddff2009-02-04 22:31:32 +00005604
5605 if (ParamInfo.getNumTypeObjects() == 0
5606 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005607 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stumpc1fddff2009-02-04 22:31:32 +00005608 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5609
Mike Stump458287d2009-04-28 01:10:27 +00005610 if (T->isArrayType()) {
5611 Diag(ParamInfo.getSourceRange().getBegin(),
5612 diag::err_block_returns_array);
5613 return;
5614 }
5615
Mike Stumpc1fddff2009-02-04 22:31:32 +00005616 // The parameter list is optional, if there was none, assume ().
5617 if (!T->isFunctionType())
5618 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5619
5620 CurBlock->hasPrototype = true;
5621 CurBlock->isVariadic = false;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005622 // Check for a valid sentinel attribute on this block.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005623 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005624 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005625 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005626 // FIXME: remove the attribute.
5627 }
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005628 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
5629
5630 // Do not allow returning a objc interface by-value.
5631 if (RetTy->isObjCInterfaceType()) {
5632 Diag(ParamInfo.getSourceRange().getBegin(),
5633 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5634 return;
5635 }
Mike Stumpc1fddff2009-02-04 22:31:32 +00005636 return;
5637 }
5638
Steve Naroff52a81c02008-09-03 18:15:37 +00005639 // Analyze arguments to block.
5640 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5641 "Not a function declarator!");
5642 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00005643
Steve Naroff52059382008-10-10 01:28:17 +00005644 CurBlock->hasPrototype = FTI.hasPrototype;
5645 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00005646
Steve Naroff52a81c02008-09-03 18:15:37 +00005647 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5648 // no arguments, not a function that takes a single void argument.
5649 if (FTI.hasPrototype &&
5650 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner5261d0c2009-03-28 19:18:32 +00005651 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5652 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005653 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00005654 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00005655 } else if (FTI.hasPrototype) {
5656 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner5261d0c2009-03-28 19:18:32 +00005657 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff52059382008-10-10 01:28:17 +00005658 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00005659 }
Jay Foad9e6bef42009-05-21 09:52:38 +00005660 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005661 CurBlock->Params.size());
Fariborz Jahanian536f73d2009-05-19 17:08:59 +00005662 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005663 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff52059382008-10-10 01:28:17 +00005664 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5665 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5666 // If this has an identifier, add it to the scope stack.
5667 if ((*AI)->getIdentifier())
5668 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005669
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005670 // Check for a valid sentinel attribute on this block.
Douglas Gregor98da6ae2009-06-18 16:11:24 +00005671 if (!CurBlock->isVariadic &&
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005672 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005673 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005674 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005675 // FIXME: remove the attribute.
5676 }
5677
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005678 // Analyze the return type.
5679 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5680 QualType RetTy = T->getAsFunctionType()->getResultType();
5681
5682 // Do not allow returning a objc interface by-value.
5683 if (RetTy->isObjCInterfaceType()) {
5684 Diag(ParamInfo.getSourceRange().getBegin(),
5685 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5686 } else if (!RetTy->isDependentType())
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005687 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00005688}
5689
5690/// ActOnBlockError - If there is an error parsing a block, this callback
5691/// is invoked to pop the information about the block from the action impl.
5692void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5693 // Ensure that CurBlock is deleted.
5694 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00005695
Chris Lattnere7765e12009-04-19 05:28:12 +00005696 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5697
Steve Naroff52a81c02008-09-03 18:15:37 +00005698 // Pop off CurBlock, handle nested blocks.
Chris Lattnereb4d4a52009-04-21 22:38:46 +00005699 PopDeclContext();
Steve Naroff52a81c02008-09-03 18:15:37 +00005700 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff52a81c02008-09-03 18:15:37 +00005701 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff52a81c02008-09-03 18:15:37 +00005702}
5703
5704/// ActOnBlockStmtExpr - This is called when the body of a block statement
5705/// literal was successfully completed. ^(int x){...}
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005706Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5707 StmtArg body, Scope *CurScope) {
Chris Lattnerc14c7f02009-03-27 04:18:06 +00005708 // If blocks are disabled, emit an error.
5709 if (!LangOpts.Blocks)
5710 Diag(CaretLoc, diag::err_blocks_disable);
5711
Steve Naroff52a81c02008-09-03 18:15:37 +00005712 // Ensure that CurBlock is deleted.
5713 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff52a81c02008-09-03 18:15:37 +00005714
Steve Naroff52059382008-10-10 01:28:17 +00005715 PopDeclContext();
5716
Steve Naroff52a81c02008-09-03 18:15:37 +00005717 // Pop off CurBlock, handle nested blocks.
5718 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00005719
Steve Naroff52a81c02008-09-03 18:15:37 +00005720 QualType RetTy = Context.VoidTy;
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005721 if (!BSI->ReturnType.isNull())
5722 RetTy = BSI->ReturnType;
Mike Stump9afab102009-02-19 03:04:26 +00005723
Steve Naroff52a81c02008-09-03 18:15:37 +00005724 llvm::SmallVector<QualType, 8> ArgTypes;
5725 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5726 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00005727
Mike Stump8e288f42009-07-28 22:04:01 +00005728 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff52a81c02008-09-03 18:15:37 +00005729 QualType BlockTy;
5730 if (!BSI->hasPrototype)
Mike Stump8e288f42009-07-28 22:04:01 +00005731 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5732 NoReturn);
Steve Naroff52a81c02008-09-03 18:15:37 +00005733 else
Jay Foad9e6bef42009-05-21 09:52:38 +00005734 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump8e288f42009-07-28 22:04:01 +00005735 BSI->isVariadic, 0, false, false, 0, 0,
5736 NoReturn);
Mike Stump9afab102009-02-19 03:04:26 +00005737
Eli Friedman2b128322009-03-23 00:24:07 +00005738 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregor98189262009-06-19 23:52:42 +00005739 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff52a81c02008-09-03 18:15:37 +00005740 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00005741
Chris Lattnere7765e12009-04-19 05:28:12 +00005742 // If needed, diagnose invalid gotos and switches in the block.
5743 if (CurFunctionNeedsScopeChecking)
5744 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5745 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5746
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005747 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump8e288f42009-07-28 22:04:01 +00005748 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005749 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5750 BSI->hasBlockDeclRefExprs));
Steve Naroff52a81c02008-09-03 18:15:37 +00005751}
5752
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005753Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5754 ExprArg expr, TypeTy *type,
5755 SourceLocation RPLoc) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005756 QualType T = GetTypeFromParser(type);
Chris Lattnerda139482009-04-05 15:49:53 +00005757 Expr *E = static_cast<Expr*>(expr.get());
5758 Expr *OrigExpr = E;
5759
Anders Carlsson36760332007-10-15 20:28:48 +00005760 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005761
5762 // Get the va_list type
5763 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman6f6e8922009-05-16 12:46:54 +00005764 if (VaListType->isArrayType()) {
5765 // Deal with implicit array decay; for example, on x86-64,
5766 // va_list is an array, but it's supposed to decay to
5767 // a pointer for va_arg.
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005768 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman6f6e8922009-05-16 12:46:54 +00005769 // Make sure the input expression also decays appropriately.
5770 UsualUnaryConversions(E);
5771 } else {
5772 // Otherwise, the va_list argument must be an l-value because
5773 // it is modified by va_arg.
Douglas Gregor25990972009-05-19 23:10:31 +00005774 if (!E->isTypeDependent() &&
5775 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman6f6e8922009-05-16 12:46:54 +00005776 return ExprError();
5777 }
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005778
Douglas Gregor25990972009-05-19 23:10:31 +00005779 if (!E->isTypeDependent() &&
5780 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005781 return ExprError(Diag(E->getLocStart(),
5782 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerda139482009-04-05 15:49:53 +00005783 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner89a72c52009-04-05 00:59:53 +00005784 }
Mike Stump9afab102009-02-19 03:04:26 +00005785
Eli Friedman2b128322009-03-23 00:24:07 +00005786 // FIXME: Check that type is complete/non-abstract
Anders Carlsson36760332007-10-15 20:28:48 +00005787 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00005788
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005789 expr.release();
5790 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5791 RPLoc));
Anders Carlsson36760332007-10-15 20:28:48 +00005792}
5793
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005794Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregorad4b3792008-11-29 04:51:27 +00005795 // The type of __null will be int or long, depending on the size of
5796 // pointers on the target.
5797 QualType Ty;
5798 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5799 Ty = Context.IntTy;
5800 else
5801 Ty = Context.LongTy;
5802
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005803 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregorad4b3792008-11-29 04:51:27 +00005804}
5805
Chris Lattner005ed752008-01-04 18:04:52 +00005806bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5807 SourceLocation Loc,
5808 QualType DstType, QualType SrcType,
5809 Expr *SrcExpr, const char *Flavor) {
5810 // Decode the result (notice that AST's are still created for extensions).
5811 bool isInvalid = false;
5812 unsigned DiagKind;
5813 switch (ConvTy) {
5814 default: assert(0 && "Unknown conversion type");
5815 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005816 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00005817 DiagKind = diag::ext_typecheck_convert_pointer_int;
5818 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005819 case IntToPointer:
5820 DiagKind = diag::ext_typecheck_convert_int_pointer;
5821 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005822 case IncompatiblePointer:
5823 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5824 break;
Eli Friedman6ca28cb2009-03-22 23:59:44 +00005825 case IncompatiblePointerSign:
5826 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5827 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005828 case FunctionVoidPointer:
5829 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5830 break;
5831 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00005832 // If the qualifiers lost were because we were applying the
5833 // (deprecated) C++ conversion from a string literal to a char*
5834 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
5835 // Ideally, this check would be performed in
5836 // CheckPointerTypesForAssignment. However, that would require a
5837 // bit of refactoring (so that the second argument is an
5838 // expression, rather than a type), which should be done as part
5839 // of a larger effort to fix CheckPointerTypesForAssignment for
5840 // C++ semantics.
5841 if (getLangOptions().CPlusPlus &&
5842 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5843 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00005844 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5845 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005846 case IntToBlockPointer:
5847 DiagKind = diag::err_int_to_block_pointer;
5848 break;
5849 case IncompatibleBlockPointer:
Mike Stumpd331e752009-04-21 22:51:42 +00005850 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005851 break;
Steve Naroff19608432008-10-14 22:18:38 +00005852 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00005853 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00005854 // it can give a more specific diagnostic.
5855 DiagKind = diag::warn_incompatible_qualified_id;
5856 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00005857 case IncompatibleVectors:
5858 DiagKind = diag::warn_incompatible_vectors;
5859 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005860 case Incompatible:
5861 DiagKind = diag::err_typecheck_convert_incompatible;
5862 isInvalid = true;
5863 break;
5864 }
Mike Stump9afab102009-02-19 03:04:26 +00005865
Chris Lattner271d4c22008-11-24 05:29:24 +00005866 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5867 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00005868 return isInvalid;
5869}
Anders Carlssond5201b92008-11-30 19:50:32 +00005870
Chris Lattnereec8ae22009-04-25 21:59:05 +00005871bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmance329412009-04-25 22:26:58 +00005872 llvm::APSInt ICEResult;
5873 if (E->isIntegerConstantExpr(ICEResult, Context)) {
5874 if (Result)
5875 *Result = ICEResult;
5876 return false;
5877 }
5878
Anders Carlssond5201b92008-11-30 19:50:32 +00005879 Expr::EvalResult EvalResult;
5880
Mike Stump9afab102009-02-19 03:04:26 +00005881 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00005882 EvalResult.HasSideEffects) {
5883 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5884
5885 if (EvalResult.Diag) {
5886 // We only show the note if it's not the usual "invalid subexpression"
5887 // or if it's actually in a subexpression.
5888 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5889 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5890 Diag(EvalResult.DiagLoc, EvalResult.Diag);
5891 }
Mike Stump9afab102009-02-19 03:04:26 +00005892
Anders Carlssond5201b92008-11-30 19:50:32 +00005893 return true;
5894 }
5895
Eli Friedmance329412009-04-25 22:26:58 +00005896 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5897 E->getSourceRange();
Anders Carlssond5201b92008-11-30 19:50:32 +00005898
Eli Friedmance329412009-04-25 22:26:58 +00005899 if (EvalResult.Diag &&
5900 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5901 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump9afab102009-02-19 03:04:26 +00005902
Anders Carlssond5201b92008-11-30 19:50:32 +00005903 if (Result)
5904 *Result = EvalResult.Val.getInt();
5905 return false;
5906}
Douglas Gregor98189262009-06-19 23:52:42 +00005907
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005908Sema::ExpressionEvaluationContext
5909Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
5910 // Introduce a new set of potentially referenced declarations to the stack.
5911 if (NewContext == PotentiallyPotentiallyEvaluated)
5912 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
5913
5914 std::swap(ExprEvalContext, NewContext);
5915 return NewContext;
5916}
5917
5918void
5919Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
5920 ExpressionEvaluationContext NewContext) {
5921 ExprEvalContext = NewContext;
5922
5923 if (OldContext == PotentiallyPotentiallyEvaluated) {
5924 // Mark any remaining declarations in the current position of the stack
5925 // as "referenced". If they were not meant to be referenced, semantic
5926 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
5927 PotentiallyReferencedDecls RemainingDecls;
5928 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
5929 PotentiallyReferencedDeclStack.pop_back();
5930
5931 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
5932 IEnd = RemainingDecls.end();
5933 I != IEnd; ++I)
5934 MarkDeclarationReferenced(I->first, I->second);
5935 }
5936}
Douglas Gregor98189262009-06-19 23:52:42 +00005937
5938/// \brief Note that the given declaration was referenced in the source code.
5939///
5940/// This routine should be invoke whenever a given declaration is referenced
5941/// in the source code, and where that reference occurred. If this declaration
5942/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
5943/// C99 6.9p3), then the declaration will be marked as used.
5944///
5945/// \param Loc the location where the declaration was referenced.
5946///
5947/// \param D the declaration that has been referenced by the source code.
5948void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
5949 assert(D && "No declaration?");
5950
Douglas Gregorcad27f62009-06-22 23:06:13 +00005951 if (D->isUsed())
5952 return;
5953
Douglas Gregor98189262009-06-19 23:52:42 +00005954 // Mark a parameter declaration "used", regardless of whether we're in a
5955 // template or not.
5956 if (isa<ParmVarDecl>(D))
5957 D->setUsed(true);
5958
5959 // Do not mark anything as "used" within a dependent context; wait for
5960 // an instantiation.
5961 if (CurContext->isDependentContext())
5962 return;
5963
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005964 switch (ExprEvalContext) {
5965 case Unevaluated:
5966 // We are in an expression that is not potentially evaluated; do nothing.
5967 return;
5968
5969 case PotentiallyEvaluated:
5970 // We are in a potentially-evaluated expression, so this declaration is
5971 // "used"; handle this below.
5972 break;
5973
5974 case PotentiallyPotentiallyEvaluated:
5975 // We are in an expression that may be potentially evaluated; queue this
5976 // declaration reference until we know whether the expression is
5977 // potentially evaluated.
5978 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
5979 return;
5980 }
5981
Douglas Gregor98189262009-06-19 23:52:42 +00005982 // Note that this declaration has been used.
Fariborz Jahanian8915a3d2009-06-22 17:30:33 +00005983 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00005984 unsigned TypeQuals;
Fariborz Jahanian2f5a0a32009-06-22 20:37:23 +00005985 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
5986 if (!Constructor->isUsed())
5987 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump90fc78e2009-08-04 21:02:39 +00005988 } else if (Constructor->isImplicit() &&
5989 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00005990 if (!Constructor->isUsed())
5991 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
5992 }
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00005993 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
5994 if (Destructor->isImplicit() && !Destructor->isUsed())
5995 DefineImplicitDestructor(Loc, Destructor);
5996
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00005997 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
5998 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
5999 MethodDecl->getOverloadedOperator() == OO_Equal) {
6000 if (!MethodDecl->isUsed())
6001 DefineImplicitOverloadedAssign(Loc, MethodDecl);
6002 }
6003 }
Fariborz Jahanianb12bd432009-06-24 22:09:44 +00006004 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00006005 // Implicit instantiation of function templates and member functions of
6006 // class templates.
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00006007 if (!Function->getBody()) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00006008 // FIXME: distinguish between implicit instantiations of function
6009 // templates and explicit specializations (the latter don't get
6010 // instantiated, naturally).
6011 if (Function->getInstantiatedFromMemberFunction() ||
6012 Function->getPrimaryTemplate())
Douglas Gregordcdb3842009-06-30 17:20:14 +00006013 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregorcad27f62009-06-22 23:06:13 +00006014 }
6015
6016
Douglas Gregor98189262009-06-19 23:52:42 +00006017 // FIXME: keep track of references to static functions
Douglas Gregor98189262009-06-19 23:52:42 +00006018 Function->setUsed(true);
6019 return;
Douglas Gregorcad27f62009-06-22 23:06:13 +00006020 }
Douglas Gregor98189262009-06-19 23:52:42 +00006021
6022 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor181fe792009-07-24 20:34:43 +00006023 // Implicit instantiation of static data members of class templates.
6024 // FIXME: distinguish between implicit instantiations (which we need to
6025 // actually instantiate) and explicit specializations.
6026 if (Var->isStaticDataMember() &&
6027 Var->getInstantiatedFromStaticDataMember())
6028 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6029
Douglas Gregor98189262009-06-19 23:52:42 +00006030 // FIXME: keep track of references to static data?
Douglas Gregor181fe792009-07-24 20:34:43 +00006031
Douglas Gregor98189262009-06-19 23:52:42 +00006032 D->setUsed(true);
Douglas Gregor181fe792009-07-24 20:34:43 +00006033 return;
6034}
Douglas Gregor98189262009-06-19 23:52:42 +00006035}
6036