blob: ee3ef04084e1c125ed7d7853dfd3a8bb21bf0927 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
Chris Lattner299b8842008-07-25 21:10:04 +000029//===----------------------------------------------------------------------===//
30// Standard Promotions and Conversions
31//===----------------------------------------------------------------------===//
32
Chris Lattner299b8842008-07-25 21:10:04 +000033/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
34void Sema::DefaultFunctionArrayConversion(Expr *&E) {
35 QualType Ty = E->getType();
36 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
37
Chris Lattner299b8842008-07-25 21:10:04 +000038 if (Ty->isFunctionType())
39 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +000040 else if (Ty->isArrayType()) {
41 // In C90 mode, arrays only promote to pointers if the array expression is
42 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
43 // type 'array of type' is converted to an expression that has type 'pointer
44 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
45 // that has type 'array of type' ...". The relevant change is "an lvalue"
46 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +000047 //
48 // C++ 4.2p1:
49 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
50 // T" can be converted to an rvalue of type "pointer to T".
51 //
52 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
53 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +000054 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
55 }
Chris Lattner299b8842008-07-25 21:10:04 +000056}
57
58/// UsualUnaryConversions - Performs various conversions that are common to most
59/// operators (C99 6.3). The conversions of array and function types are
60/// sometimes surpressed. For example, the array->pointer conversion doesn't
61/// apply if the array is an argument to the sizeof or address (&) operators.
62/// In these instances, this routine should *not* be called.
63Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
64 QualType Ty = Expr->getType();
65 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
66
Chris Lattner299b8842008-07-25 21:10:04 +000067 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
68 ImpCastExprToType(Expr, Context.IntTy);
69 else
70 DefaultFunctionArrayConversion(Expr);
71
72 return Expr;
73}
74
Chris Lattner9305c3d2008-07-25 22:25:12 +000075/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
76/// do not have a prototype. Arguments that have type float are promoted to
77/// double. All other argument types are converted by UsualUnaryConversions().
78void Sema::DefaultArgumentPromotion(Expr *&Expr) {
79 QualType Ty = Expr->getType();
80 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
81
82 // If this is a 'float' (CVR qualified or typedef) promote to double.
83 if (const BuiltinType *BT = Ty->getAsBuiltinType())
84 if (BT->getKind() == BuiltinType::Float)
85 return ImpCastExprToType(Expr, Context.DoubleTy);
86
87 UsualUnaryConversions(Expr);
88}
89
Anders Carlsson4b8e38c2009-01-16 16:48:51 +000090// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
91// will warn if the resulting type is not a POD type.
92void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT)
93
94{
95 DefaultArgumentPromotion(Expr);
96
97 if (!Expr->getType()->isPODType()) {
98 Diag(Expr->getLocStart(),
99 diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
100 Expr->getType() << CT;
101 }
102}
103
104
Chris Lattner299b8842008-07-25 21:10:04 +0000105/// UsualArithmeticConversions - Performs various conversions that are common to
106/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
107/// routine returns the first non-arithmetic type found. The client is
108/// responsible for emitting appropriate error diagnostics.
109/// FIXME: verify the conversion rules for "complex int" are consistent with
110/// GCC.
111QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
112 bool isCompAssign) {
113 if (!isCompAssign) {
114 UsualUnaryConversions(lhsExpr);
115 UsualUnaryConversions(rhsExpr);
116 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000117
Chris Lattner299b8842008-07-25 21:10:04 +0000118 // For conversion purposes, we ignore any qualifiers.
119 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000120 QualType lhs =
121 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
122 QualType rhs =
123 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000124
125 // If both types are identical, no conversion is needed.
126 if (lhs == rhs)
127 return lhs;
128
129 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
130 // The caller can deal with this (e.g. pointer + int).
131 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
132 return lhs;
133
134 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
135 if (!isCompAssign) {
136 ImpCastExprToType(lhsExpr, destType);
137 ImpCastExprToType(rhsExpr, destType);
138 }
139 return destType;
140}
141
142QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
143 // Perform the usual unary conversions. We do this early so that
144 // integral promotions to "int" can allow us to exit early, in the
145 // lhs == rhs check. Also, for conversion purposes, we ignore any
146 // qualifiers. For example, "const float" and "float" are
147 // equivalent.
Douglas Gregor3d4492e2008-11-13 20:12:29 +0000148 if (lhs->isPromotableIntegerType()) lhs = Context.IntTy;
149 else lhs = lhs.getUnqualifiedType();
150 if (rhs->isPromotableIntegerType()) rhs = Context.IntTy;
151 else rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000152
Chris Lattner299b8842008-07-25 21:10:04 +0000153 // If both types are identical, no conversion is needed.
154 if (lhs == rhs)
155 return lhs;
156
157 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
158 // The caller can deal with this (e.g. pointer + int).
159 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
160 return lhs;
161
162 // At this point, we have two different arithmetic types.
163
164 // Handle complex types first (C99 6.3.1.8p1).
165 if (lhs->isComplexType() || rhs->isComplexType()) {
166 // if we have an integer operand, the result is the complex type.
167 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
168 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000169 return lhs;
170 }
171 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
172 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000173 return rhs;
174 }
175 // This handles complex/complex, complex/float, or float/complex.
176 // When both operands are complex, the shorter operand is converted to the
177 // type of the longer, and that is the type of the result. This corresponds
178 // to what is done when combining two real floating-point operands.
179 // The fun begins when size promotion occur across type domains.
180 // From H&S 6.3.4: When one operand is complex and the other is a real
181 // floating-point type, the less precise type is converted, within it's
182 // real or complex domain, to the precision of the other type. For example,
183 // when combining a "long double" with a "double _Complex", the
184 // "double _Complex" is promoted to "long double _Complex".
185 int result = Context.getFloatingTypeOrder(lhs, rhs);
186
187 if (result > 0) { // The left side is bigger, convert rhs.
188 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000189 } else if (result < 0) { // The right side is bigger, convert lhs.
190 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000191 }
192 // At this point, lhs and rhs have the same rank/size. Now, make sure the
193 // domains match. This is a requirement for our implementation, C99
194 // does not require this promotion.
195 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
196 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000197 return rhs;
198 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000199 return lhs;
200 }
201 }
202 return lhs; // The domain/size match exactly.
203 }
204 // Now handle "real" floating types (i.e. float, double, long double).
205 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
206 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000207 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000208 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000209 return lhs;
210 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000211 if (rhs->isComplexIntegerType()) {
212 // convert rhs to the complex floating point type.
213 return Context.getComplexType(lhs);
214 }
215 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000216 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000217 return rhs;
218 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000219 if (lhs->isComplexIntegerType()) {
220 // convert lhs to the complex floating point type.
221 return Context.getComplexType(rhs);
222 }
Chris Lattner299b8842008-07-25 21:10:04 +0000223 // We have two real floating types, float/complex combos were handled above.
224 // Convert the smaller operand to the bigger result.
225 int result = Context.getFloatingTypeOrder(lhs, rhs);
226
227 if (result > 0) { // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000228 return lhs;
229 }
230 if (result < 0) { // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000231 return rhs;
232 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000233 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
Chris Lattner299b8842008-07-25 21:10:04 +0000234 }
235 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
236 // Handle GCC complex int extension.
237 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
238 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
239
240 if (lhsComplexInt && rhsComplexInt) {
241 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
242 rhsComplexInt->getElementType()) >= 0) {
243 // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000244 return lhs;
245 }
Chris Lattner299b8842008-07-25 21:10:04 +0000246 return rhs;
247 } else if (lhsComplexInt && rhs->isIntegerType()) {
248 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000249 return lhs;
250 } else if (rhsComplexInt && lhs->isIntegerType()) {
251 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000252 return rhs;
253 }
254 }
255 // Finally, we have two differing integer types.
256 // The rules for this case are in C99 6.3.1.8
257 int compare = Context.getIntegerTypeOrder(lhs, rhs);
258 bool lhsSigned = lhs->isSignedIntegerType(),
259 rhsSigned = rhs->isSignedIntegerType();
260 QualType destType;
261 if (lhsSigned == rhsSigned) {
262 // Same signedness; use the higher-ranked type
263 destType = compare >= 0 ? lhs : rhs;
264 } else if (compare != (lhsSigned ? 1 : -1)) {
265 // The unsigned type has greater than or equal rank to the
266 // signed type, so use the unsigned type
267 destType = lhsSigned ? rhs : lhs;
268 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
269 // The two types are different widths; if we are here, that
270 // means the signed type is larger than the unsigned type, so
271 // use the signed type.
272 destType = lhsSigned ? lhs : rhs;
273 } else {
274 // The signed type is higher-ranked than the unsigned type,
275 // but isn't actually any bigger (like unsigned int and long
276 // on most 32-bit systems). Use the unsigned type corresponding
277 // to the signed type.
278 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
279 }
Chris Lattner299b8842008-07-25 21:10:04 +0000280 return destType;
281}
282
283//===----------------------------------------------------------------------===//
284// Semantic Analysis for various Expression Types
285//===----------------------------------------------------------------------===//
286
287
Steve Naroff87d58b42007-09-16 03:34:24 +0000288/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000289/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
290/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
291/// multiple tokens. However, the common case is that StringToks points to one
292/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000293///
294Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000295Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000296 assert(NumStringToks && "Must have at least one string!");
297
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000298 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000299 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000300 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000301
302 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
303 for (unsigned i = 0; i != NumStringToks; ++i)
304 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000305
Chris Lattnera6dcce32008-02-11 00:02:17 +0000306 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000307 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000308 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000309
310 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
311 if (getLangOptions().CPlusPlus)
312 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000313
Chris Lattnera6dcce32008-02-11 00:02:17 +0000314 // Get an array type for the string, according to C99 6.4.5. This includes
315 // the nul terminator character as well as the string length for pascal
316 // strings.
317 StrTy = Context.getConstantArrayType(StrTy,
318 llvm::APInt(32, Literal.GetStringLength()+1),
319 ArrayType::Normal, 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000320
Chris Lattner4b009652007-07-25 00:24:17 +0000321 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Ted Kremenek4f530a92009-02-06 19:55:15 +0000322 return Owned(new (Context) StringLiteral(Context, Literal.GetString(),
Steve Naroff774e4152009-01-21 00:14:39 +0000323 Literal.GetStringLength(),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000324 Literal.AnyWide, StrTy,
325 StringToks[0].getLocation(),
326 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000327}
328
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000329/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
330/// CurBlock to VD should cause it to be snapshotted (as we do for auto
331/// variables defined outside the block) or false if this is not needed (e.g.
332/// for values inside the block or for globals).
333///
334/// FIXME: This will create BlockDeclRefExprs for global variables,
335/// function references, etc which is suboptimal :) and breaks
336/// things like "integer constant expression" tests.
337static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
338 ValueDecl *VD) {
339 // If the value is defined inside the block, we couldn't snapshot it even if
340 // we wanted to.
341 if (CurBlock->TheDecl == VD->getDeclContext())
342 return false;
343
344 // If this is an enum constant or function, it is constant, don't snapshot.
345 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
346 return false;
347
348 // If this is a reference to an extern, static, or global variable, no need to
349 // snapshot it.
350 // FIXME: What about 'const' variables in C++?
351 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
352 return Var->hasLocalStorage();
353
354 return true;
355}
356
357
358
Steve Naroff0acc9c92007-09-15 18:49:24 +0000359/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000360/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000361/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000362/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000363/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000364Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
365 IdentifierInfo &II,
366 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000367 const CXXScopeSpec *SS,
368 bool isAddressOfOperand) {
369 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000370 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000371}
372
Douglas Gregor566782a2009-01-06 05:10:23 +0000373/// BuildDeclRefExpr - Build either a DeclRefExpr or a
374/// QualifiedDeclRefExpr based on whether or not SS is a
375/// nested-name-specifier.
Sebastian Redl0c9da212009-02-03 20:19:35 +0000376DeclRefExpr *
377Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
378 bool TypeDependent, bool ValueDependent,
379 const CXXScopeSpec *SS) {
Steve Naroff774e4152009-01-21 00:14:39 +0000380 if (SS && !SS->isEmpty())
381 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000382 ValueDependent, SS->getRange().getBegin());
Steve Naroff774e4152009-01-21 00:14:39 +0000383 else
384 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000385}
386
Douglas Gregor723d3332009-01-07 00:43:41 +0000387/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
388/// variable corresponding to the anonymous union or struct whose type
389/// is Record.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000390static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000391 assert(Record->isAnonymousStructOrUnion() &&
392 "Record must be an anonymous struct or union!");
393
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000394 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000395 // be an O(1) operation rather than a slow walk through DeclContext's
396 // vector (which itself will be eliminated). DeclGroups might make
397 // this even better.
398 DeclContext *Ctx = Record->getDeclContext();
399 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
400 DEnd = Ctx->decls_end();
401 D != DEnd; ++D) {
402 if (*D == Record) {
403 // The object for the anonymous struct/union directly
404 // follows its type in the list of declarations.
405 ++D;
406 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000407 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000408 return *D;
409 }
410 }
411
412 assert(false && "Missing object for anonymous record");
413 return 0;
414}
415
Sebastian Redlcd883f72009-01-18 18:53:16 +0000416Sema::OwningExprResult
Douglas Gregor723d3332009-01-07 00:43:41 +0000417Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
418 FieldDecl *Field,
419 Expr *BaseObjectExpr,
420 SourceLocation OpLoc) {
421 assert(Field->getDeclContext()->isRecord() &&
422 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
423 && "Field must be stored inside an anonymous struct or union");
424
425 // Construct the sequence of field member references
426 // we'll have to perform to get to the field in the anonymous
427 // union/struct. The list of members is built from the field
428 // outward, so traverse it backwards to go from an object in
429 // the current context to the field we found.
430 llvm::SmallVector<FieldDecl *, 4> AnonFields;
431 AnonFields.push_back(Field);
432 VarDecl *BaseObject = 0;
433 DeclContext *Ctx = Field->getDeclContext();
434 do {
435 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000436 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000437 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
438 AnonFields.push_back(AnonField);
439 else {
440 BaseObject = cast<VarDecl>(AnonObject);
441 break;
442 }
443 Ctx = Ctx->getParent();
444 } while (Ctx->isRecord() &&
445 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
446
447 // Build the expression that refers to the base object, from
448 // which we will build a sequence of member references to each
449 // of the anonymous union objects and, eventually, the field we
450 // found via name lookup.
451 bool BaseObjectIsPointer = false;
452 unsigned ExtraQuals = 0;
453 if (BaseObject) {
454 // BaseObject is an anonymous struct/union variable (and is,
455 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000456 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff774e4152009-01-21 00:14:39 +0000457 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000458 SourceLocation());
459 ExtraQuals
460 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
461 } else if (BaseObjectExpr) {
462 // The caller provided the base object expression. Determine
463 // whether its a pointer and whether it adds any qualifiers to the
464 // anonymous struct/union fields we're looking into.
465 QualType ObjectType = BaseObjectExpr->getType();
466 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
467 BaseObjectIsPointer = true;
468 ObjectType = ObjectPtr->getPointeeType();
469 }
470 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
471 } else {
472 // We've found a member of an anonymous struct/union that is
473 // inside a non-anonymous struct/union, so in a well-formed
474 // program our base object expression is "this".
475 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
476 if (!MD->isStatic()) {
477 QualType AnonFieldType
478 = Context.getTagDeclType(
479 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
480 QualType ThisType = Context.getTagDeclType(MD->getParent());
481 if ((Context.getCanonicalType(AnonFieldType)
482 == Context.getCanonicalType(ThisType)) ||
483 IsDerivedFrom(ThisType, AnonFieldType)) {
484 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000485 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000486 MD->getThisType(Context));
487 BaseObjectIsPointer = true;
488 }
489 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000490 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
491 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000492 }
493 ExtraQuals = MD->getTypeQualifiers();
494 }
495
496 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000497 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
498 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000499 }
500
501 // Build the implicit member references to the field of the
502 // anonymous struct/union.
503 Expr *Result = BaseObjectExpr;
504 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
505 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
506 FI != FIEnd; ++FI) {
507 QualType MemberType = (*FI)->getType();
508 if (!(*FI)->isMutable()) {
509 unsigned combinedQualifiers
510 = MemberType.getCVRQualifiers() | ExtraQuals;
511 MemberType = MemberType.getQualifiedType(combinedQualifiers);
512 }
Steve Naroff774e4152009-01-21 00:14:39 +0000513 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
514 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000515 BaseObjectIsPointer = false;
516 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
517 OpLoc = SourceLocation();
518 }
519
Sebastian Redlcd883f72009-01-18 18:53:16 +0000520 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000521}
522
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000523/// ActOnDeclarationNameExpr - The parser has read some kind of name
524/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
525/// performs lookup on that name and returns an expression that refers
526/// to that name. This routine isn't directly called from the parser,
527/// because the parser doesn't know about DeclarationName. Rather,
528/// this routine is called by ActOnIdentifierExpr,
529/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
530/// which form the DeclarationName from the corresponding syntactic
531/// forms.
532///
533/// HasTrailingLParen indicates whether this identifier is used in a
534/// function call context. LookupCtx is only used for a C++
535/// qualified-id (foo::bar) to indicate the class or namespace that
536/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000537///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000538/// isAddressOfOperand means that this expression is the direct operand
539/// of an address-of operator. This matters because this is the only
540/// situation where a qualified name referencing a non-static member may
541/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000542Sema::OwningExprResult
543Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
544 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000545 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000546 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000547 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000548 if (SS && SS->isInvalid())
549 return ExprError();
Douglas Gregor411889e2009-02-13 23:20:09 +0000550 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
551 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000552
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000553 if (getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
554 HasTrailingLParen && Lookup.getKind() == LookupResult::NotFound) {
555 // We've seen something of the form
556 //
557 // identifier(
558 //
559 // and we did not find any entity by the name
560 // "identifier". However, this identifier is still subject to
561 // argument-dependent lookup, so keep track of the name.
562 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
563 Context.OverloadTy,
564 Loc));
565 }
566
Douglas Gregor09be81b2009-02-04 17:27:36 +0000567 NamedDecl *D = 0;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000568 if (Lookup.isAmbiguous()) {
569 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
570 SS && SS->isSet() ? SS->getRange()
571 : SourceRange());
572 return ExprError();
573 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000574 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000575
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000576 // If this reference is in an Objective-C method, then ivar lookup happens as
577 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000578 IdentifierInfo *II = Name.getAsIdentifierInfo();
579 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000580 // There are two cases to handle here. 1) scoped lookup could have failed,
581 // in which case we should look for an ivar. 2) scoped lookup could have
582 // found a decl, but that decl is outside the current method (i.e. a global
583 // variable). In these two cases, we do a lookup for an ivar with this
584 // name, if the lookup suceeds, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000585 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000586 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000587 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000588 // FIXME: This should use a new expr for a direct reference, don't turn
589 // this into Self->ivar, just return a BareIVarExpr or something.
590 IdentifierInfo &II = Context.Idents.get("self");
Sebastian Redlcd883f72009-01-18 18:53:16 +0000591 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Steve Naroff774e4152009-01-21 00:14:39 +0000592 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
593 Loc, static_cast<Expr*>(SelfExpr.release()),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000594 true, true);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000595 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000596 return Owned(MRef);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000597 }
598 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000599 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000600 if (D == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000601 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000602 getCurMethodDecl()->getClassInterface()));
Steve Naroff774e4152009-01-21 00:14:39 +0000603 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000604 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000605 }
Chris Lattner4b009652007-07-25 00:24:17 +0000606 if (D == 0) {
607 // Otherwise, this could be an implicitly declared function reference (legal
608 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000609 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000610 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000611 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000612 else {
613 // If this name wasn't predeclared and if this is not a function call,
614 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000615 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000616 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
617 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000618 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
619 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000620 return ExprError(Diag(Loc, diag::err_undeclared_use)
621 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000622 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000623 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000624 }
625 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000626
Sebastian Redl0c9da212009-02-03 20:19:35 +0000627 // If this is an expression of the form &Class::member, don't build an
628 // implicit member ref, because we want a pointer to the member in general,
629 // not any specific instance's member.
630 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000631 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
Douglas Gregor09be81b2009-02-04 17:27:36 +0000632 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000633 QualType DType;
634 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
635 DType = FD->getType().getNonReferenceType();
636 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
637 DType = Method->getType();
638 } else if (isa<OverloadedFunctionDecl>(D)) {
639 DType = Context.OverloadTy;
640 }
641 // Could be an inner type. That's diagnosed below, so ignore it here.
642 if (!DType.isNull()) {
643 // The pointer is type- and value-dependent if it points into something
644 // dependent.
645 bool Dependent = false;
646 for (; DC; DC = DC->getParent()) {
647 // FIXME: could stop early at namespace scope.
648 if (DC->isRecord()) {
649 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
650 if (Context.getTypeDeclType(Record)->isDependentType()) {
651 Dependent = true;
652 break;
653 }
654 }
655 }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000656 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000657 }
658 }
659 }
660
Douglas Gregor723d3332009-01-07 00:43:41 +0000661 // We may have found a field within an anonymous union or struct
662 // (C++ [class.union]).
663 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
664 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
665 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000666
Douglas Gregor3257fb52008-12-22 05:46:06 +0000667 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
668 if (!MD->isStatic()) {
669 // C++ [class.mfct.nonstatic]p2:
670 // [...] if name lookup (3.4.1) resolves the name in the
671 // id-expression to a nonstatic nontype member of class X or of
672 // a base class of X, the id-expression is transformed into a
673 // class member access expression (5.2.5) using (*this) (9.3.2)
674 // as the postfix-expression to the left of the '.' operator.
675 DeclContext *Ctx = 0;
676 QualType MemberType;
677 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
678 Ctx = FD->getDeclContext();
679 MemberType = FD->getType();
680
681 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
682 MemberType = RefType->getPointeeType();
683 else if (!FD->isMutable()) {
684 unsigned combinedQualifiers
685 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
686 MemberType = MemberType.getQualifiedType(combinedQualifiers);
687 }
688 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
689 if (!Method->isStatic()) {
690 Ctx = Method->getParent();
691 MemberType = Method->getType();
692 }
693 } else if (OverloadedFunctionDecl *Ovl
694 = dyn_cast<OverloadedFunctionDecl>(D)) {
695 for (OverloadedFunctionDecl::function_iterator
696 Func = Ovl->function_begin(),
697 FuncEnd = Ovl->function_end();
698 Func != FuncEnd; ++Func) {
699 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
700 if (!DMethod->isStatic()) {
701 Ctx = Ovl->getDeclContext();
702 MemberType = Context.OverloadTy;
703 break;
704 }
705 }
706 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000707
708 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000709 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
710 QualType ThisType = Context.getTagDeclType(MD->getParent());
711 if ((Context.getCanonicalType(CtxType)
712 == Context.getCanonicalType(ThisType)) ||
713 IsDerivedFrom(ThisType, CtxType)) {
714 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000715 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor3257fb52008-12-22 05:46:06 +0000716 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +0000717 return Owned(new (Context) MemberExpr(This, true, D,
Sebastian Redlcd883f72009-01-18 18:53:16 +0000718 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000719 }
720 }
721 }
722 }
723
Douglas Gregor8acb7272008-12-11 16:49:14 +0000724 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000725 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
726 if (MD->isStatic())
727 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000728 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
729 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000730 }
731
Douglas Gregor3257fb52008-12-22 05:46:06 +0000732 // Any other ways we could have found the field in a well-formed
733 // program would have been turned into implicit member expressions
734 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000735 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
736 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000737 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000738
Chris Lattner4b009652007-07-25 00:24:17 +0000739 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000740 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000741 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000742 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000743 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000744 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000745
Steve Naroffd6163f32008-09-05 22:11:13 +0000746 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000747 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000748 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
749 false, false, SS));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000750 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
751 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
752 false, false, SS));
Steve Naroffd6163f32008-09-05 22:11:13 +0000753 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000754
Steve Naroffd6163f32008-09-05 22:11:13 +0000755 // check if referencing an identifier with __attribute__((deprecated)).
756 if (VD->getAttr<DeprecatedAttr>())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000757 ExprError(Diag(Loc, diag::warn_deprecated) << VD->getDeclName());
758
Douglas Gregor48840c72008-12-10 23:01:14 +0000759 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
760 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
761 Scope *CheckS = S;
762 while (CheckS) {
763 if (CheckS->isWithinElse() &&
764 CheckS->getControlParent()->isDeclScope(Var)) {
765 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000766 ExprError(Diag(Loc, diag::warn_value_always_false)
767 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000768 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000769 ExprError(Diag(Loc, diag::warn_value_always_zero)
770 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000771 break;
772 }
773
774 // Move up one more control parent to check again.
775 CheckS = CheckS->getControlParent();
776 if (CheckS)
777 CheckS = CheckS->getParent();
778 }
779 }
780 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000781
782 // Only create DeclRefExpr's for valid Decl's.
783 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000784 return ExprError();
785
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000786 // If the identifier reference is inside a block, and it refers to a value
787 // that is outside the block, create a BlockDeclRefExpr instead of a
788 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
789 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000790 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000791 // We do not do this for things like enum constants, global variables, etc,
792 // as they do not get snapshotted.
793 //
794 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000795 // The BlocksAttr indicates the variable is bound by-reference.
796 if (VD->getAttr<BlocksAttr>())
Steve Naroff774e4152009-01-21 00:14:39 +0000797 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000798 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000799
Steve Naroff52059382008-10-10 01:28:17 +0000800 // Variable will be bound by-copy, make it const within the closure.
801 VD->getType().addConst();
Steve Naroff774e4152009-01-21 00:14:39 +0000802 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000803 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000804 }
805 // If this reference is not in a block or if the referenced variable is
806 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000807
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000808 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000809 bool ValueDependent = false;
810 if (getLangOptions().CPlusPlus) {
811 // C++ [temp.dep.expr]p3:
812 // An id-expression is type-dependent if it contains:
813 // - an identifier that was declared with a dependent type,
814 if (VD->getType()->isDependentType())
815 TypeDependent = true;
816 // - FIXME: a template-id that is dependent,
817 // - a conversion-function-id that specifies a dependent type,
818 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
819 Name.getCXXNameType()->isDependentType())
820 TypeDependent = true;
821 // - a nested-name-specifier that contains a class-name that
822 // names a dependent type.
823 else if (SS && !SS->isEmpty()) {
824 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
825 DC; DC = DC->getParent()) {
826 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000827 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000828 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
829 if (Context.getTypeDeclType(Record)->isDependentType()) {
830 TypeDependent = true;
831 break;
832 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000833 }
834 }
835 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000836
Douglas Gregora5d84612008-12-10 20:57:37 +0000837 // C++ [temp.dep.constexpr]p2:
838 //
839 // An identifier is value-dependent if it is:
840 // - a name declared with a dependent type,
841 if (TypeDependent)
842 ValueDependent = true;
843 // - the name of a non-type template parameter,
844 else if (isa<NonTypeTemplateParmDecl>(VD))
845 ValueDependent = true;
846 // - a constant with integral or enumeration type and is
847 // initialized with an expression that is value-dependent
848 // (FIXME!).
849 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000850
Sebastian Redlcd883f72009-01-18 18:53:16 +0000851 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
852 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000853}
854
Sebastian Redlcd883f72009-01-18 18:53:16 +0000855Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
856 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000857 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000858
Chris Lattner4b009652007-07-25 00:24:17 +0000859 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000860 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000861 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
862 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
863 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000864 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000865
Chris Lattner7e637512008-01-12 08:14:25 +0000866 // Pre-defined identifiers are of type char[x], where x is the length of the
867 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000868 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000869 if (FunctionDecl *FD = getCurFunctionDecl())
870 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000871 else if (ObjCMethodDecl *MD = getCurMethodDecl())
872 Length = MD->getSynthesizedMethodSize();
873 else {
874 Diag(Loc, diag::ext_predef_outside_function);
875 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
876 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
877 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000878
879
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000880 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000881 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000882 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +0000883 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +0000884}
885
Sebastian Redlcd883f72009-01-18 18:53:16 +0000886Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000887 llvm::SmallString<16> CharBuffer;
888 CharBuffer.resize(Tok.getLength());
889 const char *ThisTokBegin = &CharBuffer[0];
890 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000891
Chris Lattner4b009652007-07-25 00:24:17 +0000892 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
893 Tok.getLocation(), PP);
894 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000895 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +0000896
897 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
898
Sebastian Redl75324932009-01-20 22:23:13 +0000899 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
900 Literal.isWide(),
901 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000902}
903
Sebastian Redlcd883f72009-01-18 18:53:16 +0000904Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
905 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +0000906 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
907 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +0000908 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +0000909 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +0000910 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +0000911 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000912 }
Ted Kremenekdbde2282009-01-13 23:19:12 +0000913
Chris Lattner4b009652007-07-25 00:24:17 +0000914 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000915 // Add padding so that NumericLiteralParser can overread by one character.
916 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000917 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +0000918
Chris Lattner4b009652007-07-25 00:24:17 +0000919 // Get the spelling of the token, which eliminates trigraphs, etc.
920 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000921
Chris Lattner4b009652007-07-25 00:24:17 +0000922 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
923 Tok.getLocation(), PP);
924 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000925 return ExprError();
926
Chris Lattner1de66eb2007-08-26 03:42:43 +0000927 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000928
Chris Lattner1de66eb2007-08-26 03:42:43 +0000929 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000930 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000931 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000932 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000933 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000934 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000935 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000936 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000937
938 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
939
Ted Kremenekddedbe22007-11-29 00:56:49 +0000940 // isExact will be set by GetFloatValue().
941 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +0000942 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
943 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +0000944
Chris Lattner1de66eb2007-08-26 03:42:43 +0000945 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000946 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +0000947 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000948 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000949
Neil Booth7421e9c2007-08-29 22:00:19 +0000950 // long long is a C99 feature.
951 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000952 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000953 Diag(Tok.getLocation(), diag::ext_longlong);
954
Chris Lattner4b009652007-07-25 00:24:17 +0000955 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000956 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000957
Chris Lattner4b009652007-07-25 00:24:17 +0000958 if (Literal.GetIntegerValue(ResultVal)) {
959 // If this value didn't fit into uintmax_t, warn and force to ull.
960 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000961 Ty = Context.UnsignedLongLongTy;
962 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000963 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000964 } else {
965 // If this value fits into a ULL, try to figure out what else it fits into
966 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000967
Chris Lattner4b009652007-07-25 00:24:17 +0000968 // Octal, Hexadecimal, and integers with a U suffix are allowed to
969 // be an unsigned int.
970 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
971
972 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000973 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000974 if (!Literal.isLong && !Literal.isLongLong) {
975 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000976 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000977
Chris Lattner4b009652007-07-25 00:24:17 +0000978 // Does it fit in a unsigned int?
979 if (ResultVal.isIntN(IntSize)) {
980 // Does it fit in a signed int?
981 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000982 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000983 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000984 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000985 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000986 }
Chris Lattner4b009652007-07-25 00:24:17 +0000987 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000988
Chris Lattner4b009652007-07-25 00:24:17 +0000989 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000990 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000991 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000992
Chris Lattner4b009652007-07-25 00:24:17 +0000993 // Does it fit in a unsigned long?
994 if (ResultVal.isIntN(LongSize)) {
995 // Does it fit in a signed long?
996 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000997 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000998 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000999 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001000 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001001 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001002 }
1003
Chris Lattner4b009652007-07-25 00:24:17 +00001004 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001005 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001006 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001007
Chris Lattner4b009652007-07-25 00:24:17 +00001008 // Does it fit in a unsigned long long?
1009 if (ResultVal.isIntN(LongLongSize)) {
1010 // Does it fit in a signed long long?
1011 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001012 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001013 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001014 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001015 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001016 }
1017 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001018
Chris Lattner4b009652007-07-25 00:24:17 +00001019 // If we still couldn't decide a type, we probably have something that
1020 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001021 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001022 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001023 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001024 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001025 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001026
Chris Lattnere4068872008-05-09 05:59:00 +00001027 if (ResultVal.getBitWidth() != Width)
1028 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001029 }
Sebastian Redl75324932009-01-20 22:23:13 +00001030 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001031 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001032
Chris Lattner1de66eb2007-08-26 03:42:43 +00001033 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1034 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001035 Res = new (Context) ImaginaryLiteral(Res,
1036 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001037
1038 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001039}
1040
Sebastian Redlcd883f72009-01-18 18:53:16 +00001041Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1042 SourceLocation R, ExprArg Val) {
1043 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001044 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001045 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001046}
1047
1048/// The UsualUnaryConversions() function is *not* called by this routine.
1049/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001050bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1051 SourceLocation OpLoc,
1052 const SourceRange &ExprRange,
1053 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +00001054 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001055 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001056 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001057 if (isSizeof)
1058 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1059 return false;
1060 }
1061
1062 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001063 Diag(OpLoc, diag::ext_sizeof_void_type)
1064 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001065 return false;
1066 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001067
Chris Lattner159fe082009-01-24 19:46:37 +00001068 return DiagnoseIncompleteType(OpLoc, exprType,
1069 isSizeof ? diag::err_sizeof_incomplete_type :
1070 diag::err_alignof_incomplete_type,
1071 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001072}
1073
Chris Lattner8d9f7962009-01-24 20:17:12 +00001074bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1075 const SourceRange &ExprRange) {
1076 E = E->IgnoreParens();
1077
1078 // alignof decl is always ok.
1079 if (isa<DeclRefExpr>(E))
1080 return false;
1081
1082 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1083 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1084 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001085 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001086 return true;
1087 }
1088 // Other fields are ok.
1089 return false;
1090 }
1091 }
1092 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1093}
1094
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001095/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1096/// the same for @c alignof and @c __alignof
1097/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001098Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001099Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1100 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001101 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001102 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001103
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001104 QualType ArgTy;
1105 SourceRange Range;
1106 if (isType) {
1107 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1108 Range = ArgRange;
Chris Lattnera78909b2009-01-24 19:49:13 +00001109
1110 // Verify that the operand is valid.
1111 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1112 return ExprError();
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001113 } else {
1114 // Get the end location.
1115 Expr *ArgEx = (Expr *)TyOrEx;
1116 Range = ArgEx->getSourceRange();
1117 ArgTy = ArgEx->getType();
Chris Lattnera78909b2009-01-24 19:49:13 +00001118
1119 // Verify that the operand is valid.
Chris Lattner8d9f7962009-01-24 20:17:12 +00001120 bool isInvalid;
Chris Lattner364a42d2009-01-24 21:29:22 +00001121 if (!isSizeof) {
Chris Lattner8d9f7962009-01-24 20:17:12 +00001122 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattner364a42d2009-01-24 21:29:22 +00001123 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1124 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1125 isInvalid = true;
1126 } else {
1127 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1128 }
Chris Lattner8d9f7962009-01-24 20:17:12 +00001129
1130 if (isInvalid) {
Chris Lattnera78909b2009-01-24 19:49:13 +00001131 DeleteExpr(ArgEx);
1132 return ExprError();
1133 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001134 }
1135
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001136 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff774e4152009-01-21 00:14:39 +00001137 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner159fe082009-01-24 19:46:37 +00001138 Context.getSizeType(), OpLoc,
1139 Range.getEnd()));
Chris Lattner4b009652007-07-25 00:24:17 +00001140}
1141
Chris Lattner5110ad52007-08-24 21:41:10 +00001142QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +00001143 DefaultFunctionArrayConversion(V);
1144
Chris Lattnera16e42d2007-08-26 05:39:26 +00001145 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001146 if (const ComplexType *CT = V->getType()->getAsComplexType())
1147 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001148
1149 // Otherwise they pass through real integer and floating point types here.
1150 if (V->getType()->isArithmeticType())
1151 return V->getType();
1152
1153 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +00001154 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001155 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001156}
1157
1158
Chris Lattner4b009652007-07-25 00:24:17 +00001159
Sebastian Redl8b769972009-01-19 00:08:26 +00001160Action::OwningExprResult
1161Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1162 tok::TokenKind Kind, ExprArg Input) {
1163 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001164
Chris Lattner4b009652007-07-25 00:24:17 +00001165 UnaryOperator::Opcode Opc;
1166 switch (Kind) {
1167 default: assert(0 && "Unknown unary op!");
1168 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1169 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1170 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001171
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001172 if (getLangOptions().CPlusPlus &&
1173 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1174 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001175 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001176 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1177
1178 // C++ [over.inc]p1:
1179 //
1180 // [...] If the function is a member function with one
1181 // parameter (which shall be of type int) or a non-member
1182 // function with two parameters (the second of which shall be
1183 // of type int), it defines the postfix increment operator ++
1184 // for objects of that type. When the postfix increment is
1185 // called as a result of using the ++ operator, the int
1186 // argument will have value zero.
1187 Expr *Args[2] = {
1188 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001189 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1190 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001191 };
1192
1193 // Build the candidate set for overloading
1194 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00001195 if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet))
1196 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001197
1198 // Perform overload resolution.
1199 OverloadCandidateSet::iterator Best;
1200 switch (BestViableFunction(CandidateSet, Best)) {
1201 case OR_Success: {
1202 // We found a built-in operator or an overloaded operator.
1203 FunctionDecl *FnDecl = Best->Function;
1204
1205 if (FnDecl) {
1206 // We matched an overloaded operator. Build a call to that
1207 // operator.
1208
1209 // Convert the arguments.
1210 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1211 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001212 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001213 } else {
1214 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001215 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001216 FnDecl->getParamDecl(0)->getType(),
1217 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001218 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001219 }
1220
1221 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001222 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001223 = FnDecl->getType()->getAsFunctionType()->getResultType();
1224 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001225
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001226 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001227 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001228 SourceLocation());
1229 UsualUnaryConversions(FnExpr);
1230
Sebastian Redl8b769972009-01-19 00:08:26 +00001231 Input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001232 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
1233 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001234 } else {
1235 // We matched a built-in operator. Convert the arguments, then
1236 // break out so that we will build the appropriate built-in
1237 // operator node.
1238 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1239 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001240 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001241
1242 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001243 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001244 }
1245
1246 case OR_No_Viable_Function:
1247 // No viable function; fall through to handling this as a
1248 // built-in operator, which will produce an error message for us.
1249 break;
1250
1251 case OR_Ambiguous:
1252 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1253 << UnaryOperator::getOpcodeStr(Opc)
1254 << Arg->getSourceRange();
1255 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001256 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001257 }
1258
1259 // Either we found no viable overloaded operator or we matched a
1260 // built-in operator. In either case, fall through to trying to
1261 // build a built-in operation.
1262 }
1263
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001264 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1265 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001266 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001267 return ExprError();
1268 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001269 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001270}
1271
Sebastian Redl8b769972009-01-19 00:08:26 +00001272Action::OwningExprResult
1273Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1274 ExprArg Idx, SourceLocation RLoc) {
1275 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1276 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001277
Douglas Gregor80723c52008-11-19 17:17:41 +00001278 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001279 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001280 LHSExp->getType()->isEnumeralType() ||
1281 RHSExp->getType()->isRecordType() ||
1282 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001283 // Add the appropriate overloaded operators (C++ [over.match.oper])
1284 // to the candidate set.
1285 OverloadCandidateSet CandidateSet;
1286 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor48a87322009-02-04 16:44:47 +00001287 if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1288 SourceRange(LLoc, RLoc)))
1289 return ExprError();
Sebastian Redl8b769972009-01-19 00:08:26 +00001290
Douglas Gregor80723c52008-11-19 17:17:41 +00001291 // Perform overload resolution.
1292 OverloadCandidateSet::iterator Best;
1293 switch (BestViableFunction(CandidateSet, Best)) {
1294 case OR_Success: {
1295 // We found a built-in operator or an overloaded operator.
1296 FunctionDecl *FnDecl = Best->Function;
1297
1298 if (FnDecl) {
1299 // We matched an overloaded operator. Build a call to that
1300 // operator.
1301
1302 // Convert the arguments.
1303 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1304 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1305 PerformCopyInitialization(RHSExp,
1306 FnDecl->getParamDecl(0)->getType(),
1307 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001308 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001309 } else {
1310 // Convert the arguments.
1311 if (PerformCopyInitialization(LHSExp,
1312 FnDecl->getParamDecl(0)->getType(),
1313 "passing") ||
1314 PerformCopyInitialization(RHSExp,
1315 FnDecl->getParamDecl(1)->getType(),
1316 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001317 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001318 }
1319
1320 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001321 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001322 = FnDecl->getType()->getAsFunctionType()->getResultType();
1323 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001324
Douglas Gregor80723c52008-11-19 17:17:41 +00001325 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001326 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor80723c52008-11-19 17:17:41 +00001327 SourceLocation());
1328 UsualUnaryConversions(FnExpr);
1329
Sebastian Redl8b769972009-01-19 00:08:26 +00001330 Base.release();
1331 Idx.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001332 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001333 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001334 } else {
1335 // We matched a built-in operator. Convert the arguments, then
1336 // break out so that we will build the appropriate built-in
1337 // operator node.
1338 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1339 "passing") ||
1340 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1341 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001342 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001343
1344 break;
1345 }
1346 }
1347
1348 case OR_No_Viable_Function:
1349 // No viable function; fall through to handling this as a
1350 // built-in operator, which will produce an error message for us.
1351 break;
1352
1353 case OR_Ambiguous:
1354 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1355 << "[]"
1356 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1357 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001358 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001359 }
1360
1361 // Either we found no viable overloaded operator or we matched a
1362 // built-in operator. In either case, fall through to trying to
1363 // build a built-in operation.
1364 }
1365
Chris Lattner4b009652007-07-25 00:24:17 +00001366 // Perform default conversions.
1367 DefaultFunctionArrayConversion(LHSExp);
1368 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001369
Chris Lattner4b009652007-07-25 00:24:17 +00001370 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1371
1372 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001373 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001374 // in the subscript position. As a result, we need to derive the array base
1375 // and index from the expression types.
1376 Expr *BaseExpr, *IndexExpr;
1377 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001378 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001379 BaseExpr = LHSExp;
1380 IndexExpr = RHSExp;
1381 // FIXME: need to deal with const...
1382 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001383 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001384 // Handle the uncommon case of "123[Ptr]".
1385 BaseExpr = RHSExp;
1386 IndexExpr = LHSExp;
1387 // FIXME: need to deal with const...
1388 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001389 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1390 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001391 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001392
Chris Lattner4b009652007-07-25 00:24:17 +00001393 // FIXME: need to deal with const...
1394 ResultType = VTy->getElementType();
1395 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001396 return ExprError(Diag(LHSExp->getLocStart(),
1397 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1398 }
Chris Lattner4b009652007-07-25 00:24:17 +00001399 // C99 6.5.2.1p1
1400 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001401 return ExprError(Diag(IndexExpr->getLocStart(),
1402 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001403
1404 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1405 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001406 // void (*)(int)) and pointers to incomplete types. Functions are not
1407 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001408 if (!ResultType->isObjectType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001409 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001410 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001411 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001412
Sebastian Redl8b769972009-01-19 00:08:26 +00001413 Base.release();
1414 Idx.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001415 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1416 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001417}
1418
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001419QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001420CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001421 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001422 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001423
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001424 // The vector accessor can't exceed the number of elements.
1425 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001426
1427 // This flag determines whether or not the component is one of the four
1428 // special names that indicate a subset of exactly half the elements are
1429 // to be selected.
1430 bool HalvingSwizzle = false;
1431
1432 // This flag determines whether or not CompName has an 's' char prefix,
1433 // indicating that it is a string of hex values to be used as vector indices.
1434 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001435
1436 // Check that we've found one of the special components, or that the component
1437 // names must come from the same set.
1438 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001439 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1440 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001441 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001442 do
1443 compStr++;
1444 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001445 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001446 do
1447 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001448 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001449 }
Nate Begeman1486b502009-01-18 01:47:54 +00001450
1451 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001452 // We didn't get to the end of the string. This means the component names
1453 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001454 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1455 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001456 return QualType();
1457 }
Nate Begeman1486b502009-01-18 01:47:54 +00001458
1459 // Ensure no component accessor exceeds the width of the vector type it
1460 // operates on.
1461 if (!HalvingSwizzle) {
1462 compStr = CompName.getName();
1463
1464 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001465 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001466
1467 while (*compStr) {
1468 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1469 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1470 << baseType << SourceRange(CompLoc);
1471 return QualType();
1472 }
1473 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001474 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001475
Nate Begeman1486b502009-01-18 01:47:54 +00001476 // If this is a halving swizzle, verify that the base type has an even
1477 // number of elements.
1478 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001479 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001480 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001481 return QualType();
1482 }
1483
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001484 // The component accessor looks fine - now we need to compute the actual type.
1485 // The vector type is implied by the component accessor. For example,
1486 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001487 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001488 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001489 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1490 : CompName.getLength();
1491 if (HexSwizzle)
1492 CompSize--;
1493
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001494 if (CompSize == 1)
1495 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001496
Nate Begemanaf6ed502008-04-18 23:10:10 +00001497 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001498 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001499 // diagostics look bad. We want extended vector types to appear built-in.
1500 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1501 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1502 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001503 }
1504 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001505}
1506
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001507/// constructSetterName - Return the setter name for the given
1508/// identifier, i.e. "set" + Name where the initial character of Name
1509/// has been capitalized.
1510// FIXME: Merge with same routine in Parser. But where should this
1511// live?
1512static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1513 const IdentifierInfo *Name) {
1514 llvm::SmallString<100> SelectorName;
1515 SelectorName = "set";
1516 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1517 SelectorName[3] = toupper(SelectorName[3]);
1518 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1519}
1520
Sebastian Redl8b769972009-01-19 00:08:26 +00001521Action::OwningExprResult
1522Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1523 tok::TokenKind OpKind, SourceLocation MemberLoc,
1524 IdentifierInfo &Member) {
1525 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001526 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001527
1528 // Perform default conversions.
1529 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001530
Steve Naroff2cb66382007-07-26 03:11:44 +00001531 QualType BaseType = BaseExpr->getType();
1532 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001533
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001534 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1535 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001536 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001537 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001538 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001539 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001540 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1541 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001542 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001543 return ExprError(Diag(MemberLoc,
1544 diag::err_typecheck_member_reference_arrow)
1545 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001546 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001547
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001548 // Handle field access to simple records. This also handles access to fields
1549 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001550 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001551 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001552 if (DiagnoseIncompleteType(OpLoc, BaseType,
1553 diag::err_typecheck_incomplete_tag,
1554 BaseExpr->getSourceRange()))
1555 return ExprError();
1556
Steve Naroff2cb66382007-07-26 03:11:44 +00001557 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001558 // FIXME: Qualified name lookup for C++ is a bit more complicated
1559 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001560 LookupResult Result
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001561 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001562 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001563
Douglas Gregor09be81b2009-02-04 17:27:36 +00001564 NamedDecl *MemberDecl = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001565 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001566 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1567 << &Member << BaseExpr->getSourceRange());
1568 else if (Result.isAmbiguous()) {
1569 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1570 MemberLoc, BaseExpr->getSourceRange());
1571 return ExprError();
1572 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001573 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001574
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001575 // If the decl being referenced had an error, return an error for this
1576 // sub-expr without emitting another error, in order to avoid cascading
1577 // error cases.
1578 if (MemberDecl->isInvalidDecl())
1579 return ExprError();
1580
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001581 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001582 // We may have found a field within an anonymous union or struct
1583 // (C++ [class.union]).
1584 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001585 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001586 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001587
Douglas Gregor82d44772008-12-20 23:49:58 +00001588 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1589 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001590 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001591 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1592 MemberType = Ref->getPointeeType();
1593 else {
1594 unsigned combinedQualifiers =
1595 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001596 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001597 combinedQualifiers &= ~QualType::Const;
1598 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1599 }
Eli Friedman76b49832008-02-06 22:48:16 +00001600
Steve Naroff774e4152009-01-21 00:14:39 +00001601 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1602 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001603 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001604 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001605 Var, MemberLoc,
1606 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001607 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001608 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1609 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001610 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001611 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001612 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001613 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001614 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001615 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Enum,
Sebastian Redl8b769972009-01-19 00:08:26 +00001616 MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001617 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001618 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1619 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001620
Douglas Gregor82d44772008-12-20 23:49:58 +00001621 // We found a declaration kind that we didn't expect. This is a
1622 // generic error message that tells the user that she can't refer
1623 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001624 return ExprError(Diag(MemberLoc,
1625 diag::err_typecheck_member_reference_unknown)
1626 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001627 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001628
Chris Lattnere9d71612008-07-21 04:59:05 +00001629 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1630 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001631 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001632 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001633 // If the decl being referenced had an error, return an error for this
1634 // sub-expr without emitting another error, in order to avoid cascading
1635 // error cases.
1636 if (IV->isInvalidDecl())
1637 return ExprError();
1638
Steve Naroff774e4152009-01-21 00:14:39 +00001639 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1640 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001641 OpKind == tok::arrow);
1642 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001643 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001644 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001645 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1646 << IFTy->getDecl()->getDeclName() << &Member
1647 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001648 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001649
Chris Lattnere9d71612008-07-21 04:59:05 +00001650 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1651 // pointer to a (potentially qualified) interface type.
1652 const PointerType *PTy;
1653 const ObjCInterfaceType *IFTy;
1654 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1655 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1656 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001657
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001658 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001659 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001660 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001661 MemberLoc, BaseExpr));
1662
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001663 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001664 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1665 E = IFTy->qual_end(); I != E; ++I)
1666 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001667 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001668 MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001669
1670 // If that failed, look for an "implicit" property by seeing if the nullary
1671 // selector is implemented.
1672
1673 // FIXME: The logic for looking up nullary and unary selectors should be
1674 // shared with the code in ActOnInstanceMessage.
1675
1676 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1677 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001678
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001679 // If this reference is in an @implementation, check for 'private' methods.
1680 if (!Getter)
1681 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1682 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1683 if (ObjCImplementationDecl *ImpDecl =
1684 ObjCImplementations[ClassDecl->getIdentifier()])
1685 Getter = ImpDecl->getInstanceMethod(Sel);
1686
Steve Naroff04151f32008-10-22 19:16:27 +00001687 // Look through local category implementations associated with the class.
1688 if (!Getter) {
1689 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1690 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1691 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1692 }
1693 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001694 if (Getter) {
1695 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001696 // will look for the matching setter, in case it is needed.
1697 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1698 &Member);
1699 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1700 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1701 if (!Setter) {
1702 // If this reference is in an @implementation, also check for 'private'
1703 // methods.
1704 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1705 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1706 if (ObjCImplementationDecl *ImpDecl =
1707 ObjCImplementations[ClassDecl->getIdentifier()])
1708 Setter = ImpDecl->getInstanceMethod(SetterSel);
1709 }
1710 // Look through local category implementations associated with the class.
1711 if (!Setter) {
1712 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1713 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1714 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1715 }
1716 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001717
1718 // FIXME: we must check that the setter has property type.
Steve Naroff774e4152009-01-21 00:14:39 +00001719 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
1720 Setter, MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001721 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001722
1723 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1724 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001725 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001726 // Handle properties on qualified "id" protocols.
1727 const ObjCQualifiedIdType *QIdTy;
1728 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1729 // Check protocols on qualified interfaces.
1730 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001731 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroffd1d44402008-10-20 22:53:06 +00001732 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001733 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001734 MemberLoc, BaseExpr));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001735 // Also must look for a getter name which uses property syntax.
1736 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1737 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Steve Naroff774e4152009-01-21 00:14:39 +00001738 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
1739 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001740 }
1741 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001742
1743 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1744 << &Member << BaseType);
1745 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001746 // Handle 'field access' to vectors, such as 'V.xx'.
1747 if (BaseType->isExtVectorType() && OpKind == tok::period) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001748 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1749 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001750 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00001751 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
1752 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001753 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001754
1755 return ExprError(Diag(MemberLoc,
1756 diag::err_typecheck_member_reference_struct_union)
1757 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001758}
1759
Douglas Gregor3257fb52008-12-22 05:46:06 +00001760/// ConvertArgumentsForCall - Converts the arguments specified in
1761/// Args/NumArgs to the parameter types of the function FDecl with
1762/// function prototype Proto. Call is the call expression itself, and
1763/// Fn is the function expression. For a C++ member function, this
1764/// routine does not attempt to convert the object argument. Returns
1765/// true if the call is ill-formed.
1766bool
1767Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1768 FunctionDecl *FDecl,
1769 const FunctionTypeProto *Proto,
1770 Expr **Args, unsigned NumArgs,
1771 SourceLocation RParenLoc) {
1772 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1773 // assignment, to the types of the corresponding parameter, ...
1774 unsigned NumArgsInProto = Proto->getNumArgs();
1775 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001776 bool Invalid = false;
1777
Douglas Gregor3257fb52008-12-22 05:46:06 +00001778 // If too few arguments are available (and we don't have default
1779 // arguments for the remaining parameters), don't make the call.
1780 if (NumArgs < NumArgsInProto) {
1781 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1782 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1783 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1784 // Use default arguments for missing arguments
1785 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001786 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001787 }
1788
1789 // If too many are passed and not variadic, error on the extras and drop
1790 // them.
1791 if (NumArgs > NumArgsInProto) {
1792 if (!Proto->isVariadic()) {
1793 Diag(Args[NumArgsInProto]->getLocStart(),
1794 diag::err_typecheck_call_too_many_args)
1795 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1796 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1797 Args[NumArgs-1]->getLocEnd());
1798 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001799 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001800 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001801 }
1802 NumArgsToCheck = NumArgsInProto;
1803 }
1804
1805 // Continue to check argument types (even if we have too few/many args).
1806 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1807 QualType ProtoArgType = Proto->getArgType(i);
1808
1809 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001810 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001811 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001812
1813 // Pass the argument.
1814 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1815 return true;
1816 } else
1817 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00001818 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001819 QualType ArgType = Arg->getType();
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001820
Douglas Gregor3257fb52008-12-22 05:46:06 +00001821 Call->setArg(i, Arg);
1822 }
1823
1824 // If this is a variadic call, handle args passed through "...".
1825 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001826 VariadicCallType CallType = VariadicFunction;
1827 if (Fn->getType()->isBlockPointerType())
1828 CallType = VariadicBlock; // Block
1829 else if (isa<MemberExpr>(Fn))
1830 CallType = VariadicMethod;
1831
Douglas Gregor3257fb52008-12-22 05:46:06 +00001832 // Promote the arguments (C99 6.5.2.2p7).
1833 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1834 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001835 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001836 Call->setArg(i, Arg);
1837 }
1838 }
1839
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001840 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001841}
1842
Steve Naroff87d58b42007-09-16 03:34:24 +00001843/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001844/// This provides the location of the left/right parens and a list of comma
1845/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00001846Action::OwningExprResult
1847Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1848 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001849 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001850 unsigned NumArgs = args.size();
1851 Expr *Fn = static_cast<Expr *>(fn.release());
1852 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00001853 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001854 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001855 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001856
Douglas Gregor3257fb52008-12-22 05:46:06 +00001857 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001858 // Determine whether this is a dependent call inside a C++ template,
1859 // in which case we won't do any semantic analysis now.
1860 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
1861 bool Dependent = false;
1862 if (Fn->isTypeDependent())
1863 Dependent = true;
1864 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1865 Dependent = true;
1866
1867 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00001868 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001869 Context.DependentTy, RParenLoc));
1870
1871 // Determine whether this is a call to an object (C++ [over.call.object]).
1872 if (Fn->getType()->isRecordType())
1873 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1874 CommaLocs, RParenLoc));
1875
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001876 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00001877 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1878 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1879 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00001880 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1881 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001882 }
1883
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001884 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00001885 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001886 Expr *FnExpr = Fn;
1887 bool ADL = true;
1888 while (true) {
1889 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
1890 FnExpr = IcExpr->getSubExpr();
1891 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001892 // Parentheses around a function disable ADL
1893 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001894 ADL = false;
1895 FnExpr = PExpr->getSubExpr();
1896 } else if (isa<UnaryOperator>(FnExpr) &&
1897 cast<UnaryOperator>(FnExpr)->getOpcode()
1898 == UnaryOperator::AddrOf) {
1899 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00001900 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
1901 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
1902 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
1903 break;
1904 } else if (UnresolvedFunctionNameExpr *DepName
1905 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
1906 UnqualifiedName = DepName->getName();
1907 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001908 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00001909 // Any kind of name that does not refer to a declaration (or
1910 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
1911 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001912 break;
1913 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001914 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001915
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001916 OverloadedFunctionDecl *Ovl = 0;
1917 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001918 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001919 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1920 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001921
Douglas Gregorfcb19192009-02-11 23:02:49 +00001922 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00001923 // We don't perform ADL for implicit declarations of builtins.
1924 if (FDecl && FDecl->getBuiltinID() && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001925 ADL = false;
1926
Douglas Gregorfcb19192009-02-11 23:02:49 +00001927 // We don't perform ADL in C.
1928 if (!getLangOptions().CPlusPlus)
1929 ADL = false;
1930
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001931 if (Ovl || ADL) {
1932 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
1933 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001934 NumArgs, CommaLocs, RParenLoc, ADL);
1935 if (!FDecl)
1936 return ExprError();
1937
1938 // Update Fn to refer to the actual function selected.
1939 Expr *NewFn = 0;
1940 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001941 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001942 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
1943 QDRExpr->getLocation(),
1944 false, false,
1945 QDRExpr->getSourceRange().getBegin());
1946 else
1947 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
1948 Fn->getSourceRange().getBegin());
1949 Fn->Destroy(Context);
1950 Fn = NewFn;
1951 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001952 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001953
1954 // Promote the function operand.
1955 UsualUnaryConversions(Fn);
1956
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001957 // Make the call expr early, before semantic checks. This guarantees cleanup
1958 // of arguments and function on error.
Sebastian Redl8b769972009-01-19 00:08:26 +00001959 // FIXME: Except that llvm::OwningPtr uses delete, when it really must be
1960 // Destroy(), or nothing gets cleaned up.
Ted Kremenek362abcd2009-02-09 20:51:47 +00001961 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
1962 Args, NumArgs,
1963 Context.BoolTy,
1964 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001965
Steve Naroffd6163f32008-09-05 22:11:13 +00001966 const FunctionType *FuncT;
1967 if (!Fn->getType()->isBlockPointerType()) {
1968 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1969 // have type pointer to function".
1970 const PointerType *PT = Fn->getType()->getAsPointerType();
1971 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00001972 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1973 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00001974 FuncT = PT->getPointeeType()->getAsFunctionType();
1975 } else { // This is a block call.
1976 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1977 getAsFunctionType();
1978 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001979 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00001980 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1981 << Fn->getType() << Fn->getSourceRange());
1982
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001983 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001984 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00001985
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001986 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001987 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
1988 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00001989 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001990 } else {
1991 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00001992
Steve Naroffdb65e052007-08-28 23:30:39 +00001993 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001994 for (unsigned i = 0; i != NumArgs; i++) {
1995 Expr *Arg = Args[i];
1996 DefaultArgumentPromotion(Arg);
1997 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001998 }
Chris Lattner4b009652007-07-25 00:24:17 +00001999 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002000
Douglas Gregor3257fb52008-12-22 05:46:06 +00002001 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2002 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002003 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2004 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002005
Chris Lattner2e64c072007-08-10 20:18:51 +00002006 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00002007 if (FDecl)
2008 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002009
Sebastian Redl8b769972009-01-19 00:08:26 +00002010 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002011}
2012
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002013Action::OwningExprResult
2014Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2015 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002016 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002017 QualType literalType = QualType::getFromOpaquePtr(Ty);
2018 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002019 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002020 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002021
Eli Friedman8c2173d2008-05-20 05:22:08 +00002022 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002023 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002024 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2025 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002026 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2027 diag::err_typecheck_decl_incomplete_type,
2028 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002029 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002030
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002031 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002032 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002033 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002034
Chris Lattnere5cb5862008-12-04 23:50:19 +00002035 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002036 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002037 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002038 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002039 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002040 InitExpr.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002041 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
2042 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002043}
2044
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002045Action::OwningExprResult
2046Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2047 InitListDesignations &Designators,
2048 SourceLocation RBraceLoc) {
2049 unsigned NumInit = initlist.size();
2050 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002051
Steve Naroff0acc9c92007-09-15 18:49:24 +00002052 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00002053 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002054
Steve Naroff774e4152009-01-21 00:14:39 +00002055 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002056 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002057 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002058 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002059}
2060
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002061/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002062bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002063 UsualUnaryConversions(castExpr);
2064
2065 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2066 // type needs to be scalar.
2067 if (castType->isVoidType()) {
2068 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002069 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2070 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002071 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002072 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2073 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2074 (castType->isStructureType() || castType->isUnionType())) {
2075 // GCC struct/union extension: allow cast to self.
2076 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2077 << castType << castExpr->getSourceRange();
2078 } else if (castType->isUnionType()) {
2079 // GCC cast to union extension
2080 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2081 RecordDecl::field_iterator Field, FieldEnd;
2082 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2083 Field != FieldEnd; ++Field) {
2084 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2085 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2086 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2087 << castExpr->getSourceRange();
2088 break;
2089 }
2090 }
2091 if (Field == FieldEnd)
2092 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2093 << castExpr->getType() << castExpr->getSourceRange();
2094 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002095 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002096 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002097 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002098 }
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002099 } else if (!castExpr->getType()->isScalarType() &&
2100 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002101 return Diag(castExpr->getLocStart(),
2102 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002103 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002104 } else if (castExpr->getType()->isVectorType()) {
2105 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2106 return true;
2107 } else if (castType->isVectorType()) {
2108 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2109 return true;
2110 }
2111 return false;
2112}
2113
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002114bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002115 assert(VectorTy->isVectorType() && "Not a vector type!");
2116
2117 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002118 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002119 return Diag(R.getBegin(),
2120 Ty->isVectorType() ?
2121 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002122 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002123 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002124 } else
2125 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002126 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002127 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002128
2129 return false;
2130}
2131
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002132Action::OwningExprResult
2133Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2134 SourceLocation RParenLoc, ExprArg Op) {
2135 assert((Ty != 0) && (Op.get() != 0) &&
2136 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002137
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002138 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002139 QualType castType = QualType::getFromOpaquePtr(Ty);
2140
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002141 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002142 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002143 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002144 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002145}
2146
Chris Lattner98a425c2007-11-26 01:40:58 +00002147/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2148/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00002149inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
2150 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
2151 UsualUnaryConversions(cond);
2152 UsualUnaryConversions(lex);
2153 UsualUnaryConversions(rex);
2154 QualType condT = cond->getType();
2155 QualType lexT = lex->getType();
2156 QualType rexT = rex->getType();
2157
2158 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002159 if (!cond->isTypeDependent()) {
2160 if (!condT->isScalarType()) { // C99 6.5.15p2
2161 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
2162 return QualType();
2163 }
Chris Lattner4b009652007-07-25 00:24:17 +00002164 }
Chris Lattner992ae932008-01-06 22:42:25 +00002165
2166 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002167 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
2168 return Context.DependentTy;
2169
Chris Lattner992ae932008-01-06 22:42:25 +00002170 // If both operands have arithmetic type, do the usual arithmetic conversions
2171 // to find a common type: C99 6.5.15p3,5.
2172 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002173 UsualArithmeticConversions(lex, rex);
2174 return lex->getType();
2175 }
Chris Lattner992ae932008-01-06 22:42:25 +00002176
2177 // If both operands are the same structure or union type, the result is that
2178 // type.
Chris Lattner71225142007-07-31 21:27:01 +00002179 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00002180 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002181 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00002182 // "If both the operands have structure or union type, the result has
2183 // that type." This implies that CV qualifiers are dropped.
2184 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002185 }
Chris Lattner992ae932008-01-06 22:42:25 +00002186
2187 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002188 // The following || allows only one side to be void (a GCC-ism).
2189 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00002190 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002191 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2192 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00002193 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002194 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2195 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00002196 ImpCastExprToType(lex, Context.VoidTy);
2197 ImpCastExprToType(rex, Context.VoidTy);
2198 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002199 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002200 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2201 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002202 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2203 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002204 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002205 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002206 return lexT;
2207 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002208 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2209 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002210 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002211 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002212 return rexT;
2213 }
Chris Lattner0ac51632008-01-06 22:50:31 +00002214 // Handle the case where both operands are pointers before we handle null
2215 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00002216 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2217 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2218 // get the "pointed to" types
2219 QualType lhptee = LHSPT->getPointeeType();
2220 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002221
Chris Lattner71225142007-07-31 21:27:01 +00002222 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2223 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002224 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002225 // Figure out necessary qualifiers (C99 6.5.15p6)
2226 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002227 QualType destType = Context.getPointerType(destPointee);
2228 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2229 ImpCastExprToType(rex, destType); // promote to void*
2230 return destType;
2231 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002232 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002233 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002234 QualType destType = Context.getPointerType(destPointee);
2235 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2236 ImpCastExprToType(rex, destType); // promote to void*
2237 return destType;
2238 }
Chris Lattner4b009652007-07-25 00:24:17 +00002239
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002240 QualType compositeType = lexT;
2241
2242 // If either type is an Objective-C object type then check
2243 // compatibility according to Objective-C.
2244 if (Context.isObjCObjectPointerType(lexT) ||
2245 Context.isObjCObjectPointerType(rexT)) {
2246 // If both operands are interfaces and either operand can be
2247 // assigned to the other, use that type as the composite
2248 // type. This allows
2249 // xxx ? (A*) a : (B*) b
2250 // where B is a subclass of A.
2251 //
2252 // Additionally, as for assignment, if either type is 'id'
2253 // allow silent coercion. Finally, if the types are
2254 // incompatible then make sure to use 'id' as the composite
2255 // type so the result is acceptable for sending messages to.
2256
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002257 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
2258 // It could return the composite type.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002259 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2260 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2261 if (LHSIface && RHSIface &&
2262 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2263 compositeType = lexT;
2264 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002265 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002266 compositeType = rexT;
Steve Naroff17c03822009-02-12 17:52:19 +00002267 } else if (Context.isObjCIdStructType(lhptee) ||
2268 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002269 compositeType = Context.getObjCIdType();
2270 } else {
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002271 Diag(questionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
2272 << lexT << rexT
2273 << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002274 QualType incompatTy = Context.getObjCIdType();
2275 ImpCastExprToType(lex, incompatTy);
2276 ImpCastExprToType(rex, incompatTy);
2277 return incompatTy;
2278 }
2279 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2280 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002281 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002282 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002283 // In this situation, we assume void* type. No especially good
2284 // reason, but this is what gcc does, and we do have to pick
2285 // to get a consistent AST.
2286 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002287 ImpCastExprToType(lex, incompatTy);
2288 ImpCastExprToType(rex, incompatTy);
2289 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002290 }
2291 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002292 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2293 // differently qualified versions of compatible types, the result type is
2294 // a pointer to an appropriately qualified version of the *composite*
2295 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002296 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002297 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00002298 ImpCastExprToType(lex, compositeType);
2299 ImpCastExprToType(rex, compositeType);
2300 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002301 }
Chris Lattner4b009652007-07-25 00:24:17 +00002302 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002303 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2304 // evaluates to "struct objc_object *" (and is handled above when comparing
2305 // id with statically typed objects).
2306 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2307 // GCC allows qualified id and any Objective-C type to devolve to
2308 // id. Currently localizing to here until clear this should be
2309 // part of ObjCQualifiedIdTypesAreCompatible.
2310 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2311 (lexT->isObjCQualifiedIdType() &&
2312 Context.isObjCObjectPointerType(rexT)) ||
2313 (rexT->isObjCQualifiedIdType() &&
2314 Context.isObjCObjectPointerType(lexT))) {
2315 // FIXME: This is not the correct composite type. This only
2316 // happens to work because id can more or less be used anywhere,
2317 // however this may change the type of method sends.
2318 // FIXME: gcc adds some type-checking of the arguments and emits
2319 // (confusing) incompatible comparison warnings in some
2320 // cases. Investigate.
2321 QualType compositeType = Context.getObjCIdType();
2322 ImpCastExprToType(lex, compositeType);
2323 ImpCastExprToType(rex, compositeType);
2324 return compositeType;
2325 }
2326 }
2327
Steve Naroff3eac7692008-09-10 19:17:48 +00002328 // Selection between block pointer types is ok as long as they are the same.
2329 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2330 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2331 return lexT;
2332
Chris Lattner992ae932008-01-06 22:42:25 +00002333 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00002334 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002335 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002336 return QualType();
2337}
2338
Steve Naroff87d58b42007-09-16 03:34:24 +00002339/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002340/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002341Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2342 SourceLocation ColonLoc,
2343 ExprArg Cond, ExprArg LHS,
2344 ExprArg RHS) {
2345 Expr *CondExpr = (Expr *) Cond.get();
2346 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002347
2348 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2349 // was the condition.
2350 bool isLHSNull = LHSExpr == 0;
2351 if (isLHSNull)
2352 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002353
2354 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002355 RHSExpr, QuestionLoc);
2356 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002357 return ExprError();
2358
2359 Cond.release();
2360 LHS.release();
2361 RHS.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002362 return Owned(new (Context) ConditionalOperator(CondExpr,
2363 isLHSNull ? 0 : LHSExpr,
2364 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002365}
2366
Chris Lattner4b009652007-07-25 00:24:17 +00002367
2368// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2369// being closely modeled after the C99 spec:-). The odd characteristic of this
2370// routine is it effectively iqnores the qualifiers on the top level pointee.
2371// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2372// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00002373Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002374Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2375 QualType lhptee, rhptee;
2376
2377 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002378 lhptee = lhsType->getAsPointerType()->getPointeeType();
2379 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002380
2381 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002382 lhptee = Context.getCanonicalType(lhptee);
2383 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002384
Chris Lattner005ed752008-01-04 18:04:52 +00002385 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002386
2387 // C99 6.5.16.1p1: This following citation is common to constraints
2388 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2389 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00002390 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002391 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002392 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002393
2394 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2395 // incomplete type and the other is a pointer to a qualified or unqualified
2396 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002397 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002398 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002399 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002400
2401 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002402 assert(rhptee->isFunctionType());
2403 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002404 }
2405
2406 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002407 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002408 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002409
2410 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002411 assert(lhptee->isFunctionType());
2412 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002413 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002414
2415 // Check for ObjC interfaces
2416 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2417 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2418 if (LHSIface && RHSIface &&
2419 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2420 return ConvTy;
2421
2422 // ID acts sort of like void* for ObjC interfaces
Steve Naroff17c03822009-02-12 17:52:19 +00002423 if (LHSIface && Context.isObjCIdStructType(rhptee))
Eli Friedman0d9549b2008-08-22 00:56:42 +00002424 return ConvTy;
Steve Naroff17c03822009-02-12 17:52:19 +00002425 if (RHSIface && Context.isObjCIdStructType(lhptee))
Eli Friedman0d9549b2008-08-22 00:56:42 +00002426 return ConvTy;
2427
Chris Lattner4b009652007-07-25 00:24:17 +00002428 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2429 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002430 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2431 rhptee.getUnqualifiedType()))
2432 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002433 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002434}
2435
Steve Naroff3454b6c2008-09-04 15:10:53 +00002436/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2437/// block pointer types are compatible or whether a block and normal pointer
2438/// are compatible. It is more restrict than comparing two function pointer
2439// types.
2440Sema::AssignConvertType
2441Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2442 QualType rhsType) {
2443 QualType lhptee, rhptee;
2444
2445 // get the "pointed to" type (ignoring qualifiers at the top level)
2446 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2447 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2448
2449 // make sure we operate on the canonical type
2450 lhptee = Context.getCanonicalType(lhptee);
2451 rhptee = Context.getCanonicalType(rhptee);
2452
2453 AssignConvertType ConvTy = Compatible;
2454
2455 // For blocks we enforce that qualifiers are identical.
2456 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2457 ConvTy = CompatiblePointerDiscardsQualifiers;
2458
2459 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2460 return IncompatibleBlockPointer;
2461 return ConvTy;
2462}
2463
Chris Lattner4b009652007-07-25 00:24:17 +00002464/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2465/// has code to accommodate several GCC extensions when type checking
2466/// pointers. Here are some objectionable examples that GCC considers warnings:
2467///
2468/// int a, *pint;
2469/// short *pshort;
2470/// struct foo *pfoo;
2471///
2472/// pint = pshort; // warning: assignment from incompatible pointer type
2473/// a = pint; // warning: assignment makes integer from pointer without a cast
2474/// pint = a; // warning: assignment makes pointer from integer without a cast
2475/// pint = pfoo; // warning: assignment from incompatible pointer type
2476///
2477/// As a result, the code for dealing with pointers is more complex than the
2478/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002479///
Chris Lattner005ed752008-01-04 18:04:52 +00002480Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002481Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002482 // Get canonical types. We're not formatting these types, just comparing
2483 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002484 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2485 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002486
2487 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002488 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002489
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002490 // If the left-hand side is a reference type, then we are in a
2491 // (rare!) case where we've allowed the use of references in C,
2492 // e.g., as a parameter type in a built-in function. In this case,
2493 // just make sure that the type referenced is compatible with the
2494 // right-hand side type. The caller is responsible for adjusting
2495 // lhsType so that the resulting expression does not have reference
2496 // type.
2497 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2498 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002499 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002500 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002501 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002502
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002503 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2504 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002505 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002506 // Relax integer conversions like we do for pointers below.
2507 if (rhsType->isIntegerType())
2508 return IntToPointer;
2509 if (lhsType->isIntegerType())
2510 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002511 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002512 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002513
Nate Begemanc5f0f652008-07-14 18:02:46 +00002514 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002515 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002516 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2517 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002518 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002519
Nate Begemanc5f0f652008-07-14 18:02:46 +00002520 // If we are allowing lax vector conversions, and LHS and RHS are both
2521 // vectors, the total size only needs to be the same. This is a bitcast;
2522 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002523 if (getLangOptions().LaxVectorConversions &&
2524 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002525 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002526 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002527 }
2528 return Incompatible;
2529 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002530
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002531 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002532 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002533
Chris Lattner390564e2008-04-07 06:49:41 +00002534 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002535 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002536 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002537
Chris Lattner390564e2008-04-07 06:49:41 +00002538 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002539 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002540
Steve Naroffa982c712008-09-29 18:10:17 +00002541 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002542 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002543 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002544
2545 // Treat block pointers as objects.
2546 if (getLangOptions().ObjC1 &&
2547 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2548 return Compatible;
2549 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002550 return Incompatible;
2551 }
2552
2553 if (isa<BlockPointerType>(lhsType)) {
2554 if (rhsType->isIntegerType())
2555 return IntToPointer;
2556
Steve Naroffa982c712008-09-29 18:10:17 +00002557 // Treat block pointers as objects.
2558 if (getLangOptions().ObjC1 &&
2559 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2560 return Compatible;
2561
Steve Naroff3454b6c2008-09-04 15:10:53 +00002562 if (rhsType->isBlockPointerType())
2563 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2564
2565 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2566 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002567 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002568 }
Chris Lattner1853da22008-01-04 23:18:45 +00002569 return Incompatible;
2570 }
2571
Chris Lattner390564e2008-04-07 06:49:41 +00002572 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002573 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002574 if (lhsType == Context.BoolTy)
2575 return Compatible;
2576
2577 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002578 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002579
Chris Lattner390564e2008-04-07 06:49:41 +00002580 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002581 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002582
2583 if (isa<BlockPointerType>(lhsType) &&
2584 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002585 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002586 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002587 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002588
Chris Lattner1853da22008-01-04 23:18:45 +00002589 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002590 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002591 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002592 }
2593 return Incompatible;
2594}
2595
Chris Lattner005ed752008-01-04 18:04:52 +00002596Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002597Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002598 if (getLangOptions().CPlusPlus) {
2599 if (!lhsType->isRecordType()) {
2600 // C++ 5.17p3: If the left operand is not of class type, the
2601 // expression is implicitly converted (C++ 4) to the
2602 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002603 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2604 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002605 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002606 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002607 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002608 }
2609
2610 // FIXME: Currently, we fall through and treat C++ classes like C
2611 // structures.
2612 }
2613
Steve Naroffcdee22d2007-11-27 17:58:44 +00002614 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2615 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002616 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2617 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002618 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002619 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002620 return Compatible;
2621 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002622
2623 // We don't allow conversion of non-null-pointer constants to integers.
2624 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2625 return IntToBlockPointer;
2626
Chris Lattner5f505bf2007-10-16 02:55:40 +00002627 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002628 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002629 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002630 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002631 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002632 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002633 if (!lhsType->isReferenceType())
2634 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002635
Chris Lattner005ed752008-01-04 18:04:52 +00002636 Sema::AssignConvertType result =
2637 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002638
2639 // C99 6.5.16.1p2: The value of the right operand is converted to the
2640 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002641 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2642 // so that we can use references in built-in functions even in C.
2643 // The getNonReferenceType() call makes sure that the resulting expression
2644 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002645 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002646 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002647 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002648}
2649
Chris Lattner005ed752008-01-04 18:04:52 +00002650Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002651Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2652 return CheckAssignmentConstraints(lhsType, rhsType);
2653}
2654
Chris Lattner1eafdea2008-11-18 01:30:42 +00002655QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002656 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002657 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002658 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002659 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002660}
2661
Chris Lattner1eafdea2008-11-18 01:30:42 +00002662inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002663 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002664 // For conversion purposes, we ignore any qualifiers.
2665 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002666 QualType lhsType =
2667 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2668 QualType rhsType =
2669 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002670
Nate Begemanc5f0f652008-07-14 18:02:46 +00002671 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002672 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002673 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002674
Nate Begemanc5f0f652008-07-14 18:02:46 +00002675 // Handle the case of a vector & extvector type of the same size and element
2676 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00002677 if (getLangOptions().LaxVectorConversions) {
2678 // FIXME: Should we warn here?
2679 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002680 if (const VectorType *RV = rhsType->getAsVectorType())
2681 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00002682 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002683 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00002684 }
2685 }
2686 }
2687
Nate Begemanc5f0f652008-07-14 18:02:46 +00002688 // If the lhs is an extended vector and the rhs is a scalar of the same type
2689 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002690 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002691 QualType eltType = V->getElementType();
2692
2693 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2694 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2695 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002696 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002697 return lhsType;
2698 }
2699 }
2700
Nate Begemanc5f0f652008-07-14 18:02:46 +00002701 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002702 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002703 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002704 QualType eltType = V->getElementType();
2705
2706 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2707 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2708 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002709 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002710 return rhsType;
2711 }
2712 }
2713
Chris Lattner4b009652007-07-25 00:24:17 +00002714 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002715 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002716 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002717 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002718 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00002719}
2720
Chris Lattner4b009652007-07-25 00:24:17 +00002721inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002722 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002723{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002724 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002725 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002726
Steve Naroff8f708362007-08-24 19:07:16 +00002727 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002728
Chris Lattner4b009652007-07-25 00:24:17 +00002729 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002730 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002731 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002732}
2733
2734inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002735 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002736{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002737 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2738 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2739 return CheckVectorOperands(Loc, lex, rex);
2740 return InvalidOperands(Loc, lex, rex);
2741 }
Chris Lattner4b009652007-07-25 00:24:17 +00002742
Steve Naroff8f708362007-08-24 19:07:16 +00002743 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002744
Chris Lattner4b009652007-07-25 00:24:17 +00002745 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002746 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002747 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002748}
2749
2750inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002751 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002752{
2753 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002754 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002755
Steve Naroff8f708362007-08-24 19:07:16 +00002756 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002757
Chris Lattner4b009652007-07-25 00:24:17 +00002758 // handle the common case first (both operands are arithmetic).
2759 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002760 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002761
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002762 // Put any potential pointer into PExp
2763 Expr* PExp = lex, *IExp = rex;
2764 if (IExp->getType()->isPointerType())
2765 std::swap(PExp, IExp);
2766
2767 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2768 if (IExp->getType()->isIntegerType()) {
2769 // Check for arithmetic on pointers to incomplete types
2770 if (!PTy->getPointeeType()->isObjectType()) {
2771 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002772 if (getLangOptions().CPlusPlus) {
2773 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2774 << lex->getSourceRange() << rex->getSourceRange();
2775 return QualType();
2776 }
2777
2778 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00002779 Diag(Loc, diag::ext_gnu_void_ptr)
2780 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002781 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002782 if (getLangOptions().CPlusPlus) {
2783 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2784 << lex->getType() << lex->getSourceRange();
2785 return QualType();
2786 }
2787
2788 // GNU extension: arithmetic on pointer to function
2789 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002790 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002791 } else {
2792 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2793 diag::err_typecheck_arithmetic_incomplete_type,
2794 lex->getSourceRange(), SourceRange(),
2795 lex->getType());
2796 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002797 }
2798 }
2799 return PExp->getType();
2800 }
2801 }
2802
Chris Lattner1eafdea2008-11-18 01:30:42 +00002803 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002804}
2805
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002806// C99 6.5.6
2807QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002808 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002809 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002810 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002811
Steve Naroff8f708362007-08-24 19:07:16 +00002812 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002813
Chris Lattnerf6da2912007-12-09 21:53:25 +00002814 // Enforce type constraints: C99 6.5.6p3.
2815
2816 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002817 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002818 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002819
2820 // Either ptr - int or ptr - ptr.
2821 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002822 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002823
Chris Lattnerf6da2912007-12-09 21:53:25 +00002824 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002825 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002826 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002827 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002828 Diag(Loc, diag::ext_gnu_void_ptr)
2829 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00002830 } else if (lpointee->isFunctionType()) {
2831 if (getLangOptions().CPlusPlus) {
2832 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2833 << lex->getType() << lex->getSourceRange();
2834 return QualType();
2835 }
2836
2837 // GNU extension: arithmetic on pointer to function
2838 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2839 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002840 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002841 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002842 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002843 return QualType();
2844 }
2845 }
2846
2847 // The result type of a pointer-int computation is the pointer type.
2848 if (rex->getType()->isIntegerType())
2849 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002850
Chris Lattnerf6da2912007-12-09 21:53:25 +00002851 // Handle pointer-pointer subtractions.
2852 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002853 QualType rpointee = RHSPTy->getPointeeType();
2854
Chris Lattnerf6da2912007-12-09 21:53:25 +00002855 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002856 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002857 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002858 if (rpointee->isVoidType()) {
2859 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002860 Diag(Loc, diag::ext_gnu_void_ptr)
2861 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00002862 } else if (rpointee->isFunctionType()) {
2863 if (getLangOptions().CPlusPlus) {
2864 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2865 << rex->getType() << rex->getSourceRange();
2866 return QualType();
2867 }
2868
2869 // GNU extension: arithmetic on pointer to function
2870 if (!lpointee->isFunctionType())
2871 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2872 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002873 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002874 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002875 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002876 return QualType();
2877 }
2878 }
2879
2880 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002881 if (!Context.typesAreCompatible(
2882 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2883 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002884 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002885 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002886 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002887 return QualType();
2888 }
2889
2890 return Context.getPointerDiffType();
2891 }
2892 }
2893
Chris Lattner1eafdea2008-11-18 01:30:42 +00002894 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002895}
2896
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002897// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002898QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002899 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002900 // C99 6.5.7p2: Each of the operands shall have integer type.
2901 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002902 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002903
Chris Lattner2c8bff72007-12-12 05:47:28 +00002904 // Shifts don't perform usual arithmetic conversions, they just do integer
2905 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002906 if (!isCompAssign)
2907 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002908 UsualUnaryConversions(rex);
2909
2910 // "The type of the result is that of the promoted left operand."
2911 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002912}
2913
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002914// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002915QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002916 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002917 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002918 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002919
Chris Lattner254f3bc2007-08-26 01:18:55 +00002920 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002921 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2922 UsualArithmeticConversions(lex, rex);
2923 else {
2924 UsualUnaryConversions(lex);
2925 UsualUnaryConversions(rex);
2926 }
Chris Lattner4b009652007-07-25 00:24:17 +00002927 QualType lType = lex->getType();
2928 QualType rType = rex->getType();
2929
Ted Kremenek486509e2007-10-29 17:13:39 +00002930 // For non-floating point types, check for self-comparisons of the form
2931 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2932 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002933 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002934 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2935 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002936 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002937 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002938 }
2939
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002940 // The result of comparisons is 'bool' in C++, 'int' in C.
2941 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2942
Chris Lattner254f3bc2007-08-26 01:18:55 +00002943 if (isRelational) {
2944 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002945 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002946 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002947 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002948 if (lType->isFloatingType()) {
2949 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002950 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002951 }
2952
Chris Lattner254f3bc2007-08-26 01:18:55 +00002953 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002954 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002955 }
Chris Lattner4b009652007-07-25 00:24:17 +00002956
Chris Lattner22be8422007-08-26 01:10:14 +00002957 bool LHSIsNull = lex->isNullPointerConstant(Context);
2958 bool RHSIsNull = rex->isNullPointerConstant(Context);
2959
Chris Lattner254f3bc2007-08-26 01:18:55 +00002960 // All of the following pointer related warnings are GCC extensions, except
2961 // when handling null pointer constants. One day, we can consider making them
2962 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002963 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002964 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002965 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002966 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002967 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002968
Steve Naroff3b435622007-11-13 14:57:38 +00002969 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002970 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2971 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002972 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00002973 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002974 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002975 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002976 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002977 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002978 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002979 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002980 // Handle block pointer types.
2981 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2982 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2983 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2984
2985 if (!LHSIsNull && !RHSIsNull &&
2986 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002987 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002988 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00002989 }
2990 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002991 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002992 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002993 // Allow block pointers to be compared with null pointer constants.
2994 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2995 (lType->isPointerType() && rType->isBlockPointerType())) {
2996 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002997 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002998 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00002999 }
3000 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003001 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003002 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003003
Steve Naroff936c4362008-06-03 14:04:54 +00003004 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003005 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003006 const PointerType *LPT = lType->getAsPointerType();
3007 const PointerType *RPT = rType->getAsPointerType();
3008 bool LPtrToVoid = LPT ?
3009 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
3010 bool RPtrToVoid = RPT ?
3011 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
3012
3013 if (!LPtrToVoid && !RPtrToVoid &&
3014 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003015 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003016 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003017 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003018 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003019 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003020 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003021 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003022 }
Steve Naroff936c4362008-06-03 14:04:54 +00003023 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3024 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003025 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003026 } else {
3027 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003028 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003029 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003030 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003031 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003032 }
Steve Naroff936c4362008-06-03 14:04:54 +00003033 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003034 }
Steve Naroff936c4362008-06-03 14:04:54 +00003035 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
3036 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003037 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003038 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003039 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003040 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003041 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003042 }
Steve Naroff936c4362008-06-03 14:04:54 +00003043 if (lType->isIntegerType() &&
3044 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003045 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003046 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003047 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003048 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003049 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003050 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003051 // Handle block pointers.
3052 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3053 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003054 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003055 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003056 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003057 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003058 }
3059 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3060 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003061 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003062 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003063 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003064 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003065 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003066 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003067}
3068
Nate Begemanc5f0f652008-07-14 18:02:46 +00003069/// CheckVectorCompareOperands - vector comparisons are a clang extension that
3070/// operates on extended vector types. Instead of producing an IntTy result,
3071/// like a scalar comparison, a vector comparison produces a vector of integer
3072/// types.
3073QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003074 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003075 bool isRelational) {
3076 // Check to make sure we're operating on vectors of the same type and width,
3077 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003078 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003079 if (vType.isNull())
3080 return vType;
3081
3082 QualType lType = lex->getType();
3083 QualType rType = rex->getType();
3084
3085 // For non-floating point types, check for self-comparisons of the form
3086 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3087 // often indicate logic errors in the program.
3088 if (!lType->isFloatingType()) {
3089 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3090 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3091 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003092 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003093 }
3094
3095 // Check for comparisons of floating point operands using != and ==.
3096 if (!isRelational && lType->isFloatingType()) {
3097 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003098 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003099 }
3100
3101 // Return the type for the comparison, which is the same as vector type for
3102 // integer vectors, or an integer type of identical size and number of
3103 // elements for floating point vectors.
3104 if (lType->isIntegerType())
3105 return lType;
3106
3107 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003108 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003109 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003110 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003111 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3112 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3113
3114 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3115 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003116 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3117}
3118
Chris Lattner4b009652007-07-25 00:24:17 +00003119inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00003120 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003121{
3122 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003123 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003124
Steve Naroff8f708362007-08-24 19:07:16 +00003125 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00003126
3127 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003128 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003129 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003130}
3131
3132inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00003133 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003134{
3135 UsualUnaryConversions(lex);
3136 UsualUnaryConversions(rex);
3137
Eli Friedmanbea3f842008-05-13 20:16:47 +00003138 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003139 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003140 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003141}
3142
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003143/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3144/// is a read-only property; return true if so. A readonly property expression
3145/// depends on various declarations and thus must be treated specially.
3146///
3147static bool IsReadonlyProperty(Expr *E, Sema &S)
3148{
3149 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3150 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3151 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3152 QualType BaseType = PropExpr->getBase()->getType();
3153 if (const PointerType *PTy = BaseType->getAsPointerType())
3154 if (const ObjCInterfaceType *IFTy =
3155 PTy->getPointeeType()->getAsObjCInterfaceType())
3156 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3157 if (S.isPropertyReadonly(PDecl, IFace))
3158 return true;
3159 }
3160 }
3161 return false;
3162}
3163
Chris Lattner4c2642c2008-11-18 01:22:49 +00003164/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3165/// emit an error and return true. If so, return false.
3166static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003167 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3168 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3169 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003170 if (IsLV == Expr::MLV_Valid)
3171 return false;
3172
3173 unsigned Diag = 0;
3174 bool NeedType = false;
3175 switch (IsLV) { // C99 6.5.16p2
3176 default: assert(0 && "Unknown result from isModifiableLvalue!");
3177 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00003178 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003179 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3180 NeedType = true;
3181 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003182 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003183 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3184 NeedType = true;
3185 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003186 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003187 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3188 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003189 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003190 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3191 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003192 case Expr::MLV_IncompleteType:
3193 case Expr::MLV_IncompleteVoidType:
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003194 return S.DiagnoseIncompleteType(Loc, E->getType(),
3195 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3196 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003197 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003198 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3199 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003200 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003201 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3202 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003203 case Expr::MLV_ReadonlyProperty:
3204 Diag = diag::error_readonly_property_assignment;
3205 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003206 case Expr::MLV_NoSetterProperty:
3207 Diag = diag::error_nosetter_property_assignment;
3208 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003209 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003210
Chris Lattner4c2642c2008-11-18 01:22:49 +00003211 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003212 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003213 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003214 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003215 return true;
3216}
3217
3218
3219
3220// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003221QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3222 SourceLocation Loc,
3223 QualType CompoundType) {
3224 // Verify that LHS is a modifiable lvalue, and emit error if not.
3225 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003226 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003227
3228 QualType LHSType = LHS->getType();
3229 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003230
Chris Lattner005ed752008-01-04 18:04:52 +00003231 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003232 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003233 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003234 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003235 // Special case of NSObject attributes on c-style pointer types.
3236 if (ConvTy == IncompatiblePointer &&
3237 ((Context.isObjCNSObjectType(LHSType) &&
3238 Context.isObjCObjectPointerType(RHSType)) ||
3239 (Context.isObjCNSObjectType(RHSType) &&
3240 Context.isObjCObjectPointerType(LHSType))))
3241 ConvTy = Compatible;
3242
Chris Lattner34c85082008-08-21 18:04:13 +00003243 // If the RHS is a unary plus or minus, check to see if they = and + are
3244 // right next to each other. If so, the user may have typo'd "x =+ 4"
3245 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003246 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003247 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3248 RHSCheck = ICE->getSubExpr();
3249 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3250 if ((UO->getOpcode() == UnaryOperator::Plus ||
3251 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003252 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003253 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003254 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003255 Diag(Loc, diag::warn_not_compound_assign)
3256 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3257 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003258 }
3259 } else {
3260 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003261 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003262 }
Chris Lattner005ed752008-01-04 18:04:52 +00003263
Chris Lattner1eafdea2008-11-18 01:30:42 +00003264 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3265 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003266 return QualType();
3267
Chris Lattner4b009652007-07-25 00:24:17 +00003268 // C99 6.5.16p3: The type of an assignment expression is the type of the
3269 // left operand unless the left operand has qualified type, in which case
3270 // it is the unqualified version of the type of the left operand.
3271 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3272 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003273 // C++ 5.17p1: the type of the assignment expression is that of its left
3274 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003275 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003276}
3277
Chris Lattner1eafdea2008-11-18 01:30:42 +00003278// C99 6.5.17
3279QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3280 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00003281
3282 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003283 DefaultFunctionArrayConversion(RHS);
3284 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003285}
3286
3287/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3288/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003289QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3290 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003291 QualType ResType = Op->getType();
3292 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003293
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003294 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3295 // Decrement of bool is not allowed.
3296 if (!isInc) {
3297 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3298 return QualType();
3299 }
3300 // Increment of bool sets it to true, but is deprecated.
3301 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3302 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003303 // OK!
3304 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3305 // C99 6.5.2.4p2, 6.5.6p2
3306 if (PT->getPointeeType()->isObjectType()) {
3307 // Pointer to object is ok!
3308 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003309 if (getLangOptions().CPlusPlus) {
3310 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3311 << Op->getSourceRange();
3312 return QualType();
3313 }
3314
3315 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003316 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003317 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003318 if (getLangOptions().CPlusPlus) {
3319 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3320 << Op->getType() << Op->getSourceRange();
3321 return QualType();
3322 }
3323
3324 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003325 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003326 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003327 } else {
3328 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3329 diag::err_typecheck_arithmetic_incomplete_type,
3330 Op->getSourceRange(), SourceRange(),
3331 ResType);
3332 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003333 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003334 } else if (ResType->isComplexType()) {
3335 // C99 does not support ++/-- on complex types, we allow as an extension.
3336 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003337 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003338 } else {
3339 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003340 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003341 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003342 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00003343 // At this point, we know we have a real, complex or pointer type.
3344 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003345 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003346 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003347 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003348}
3349
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003350/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003351/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003352/// where the declaration is needed for type checking. We only need to
3353/// handle cases when the expression references a function designator
3354/// or is an lvalue. Here are some examples:
3355/// - &(x) => x
3356/// - &*****f => f for f a function designator.
3357/// - &s.xx => s
3358/// - &s.zz[1].yy -> s, if zz is an array
3359/// - *(x + 1) -> x, if x is an array
3360/// - &"123"[2] -> 0
3361/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003362static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003363 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003364 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003365 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003366 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003367 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003368 // Fields cannot be declared with a 'register' storage class.
3369 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003370 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003371 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003372 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003373 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003374 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003375
Douglas Gregord2baafd2008-10-21 16:13:35 +00003376 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003377 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003378 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003379 return 0;
3380 else
3381 return VD;
3382 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003383 case Stmt::UnaryOperatorClass: {
3384 UnaryOperator *UO = cast<UnaryOperator>(E);
3385
3386 switch(UO->getOpcode()) {
3387 case UnaryOperator::Deref: {
3388 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003389 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3390 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3391 if (!VD || VD->getType()->isPointerType())
3392 return 0;
3393 return VD;
3394 }
3395 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003396 }
3397 case UnaryOperator::Real:
3398 case UnaryOperator::Imag:
3399 case UnaryOperator::Extension:
3400 return getPrimaryDecl(UO->getSubExpr());
3401 default:
3402 return 0;
3403 }
3404 }
3405 case Stmt::BinaryOperatorClass: {
3406 BinaryOperator *BO = cast<BinaryOperator>(E);
3407
3408 // Handle cases involving pointer arithmetic. The result of an
3409 // Assign or AddAssign is not an lvalue so they can be ignored.
3410
3411 // (x + n) or (n + x) => x
3412 if (BO->getOpcode() == BinaryOperator::Add) {
3413 if (BO->getLHS()->getType()->isPointerType()) {
3414 return getPrimaryDecl(BO->getLHS());
3415 } else if (BO->getRHS()->getType()->isPointerType()) {
3416 return getPrimaryDecl(BO->getRHS());
3417 }
3418 }
3419
3420 return 0;
3421 }
Chris Lattner4b009652007-07-25 00:24:17 +00003422 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003423 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003424 case Stmt::ImplicitCastExprClass:
3425 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003426 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003427 default:
3428 return 0;
3429 }
3430}
3431
3432/// CheckAddressOfOperand - The operand of & must be either a function
3433/// designator or an lvalue designating an object. If it is an lvalue, the
3434/// object cannot be declared with storage class register or be a bit field.
3435/// Note: The usual conversions are *not* applied to the operand of the &
3436/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00003437/// In C++, the operand might be an overloaded function name, in which case
3438/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003439QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003440 if (op->isTypeDependent())
3441 return Context.DependentTy;
3442
Steve Naroff9c6c3592008-01-13 17:10:08 +00003443 if (getLangOptions().C99) {
3444 // Implement C99-only parts of addressof rules.
3445 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3446 if (uOp->getOpcode() == UnaryOperator::Deref)
3447 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3448 // (assuming the deref expression is valid).
3449 return uOp->getSubExpr()->getType();
3450 }
3451 // Technically, there should be a check for array subscript
3452 // expressions here, but the result of one is always an lvalue anyway.
3453 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003454 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003455 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003456
Chris Lattner4b009652007-07-25 00:24:17 +00003457 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003458 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3459 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003460 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3461 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003462 return QualType();
3463 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003464 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003465 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3466 if (Field->isBitField()) {
3467 Diag(OpLoc, diag::err_typecheck_address_of)
3468 << "bit-field" << op->getSourceRange();
3469 return QualType();
3470 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003471 }
3472 // Check for Apple extension for accessing vector components.
3473 } else if (isa<ArraySubscriptExpr>(op) &&
3474 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003475 Diag(OpLoc, diag::err_typecheck_address_of)
3476 << "vector" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003477 return QualType();
3478 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00003479 // We have an lvalue with a decl. Make sure the decl is not declared
3480 // with the register storage-class specifier.
3481 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3482 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003483 Diag(OpLoc, diag::err_typecheck_address_of)
3484 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003485 return QualType();
3486 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003487 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003488 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003489 } else if (isa<FieldDecl>(dcl)) {
3490 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00003491 // Could be a pointer to member, though, if there is an explicit
3492 // scope qualifier for the class.
3493 if (isa<QualifiedDeclRefExpr>(op)) {
3494 DeclContext *Ctx = dcl->getDeclContext();
3495 if (Ctx && Ctx->isRecord())
3496 return Context.getMemberPointerType(op->getType(),
3497 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3498 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003499 } else if (isa<FunctionDecl>(dcl)) {
3500 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00003501 // As above.
3502 if (isa<QualifiedDeclRefExpr>(op)) {
3503 DeclContext *Ctx = dcl->getDeclContext();
3504 if (Ctx && Ctx->isRecord())
3505 return Context.getMemberPointerType(op->getType(),
3506 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3507 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003508 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003509 else
Chris Lattner4b009652007-07-25 00:24:17 +00003510 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003511 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00003512
Chris Lattner4b009652007-07-25 00:24:17 +00003513 // If the operand has type "type", the result has type "pointer to type".
3514 return Context.getPointerType(op->getType());
3515}
3516
Chris Lattnerda5c0872008-11-23 09:13:29 +00003517QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3518 UsualUnaryConversions(Op);
3519 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003520
Chris Lattnerda5c0872008-11-23 09:13:29 +00003521 // Note that per both C89 and C99, this is always legal, even if ptype is an
3522 // incomplete type or void. It would be possible to warn about dereferencing
3523 // a void pointer, but it's completely well-defined, and such a warning is
3524 // unlikely to catch any mistakes.
3525 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003526 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00003527
Chris Lattner77d52da2008-11-20 06:06:08 +00003528 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003529 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003530 return QualType();
3531}
3532
3533static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3534 tok::TokenKind Kind) {
3535 BinaryOperator::Opcode Opc;
3536 switch (Kind) {
3537 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00003538 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3539 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003540 case tok::star: Opc = BinaryOperator::Mul; break;
3541 case tok::slash: Opc = BinaryOperator::Div; break;
3542 case tok::percent: Opc = BinaryOperator::Rem; break;
3543 case tok::plus: Opc = BinaryOperator::Add; break;
3544 case tok::minus: Opc = BinaryOperator::Sub; break;
3545 case tok::lessless: Opc = BinaryOperator::Shl; break;
3546 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3547 case tok::lessequal: Opc = BinaryOperator::LE; break;
3548 case tok::less: Opc = BinaryOperator::LT; break;
3549 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3550 case tok::greater: Opc = BinaryOperator::GT; break;
3551 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3552 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3553 case tok::amp: Opc = BinaryOperator::And; break;
3554 case tok::caret: Opc = BinaryOperator::Xor; break;
3555 case tok::pipe: Opc = BinaryOperator::Or; break;
3556 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3557 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3558 case tok::equal: Opc = BinaryOperator::Assign; break;
3559 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3560 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3561 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3562 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3563 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3564 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3565 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3566 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3567 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3568 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3569 case tok::comma: Opc = BinaryOperator::Comma; break;
3570 }
3571 return Opc;
3572}
3573
3574static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3575 tok::TokenKind Kind) {
3576 UnaryOperator::Opcode Opc;
3577 switch (Kind) {
3578 default: assert(0 && "Unknown unary op!");
3579 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3580 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3581 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3582 case tok::star: Opc = UnaryOperator::Deref; break;
3583 case tok::plus: Opc = UnaryOperator::Plus; break;
3584 case tok::minus: Opc = UnaryOperator::Minus; break;
3585 case tok::tilde: Opc = UnaryOperator::Not; break;
3586 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003587 case tok::kw___real: Opc = UnaryOperator::Real; break;
3588 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3589 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3590 }
3591 return Opc;
3592}
3593
Douglas Gregord7f915e2008-11-06 23:29:22 +00003594/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3595/// operator @p Opc at location @c TokLoc. This routine only supports
3596/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003597Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3598 unsigned Op,
3599 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003600 QualType ResultTy; // Result type of the binary operator.
3601 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3602 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3603
3604 switch (Opc) {
3605 default:
3606 assert(0 && "Unknown binary expr!");
3607 case BinaryOperator::Assign:
3608 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3609 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003610 case BinaryOperator::PtrMemD:
3611 case BinaryOperator::PtrMemI:
3612 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3613 Opc == BinaryOperator::PtrMemI);
3614 break;
3615 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003616 case BinaryOperator::Div:
3617 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3618 break;
3619 case BinaryOperator::Rem:
3620 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3621 break;
3622 case BinaryOperator::Add:
3623 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3624 break;
3625 case BinaryOperator::Sub:
3626 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3627 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003628 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003629 case BinaryOperator::Shr:
3630 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3631 break;
3632 case BinaryOperator::LE:
3633 case BinaryOperator::LT:
3634 case BinaryOperator::GE:
3635 case BinaryOperator::GT:
3636 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3637 break;
3638 case BinaryOperator::EQ:
3639 case BinaryOperator::NE:
3640 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3641 break;
3642 case BinaryOperator::And:
3643 case BinaryOperator::Xor:
3644 case BinaryOperator::Or:
3645 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3646 break;
3647 case BinaryOperator::LAnd:
3648 case BinaryOperator::LOr:
3649 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3650 break;
3651 case BinaryOperator::MulAssign:
3652 case BinaryOperator::DivAssign:
3653 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3654 if (!CompTy.isNull())
3655 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3656 break;
3657 case BinaryOperator::RemAssign:
3658 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3659 if (!CompTy.isNull())
3660 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3661 break;
3662 case BinaryOperator::AddAssign:
3663 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3664 if (!CompTy.isNull())
3665 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3666 break;
3667 case BinaryOperator::SubAssign:
3668 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3669 if (!CompTy.isNull())
3670 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3671 break;
3672 case BinaryOperator::ShlAssign:
3673 case BinaryOperator::ShrAssign:
3674 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3675 if (!CompTy.isNull())
3676 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3677 break;
3678 case BinaryOperator::AndAssign:
3679 case BinaryOperator::XorAssign:
3680 case BinaryOperator::OrAssign:
3681 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3682 if (!CompTy.isNull())
3683 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3684 break;
3685 case BinaryOperator::Comma:
3686 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3687 break;
3688 }
3689 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003690 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00003691 if (CompTy.isNull())
3692 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3693 else
3694 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Steve Naroff8b9a98d2009-01-20 21:06:31 +00003695 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003696}
3697
Chris Lattner4b009652007-07-25 00:24:17 +00003698// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003699Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3700 tok::TokenKind Kind,
3701 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003702 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003703 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003704
Steve Naroff87d58b42007-09-16 03:34:24 +00003705 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3706 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003707
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003708 // If either expression is type-dependent, just build the AST.
3709 // FIXME: We'll need to perform some caching of the result of name
3710 // lookup for operator+.
3711 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff774e4152009-01-21 00:14:39 +00003712 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3713 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003714 Context.DependentTy,
3715 Context.DependentTy, TokLoc));
Steve Naroff774e4152009-01-21 00:14:39 +00003716 else
Sebastian Redl95216a62009-02-07 00:15:38 +00003717 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc,
3718 Context.DependentTy, TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003719 }
3720
Sebastian Redl95216a62009-02-07 00:15:38 +00003721 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD &&
Douglas Gregord7f915e2008-11-06 23:29:22 +00003722 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3723 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003724 // If this is one of the assignment operators, we only perform
3725 // overload resolution if the left-hand side is a class or
3726 // enumeration type (C++ [expr.ass]p3).
3727 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3728 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3729 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3730 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003731
Douglas Gregord7f915e2008-11-06 23:29:22 +00003732 // Determine which overloaded operator we're dealing with.
3733 static const OverloadedOperatorKind OverOps[] = {
Sebastian Redl95216a62009-02-07 00:15:38 +00003734 // Overloading .* is not possible.
3735 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar,
Douglas Gregord7f915e2008-11-06 23:29:22 +00003736 OO_Star, OO_Slash, OO_Percent,
3737 OO_Plus, OO_Minus,
3738 OO_LessLess, OO_GreaterGreater,
3739 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3740 OO_EqualEqual, OO_ExclaimEqual,
3741 OO_Amp,
3742 OO_Caret,
3743 OO_Pipe,
3744 OO_AmpAmp,
3745 OO_PipePipe,
3746 OO_Equal, OO_StarEqual,
3747 OO_SlashEqual, OO_PercentEqual,
3748 OO_PlusEqual, OO_MinusEqual,
3749 OO_LessLessEqual, OO_GreaterGreaterEqual,
3750 OO_AmpEqual, OO_CaretEqual,
3751 OO_PipeEqual,
3752 OO_Comma
3753 };
3754 OverloadedOperatorKind OverOp = OverOps[Opc];
3755
Douglas Gregor5ed15042008-11-18 23:14:02 +00003756 // Add the appropriate overloaded operators (C++ [over.match.oper])
3757 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003758 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003759 Expr *Args[2] = { lhs, rhs };
Douglas Gregor48a87322009-02-04 16:44:47 +00003760 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3761 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003762
3763 // Perform overload resolution.
3764 OverloadCandidateSet::iterator Best;
3765 switch (BestViableFunction(CandidateSet, Best)) {
3766 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003767 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003768 FunctionDecl *FnDecl = Best->Function;
3769
Douglas Gregor70d26122008-11-12 17:17:38 +00003770 if (FnDecl) {
3771 // We matched an overloaded operator. Build a call to that
3772 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003773
Douglas Gregor70d26122008-11-12 17:17:38 +00003774 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003775 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3776 if (PerformObjectArgumentInitialization(lhs, Method) ||
3777 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3778 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003779 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003780 } else {
3781 // Convert the arguments.
3782 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3783 "passing") ||
3784 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3785 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003786 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003787 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003788
Douglas Gregor70d26122008-11-12 17:17:38 +00003789 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003790 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003791 = FnDecl->getType()->getAsFunctionType()->getResultType();
3792 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003793
Douglas Gregor70d26122008-11-12 17:17:38 +00003794 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003795 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3796 SourceLocation());
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003797 UsualUnaryConversions(FnExpr);
3798
Ted Kremenek362abcd2009-02-09 20:51:47 +00003799 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00003800 ResultTy, TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003801 } else {
3802 // We matched a built-in operator. Convert the arguments, then
3803 // break out so that we will build the appropriate built-in
3804 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003805 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3806 Best->Conversions[0], "passing") ||
3807 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3808 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003809 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003810
3811 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003812 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003813 }
3814
3815 case OR_No_Viable_Function:
3816 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003817 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003818 break;
3819
3820 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003821 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3822 << BinaryOperator::getOpcodeStr(Opc)
3823 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003824 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003825 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003826 }
3827
Douglas Gregor70d26122008-11-12 17:17:38 +00003828 // Either we found no viable overloaded operator or we matched a
3829 // built-in operator. In either case, fall through to trying to
3830 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003831 }
3832
Douglas Gregord7f915e2008-11-06 23:29:22 +00003833 // Build a built-in binary operation.
3834 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003835}
3836
3837// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00003838Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3839 tok::TokenKind Op, ExprArg input) {
3840 // FIXME: Input is modified later, but smart pointer not reassigned.
3841 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00003842 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003843
3844 if (getLangOptions().CPlusPlus &&
3845 (Input->getType()->isRecordType()
3846 || Input->getType()->isEnumeralType())) {
3847 // Determine which overloaded operator we're dealing with.
3848 static const OverloadedOperatorKind OverOps[] = {
3849 OO_None, OO_None,
3850 OO_PlusPlus, OO_MinusMinus,
3851 OO_Amp, OO_Star,
3852 OO_Plus, OO_Minus,
3853 OO_Tilde, OO_Exclaim,
3854 OO_None, OO_None,
3855 OO_None,
3856 OO_None
3857 };
3858 OverloadedOperatorKind OverOp = OverOps[Opc];
3859
3860 // Add the appropriate overloaded operators (C++ [over.match.oper])
3861 // to the candidate set.
3862 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00003863 if (OverOp != OO_None &&
3864 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
3865 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003866
3867 // Perform overload resolution.
3868 OverloadCandidateSet::iterator Best;
3869 switch (BestViableFunction(CandidateSet, Best)) {
3870 case OR_Success: {
3871 // We found a built-in operator or an overloaded operator.
3872 FunctionDecl *FnDecl = Best->Function;
3873
3874 if (FnDecl) {
3875 // We matched an overloaded operator. Build a call to that
3876 // operator.
3877
3878 // Convert the arguments.
3879 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3880 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00003881 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003882 } else {
3883 // Convert the arguments.
3884 if (PerformCopyInitialization(Input,
3885 FnDecl->getParamDecl(0)->getType(),
3886 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003887 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003888 }
3889
3890 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00003891 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003892 = FnDecl->getType()->getAsFunctionType()->getResultType();
3893 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00003894
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003895 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003896 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3897 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003898 UsualUnaryConversions(FnExpr);
3899
Sebastian Redl8b769972009-01-19 00:08:26 +00003900 input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00003901 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input, 1,
Steve Naroff774e4152009-01-21 00:14:39 +00003902 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003903 } else {
3904 // We matched a built-in operator. Convert the arguments, then
3905 // break out so that we will build the appropriate built-in
3906 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003907 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3908 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003909 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003910
3911 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00003912 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003913 }
3914
3915 case OR_No_Viable_Function:
3916 // No viable function; fall through to handling this as a
3917 // built-in operator, which will produce an error message for us.
3918 break;
3919
3920 case OR_Ambiguous:
3921 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3922 << UnaryOperator::getOpcodeStr(Opc)
3923 << Input->getSourceRange();
3924 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00003925 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003926 }
3927
3928 // Either we found no viable overloaded operator or we matched a
3929 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00003930 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003931 }
3932
Chris Lattner4b009652007-07-25 00:24:17 +00003933 QualType resultType;
3934 switch (Opc) {
3935 default:
3936 assert(0 && "Unimplemented unary expr!");
3937 case UnaryOperator::PreInc:
3938 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003939 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3940 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00003941 break;
3942 case UnaryOperator::AddrOf:
3943 resultType = CheckAddressOfOperand(Input, OpLoc);
3944 break;
3945 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00003946 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00003947 resultType = CheckIndirectionOperand(Input, OpLoc);
3948 break;
3949 case UnaryOperator::Plus:
3950 case UnaryOperator::Minus:
3951 UsualUnaryConversions(Input);
3952 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003953 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3954 break;
3955 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3956 resultType->isEnumeralType())
3957 break;
3958 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3959 Opc == UnaryOperator::Plus &&
3960 resultType->isPointerType())
3961 break;
3962
Sebastian Redl8b769972009-01-19 00:08:26 +00003963 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3964 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003965 case UnaryOperator::Not: // bitwise complement
3966 UsualUnaryConversions(Input);
3967 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00003968 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3969 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3970 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00003971 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003972 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00003973 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00003974 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3975 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003976 break;
3977 case UnaryOperator::LNot: // logical negation
3978 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
3979 DefaultFunctionArrayConversion(Input);
3980 resultType = Input->getType();
3981 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00003982 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3983 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003984 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00003985 // In C++, it's bool. C++ 5.3.1p8
3986 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003987 break;
Chris Lattner03931a72007-08-24 21:16:53 +00003988 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00003989 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00003990 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00003991 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003992 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00003993 resultType = Input->getType();
3994 break;
3995 }
3996 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00003997 return ExprError();
3998 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00003999 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004000}
4001
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004002/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4003Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00004004 SourceLocation LabLoc,
4005 IdentifierInfo *LabelII) {
4006 // Look up the record for this label identifier.
4007 LabelStmt *&LabelDecl = LabelMap[LabelII];
4008
Daniel Dunbar879788d2008-08-04 16:51:22 +00004009 // If we haven't seen this label yet, create a forward reference. It
4010 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00004011 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004012 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00004013
4014 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff774e4152009-01-21 00:14:39 +00004015 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4016 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00004017}
4018
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004019Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00004020 SourceLocation RPLoc) { // "({..})"
4021 Stmt *SubStmt = static_cast<Stmt*>(substmt);
4022 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4023 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4024
Eli Friedmanbc941e12009-01-24 23:09:00 +00004025 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4026 if (isFileScope) {
4027 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4028 }
4029
Chris Lattner4b009652007-07-25 00:24:17 +00004030 // FIXME: there are a variety of strange constraints to enforce here, for
4031 // example, it is not possible to goto into a stmt expression apparently.
4032 // More semantic analysis is needed.
4033
4034 // FIXME: the last statement in the compount stmt has its value used. We
4035 // should not warn about it being unused.
4036
4037 // If there are sub stmts in the compound stmt, take the type of the last one
4038 // as the type of the stmtexpr.
4039 QualType Ty = Context.VoidTy;
4040
Chris Lattner200964f2008-07-26 19:51:01 +00004041 if (!Compound->body_empty()) {
4042 Stmt *LastStmt = Compound->body_back();
4043 // If LastStmt is a label, skip down through into the body.
4044 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4045 LastStmt = Label->getSubStmt();
4046
4047 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004048 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004049 }
Chris Lattner4b009652007-07-25 00:24:17 +00004050
Steve Naroff774e4152009-01-21 00:14:39 +00004051 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00004052}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004053
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004054Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4055 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004056 SourceLocation TypeLoc,
4057 TypeTy *argty,
4058 OffsetOfComponent *CompPtr,
4059 unsigned NumComponents,
4060 SourceLocation RPLoc) {
4061 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4062 assert(!ArgTy.isNull() && "Missing type argument!");
4063
4064 // We must have at least one component that refers to the type, and the first
4065 // one is known to be a field designator. Verify that the ArgTy represents
4066 // a struct/union/class.
4067 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00004068 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004069
4070 // Otherwise, create a compound literal expression as the base, and
4071 // iteratively process the offsetof designators.
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004072 InitListExpr *IList =
Douglas Gregorf603b472009-01-28 21:54:33 +00004073 new (Context) InitListExpr(SourceLocation(), 0, 0, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004074 IList->setType(ArgTy);
4075 Expr *Res =
4076 new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, IList, false);
4077
Chris Lattnerb37522e2007-08-31 21:49:13 +00004078 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4079 // GCC extension, diagnose them.
4080 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004081 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4082 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00004083
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004084 for (unsigned i = 0; i != NumComponents; ++i) {
4085 const OffsetOfComponent &OC = CompPtr[i];
4086 if (OC.isBrackets) {
4087 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00004088 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004089 if (!AT) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004090 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004091 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004092 }
4093
Chris Lattner2af6a802007-08-30 17:59:59 +00004094 // FIXME: C++: Verify that operator[] isn't overloaded.
4095
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004096 // C99 6.5.2.1p1
4097 Expr *Idx = static_cast<Expr*>(OC.U.E);
4098 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00004099 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4100 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004101
Steve Naroff774e4152009-01-21 00:14:39 +00004102 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4103 OC.LocEnd);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004104 continue;
4105 }
4106
4107 const RecordType *RC = Res->getType()->getAsRecordType();
4108 if (!RC) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004109 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004110 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004111 }
4112
4113 // Get the decl corresponding to this.
4114 RecordDecl *RD = RC->getDecl();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004115 FieldDecl *MemberDecl
Douglas Gregor52ae30c2009-01-30 01:04:22 +00004116 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4117 LookupMemberName)
4118 .getAsDecl());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004119 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00004120 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4121 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00004122
4123 // FIXME: C++: Verify that MemberDecl isn't a static field.
4124 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00004125 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4126 // matter here.
Steve Naroff774e4152009-01-21 00:14:39 +00004127 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4128 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004129 }
4130
Steve Naroff774e4152009-01-21 00:14:39 +00004131 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4132 Context.getSizeType(), BuiltinLoc);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004133}
4134
4135
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004136Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00004137 TypeTy *arg1, TypeTy *arg2,
4138 SourceLocation RPLoc) {
4139 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4140 QualType argT2 = QualType::getFromOpaquePtr(arg2);
4141
4142 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4143
Steve Naroff774e4152009-01-21 00:14:39 +00004144 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
4145 argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00004146}
4147
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004148Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00004149 ExprTy *expr1, ExprTy *expr2,
4150 SourceLocation RPLoc) {
4151 Expr *CondExpr = static_cast<Expr*>(cond);
4152 Expr *LHSExpr = static_cast<Expr*>(expr1);
4153 Expr *RHSExpr = static_cast<Expr*>(expr2);
4154
4155 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4156
4157 // The conditional expression is required to be a constant expression.
4158 llvm::APSInt condEval(32);
4159 SourceLocation ExpLoc;
4160 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004161 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4162 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00004163
4164 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4165 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
4166 RHSExpr->getType();
Steve Naroff774e4152009-01-21 00:14:39 +00004167 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4168 resType, RPLoc);
Steve Naroff93c53012007-08-03 21:21:27 +00004169}
4170
Steve Naroff52a81c02008-09-03 18:15:37 +00004171//===----------------------------------------------------------------------===//
4172// Clang Extensions.
4173//===----------------------------------------------------------------------===//
4174
4175/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004176void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004177 // Analyze block parameters.
4178 BlockSemaInfo *BSI = new BlockSemaInfo();
4179
4180 // Add BSI to CurBlock.
4181 BSI->PrevBlockInfo = CurBlock;
4182 CurBlock = BSI;
4183
4184 BSI->ReturnType = 0;
4185 BSI->TheScope = BlockScope;
4186
Steve Naroff52059382008-10-10 01:28:17 +00004187 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004188 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004189}
4190
Mike Stumpc1fddff2009-02-04 22:31:32 +00004191void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4192 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4193
4194 if (ParamInfo.getNumTypeObjects() == 0
4195 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4196 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4197
4198 // The type is entirely optional as well, if none, use DependentTy.
4199 if (T.isNull())
4200 T = Context.DependentTy;
4201
4202 // The parameter list is optional, if there was none, assume ().
4203 if (!T->isFunctionType())
4204 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4205
4206 CurBlock->hasPrototype = true;
4207 CurBlock->isVariadic = false;
4208 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4209 .getTypePtr();
4210
4211 if (!RetTy->isDependentType())
4212 CurBlock->ReturnType = RetTy;
4213 return;
4214 }
4215
Steve Naroff52a81c02008-09-03 18:15:37 +00004216 // Analyze arguments to block.
4217 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4218 "Not a function declarator!");
4219 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004220
Steve Naroff52059382008-10-10 01:28:17 +00004221 CurBlock->hasPrototype = FTI.hasPrototype;
4222 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00004223
4224 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4225 // no arguments, not a function that takes a single void argument.
4226 if (FTI.hasPrototype &&
4227 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4228 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4229 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4230 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004231 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004232 } else if (FTI.hasPrototype) {
4233 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004234 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4235 CurBlock->isVariadic = FTI.isVariadic;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004236 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4237
4238 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4239 .getTypePtr();
4240
4241 if (!RetTy->isDependentType())
4242 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00004243 }
Steve Naroff52059382008-10-10 01:28:17 +00004244 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4245
4246 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4247 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4248 // If this has an identifier, add it to the scope stack.
4249 if ((*AI)->getIdentifier())
4250 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004251}
4252
4253/// ActOnBlockError - If there is an error parsing a block, this callback
4254/// is invoked to pop the information about the block from the action impl.
4255void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4256 // Ensure that CurBlock is deleted.
4257 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4258
4259 // Pop off CurBlock, handle nested blocks.
4260 CurBlock = CurBlock->PrevBlockInfo;
4261
4262 // FIXME: Delete the ParmVarDecl objects as well???
4263
4264}
4265
4266/// ActOnBlockStmtExpr - This is called when the body of a block statement
4267/// literal was successfully completed. ^(int x){...}
4268Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4269 Scope *CurScope) {
4270 // Ensure that CurBlock is deleted.
4271 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Ted Kremenek0c97e042009-02-07 01:47:29 +00004272 ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body));
Steve Naroff52a81c02008-09-03 18:15:37 +00004273
Steve Naroff52059382008-10-10 01:28:17 +00004274 PopDeclContext();
4275
Steve Naroff52a81c02008-09-03 18:15:37 +00004276 // Pop off CurBlock, handle nested blocks.
4277 CurBlock = CurBlock->PrevBlockInfo;
4278
4279 QualType RetTy = Context.VoidTy;
4280 if (BSI->ReturnType)
4281 RetTy = QualType(BSI->ReturnType, 0);
4282
4283 llvm::SmallVector<QualType, 8> ArgTypes;
4284 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4285 ArgTypes.push_back(BSI->Params[i]->getType());
4286
4287 QualType BlockTy;
4288 if (!BSI->hasPrototype)
4289 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4290 else
4291 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004292 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00004293
4294 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00004295
Steve Naroff95029d92008-10-08 18:44:00 +00004296 BSI->TheDecl->setBody(Body.take());
Steve Naroff774e4152009-01-21 00:14:39 +00004297 return new (Context) BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004298}
4299
Nate Begemanbd881ef2008-01-30 20:50:20 +00004300/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004301/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00004302/// The number of arguments has already been validated to match the number of
4303/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004304static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4305 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004306 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00004307 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004308 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4309 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00004310
4311 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004312 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00004313 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004314 return true;
4315}
4316
4317Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4318 SourceLocation *CommaLocs,
4319 SourceLocation BuiltinLoc,
4320 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004321 // __builtin_overload requires at least 2 arguments
4322 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004323 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4324 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004325
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004326 // The first argument is required to be a constant expression. It tells us
4327 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00004328 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004329 Expr *NParamsExpr = Args[0];
4330 llvm::APSInt constEval(32);
4331 SourceLocation ExpLoc;
4332 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004333 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4334 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004335
4336 // Verify that the number of parameters is > 0
4337 unsigned NumParams = constEval.getZExtValue();
4338 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004339 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4340 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004341 // Verify that we have at least 1 + NumParams arguments to the builtin.
4342 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004343 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4344 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004345
4346 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00004347 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00004348 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004349 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4350 // UsualUnaryConversions will convert the function DeclRefExpr into a
4351 // pointer to function.
4352 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004353 const FunctionTypeProto *FnType = 0;
4354 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4355 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004356
4357 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4358 // parameters, and the number of parameters must match the value passed to
4359 // the builtin.
4360 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004361 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4362 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004363
4364 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00004365 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004366 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004367 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004368 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004369 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4370 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00004371 // Remember our match, and continue processing the remaining arguments
4372 // to catch any errors.
Ted Kremenekf1a67122009-02-09 17:08:14 +00004373 OE = new (Context) OverloadExpr(Context, Args, NumArgs, i,
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004374 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00004375 BuiltinLoc, RParenLoc);
4376 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004377 }
Nate Begemanc6078c92008-01-31 05:38:29 +00004378 // Return the newly created OverloadExpr node, if we succeded in matching
4379 // exactly one of the candidate functions.
4380 if (OE)
4381 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004382
4383 // If we didn't find a matching function Expr in the __builtin_overload list
4384 // the return an error.
4385 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00004386 for (unsigned i = 0; i != NumParams; ++i) {
4387 if (i != 0) typeNames += ", ";
4388 typeNames += Args[i+1]->getType().getAsString();
4389 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004390
Chris Lattner77d52da2008-11-20 06:06:08 +00004391 return Diag(BuiltinLoc, diag::err_overload_no_match)
4392 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004393}
4394
Anders Carlsson36760332007-10-15 20:28:48 +00004395Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4396 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004397 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004398 Expr *E = static_cast<Expr*>(expr);
4399 QualType T = QualType::getFromOpaquePtr(type);
4400
4401 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004402
4403 // Get the va_list type
4404 QualType VaListType = Context.getBuiltinVaListType();
4405 // Deal with implicit array decay; for example, on x86-64,
4406 // va_list is an array, but it's supposed to decay to
4407 // a pointer for va_arg.
4408 if (VaListType->isArrayType())
4409 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004410 // Make sure the input expression also decays appropriately.
4411 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004412
4413 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004414 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004415 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004416 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00004417
4418 // FIXME: Warn if a non-POD type is passed in.
4419
Steve Naroff774e4152009-01-21 00:14:39 +00004420 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004421}
4422
Douglas Gregorad4b3792008-11-29 04:51:27 +00004423Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4424 // The type of __null will be int or long, depending on the size of
4425 // pointers on the target.
4426 QualType Ty;
4427 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4428 Ty = Context.IntTy;
4429 else
4430 Ty = Context.LongTy;
4431
Steve Naroff774e4152009-01-21 00:14:39 +00004432 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregorad4b3792008-11-29 04:51:27 +00004433}
4434
Chris Lattner005ed752008-01-04 18:04:52 +00004435bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4436 SourceLocation Loc,
4437 QualType DstType, QualType SrcType,
4438 Expr *SrcExpr, const char *Flavor) {
4439 // Decode the result (notice that AST's are still created for extensions).
4440 bool isInvalid = false;
4441 unsigned DiagKind;
4442 switch (ConvTy) {
4443 default: assert(0 && "Unknown conversion type");
4444 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004445 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004446 DiagKind = diag::ext_typecheck_convert_pointer_int;
4447 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004448 case IntToPointer:
4449 DiagKind = diag::ext_typecheck_convert_int_pointer;
4450 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004451 case IncompatiblePointer:
4452 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4453 break;
4454 case FunctionVoidPointer:
4455 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4456 break;
4457 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004458 // If the qualifiers lost were because we were applying the
4459 // (deprecated) C++ conversion from a string literal to a char*
4460 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4461 // Ideally, this check would be performed in
4462 // CheckPointerTypesForAssignment. However, that would require a
4463 // bit of refactoring (so that the second argument is an
4464 // expression, rather than a type), which should be done as part
4465 // of a larger effort to fix CheckPointerTypesForAssignment for
4466 // C++ semantics.
4467 if (getLangOptions().CPlusPlus &&
4468 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4469 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004470 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4471 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004472 case IntToBlockPointer:
4473 DiagKind = diag::err_int_to_block_pointer;
4474 break;
4475 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004476 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004477 break;
Steve Naroff19608432008-10-14 22:18:38 +00004478 case IncompatibleObjCQualifiedId:
4479 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4480 // it can give a more specific diagnostic.
4481 DiagKind = diag::warn_incompatible_qualified_id;
4482 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004483 case IncompatibleVectors:
4484 DiagKind = diag::warn_incompatible_vectors;
4485 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004486 case Incompatible:
4487 DiagKind = diag::err_typecheck_convert_incompatible;
4488 isInvalid = true;
4489 break;
4490 }
4491
Chris Lattner271d4c22008-11-24 05:29:24 +00004492 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4493 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004494 return isInvalid;
4495}
Anders Carlssond5201b92008-11-30 19:50:32 +00004496
4497bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4498{
4499 Expr::EvalResult EvalResult;
4500
4501 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4502 EvalResult.HasSideEffects) {
4503 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4504
4505 if (EvalResult.Diag) {
4506 // We only show the note if it's not the usual "invalid subexpression"
4507 // or if it's actually in a subexpression.
4508 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4509 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4510 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4511 }
4512
4513 return true;
4514 }
4515
4516 if (EvalResult.Diag) {
4517 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4518 E->getSourceRange();
4519
4520 // Print the reason it's not a constant.
4521 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4522 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4523 }
4524
4525 if (Result)
4526 *Result = EvalResult.Val.getInt();
4527 return false;
4528}