blob: 8c3a0a9fa15806ef1cf7f34390b10c10628d8011 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Dunbarc4a1dea2008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner04421082008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner418f6c72008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28
Chris Lattnere7a2e912008-07-25 21:10:04 +000029//===----------------------------------------------------------------------===//
30// Standard Promotions and Conversions
31//===----------------------------------------------------------------------===//
32
Chris Lattnere7a2e912008-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 Lattnere7a2e912008-07-25 21:10:04 +000038 if (Ty->isFunctionType())
39 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner67d33d82008-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).
Argyrios Kyrtzidisc39a3d72008-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 Lattner67d33d82008-07-25 21:33:13 +000054 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
55 }
Chris Lattnere7a2e912008-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 Lattnere7a2e912008-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 Lattner05faf172008-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 Carlssondce5e2c2009-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 Lattnere7a2e912008-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 Gregoreb8f3062008-11-12 17:17:38 +0000117
Chris Lattnere7a2e912008-07-25 21:10:04 +0000118 // For conversion purposes, we ignore any qualifiers.
119 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000120 QualType lhs =
121 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
122 QualType rhs =
123 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-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 Gregorbf3af052008-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 Gregoreb8f3062008-11-12 17:17:38 +0000152
Chris Lattnere7a2e912008-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 Lattnere7a2e912008-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 Lattnere7a2e912008-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 Lattnere7a2e912008-07-25 21:10:04 +0000189 } else if (result < 0) { // The right side is bigger, convert lhs.
190 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattnere7a2e912008-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 Lattnere7a2e912008-07-25 21:10:04 +0000197 return rhs;
198 } else { // handle "_Complex double, double".
Chris Lattnere7a2e912008-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 Carlsson5b1f3f02008-12-10 23:30:05 +0000207 if (rhs->isIntegerType()) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000208 // convert rhs to the lhs floating point type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000209 return lhs;
210 }
Anders Carlsson5b1f3f02008-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 Lattnere7a2e912008-07-25 21:10:04 +0000216 // convert lhs to the rhs floating point type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000217 return rhs;
218 }
Anders Carlsson5b1f3f02008-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 Lattnere7a2e912008-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 Lattnere7a2e912008-07-25 21:10:04 +0000228 return lhs;
229 }
230 if (result < 0) { // convert the lhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000231 return rhs;
232 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000233 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
Chris Lattnere7a2e912008-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 Lattnere7a2e912008-07-25 21:10:04 +0000244 return lhs;
245 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000246 return rhs;
247 } else if (lhsComplexInt && rhs->isIntegerType()) {
248 // convert the rhs to the lhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000249 return lhs;
250 } else if (rhsComplexInt && lhs->isIntegerType()) {
251 // convert the lhs to the rhs complex type.
Chris Lattnere7a2e912008-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 Lattnere7a2e912008-07-25 21:10:04 +0000280 return destType;
281}
282
283//===----------------------------------------------------------------------===//
284// Semantic Analysis for various Expression Types
285//===----------------------------------------------------------------------===//
286
287
Steve Narofff69936d2007-09-16 03:34:24 +0000288/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +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 Redlcd965b92009-01-18 18:53:16 +0000293///
294Action::OwningExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000295Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000296 assert(NumStringToks && "Must have at least one string!");
297
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000298 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000299 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000300 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000301
302 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
303 for (unsigned i = 0; i != NumStringToks; ++i)
304 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000305
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000306 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000307 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000308 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-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 Redlcd965b92009-01-18 18:53:16 +0000313
Chris Lattnera7ad98f2008-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 Redlcd965b92009-01-18 18:53:16 +0000320
Reid Spencer5f016e22007-07-11 17:01:13 +0000321 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Ted Kremenek6e94ef52009-02-06 19:55:15 +0000322 return Owned(new (Context) StringLiteral(Context, Literal.GetString(),
Steve Naroff6ece14c2009-01-21 00:14:39 +0000323 Literal.GetStringLength(),
Sebastian Redlcd965b92009-01-18 18:53:16 +0000324 Literal.AnyWide, StrTy,
325 StringToks[0].getLocation(),
326 StringToks[NumStringToks-1].getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000327}
328
Chris Lattner639e2d32008-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 Naroff08d92e42007-09-15 18:49:24 +0000359/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +0000360/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroff0d755ad2008-03-19 23:46:26 +0000361/// identifier is used in a function call context.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000362/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000363/// class or namespace that the identifier must be a member of.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000364Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
365 IdentifierInfo &II,
366 bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000367 const CXXScopeSpec *SS,
368 bool isAddressOfOperand) {
369 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor17330012009-02-04 15:01:18 +0000370 isAddressOfOperand);
Douglas Gregor10c42622008-11-18 15:03:34 +0000371}
372
Douglas Gregor1a49af92009-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 Redlebc07d52009-02-03 20:19:35 +0000376DeclRefExpr *
377Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
378 bool TypeDependent, bool ValueDependent,
379 const CXXScopeSpec *SS) {
Steve Naroff6ece14c2009-01-21 00:14:39 +0000380 if (SS && !SS->isEmpty())
381 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Steve Naroff0a473932009-01-20 19:53:53 +0000382 ValueDependent, SS->getRange().getBegin());
Steve Naroff6ece14c2009-01-21 00:14:39 +0000383 else
384 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor1a49af92009-01-06 05:10:23 +0000385}
386
Douglas Gregorbcbffc42009-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 Gregor4afa39d2009-01-20 01:17:11 +0000390static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000391 assert(Record->isAnonymousStructOrUnion() &&
392 "Record must be an anonymous struct or union!");
393
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000394 // FIXME: Once Decls are directly linked together, this will
Douglas Gregorbcbffc42009-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 Gregor4afa39d2009-01-20 01:17:11 +0000407 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregorbcbffc42009-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 Redlcd965b92009-01-18 18:53:16 +0000416Sema::OwningExprResult
Douglas Gregorbcbffc42009-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 Gregor4afa39d2009-01-20 01:17:11 +0000436 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregorbcbffc42009-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 Kremenek8189cde2009-02-07 01:47:29 +0000456 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000457 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Douglas Gregorbcbffc42009-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 Naroff6ece14c2009-01-21 00:14:39 +0000485 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000486 MD->getThisType(Context));
487 BaseObjectIsPointer = true;
488 }
489 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000490 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
491 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000492 }
493 ExtraQuals = MD->getTypeQualifiers();
494 }
495
496 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000497 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
498 << Field->getDeclName());
Douglas Gregorbcbffc42009-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 Naroff6ece14c2009-01-21 00:14:39 +0000513 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
514 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000515 BaseObjectIsPointer = false;
516 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
517 OpLoc = SourceLocation();
518 }
519
Sebastian Redlcd965b92009-01-18 18:53:16 +0000520 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000521}
522
Douglas Gregor10c42622008-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 Gregor5c37de72008-12-06 00:22:45 +0000537///
Sebastian Redlebc07d52009-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 Redlcd965b92009-01-18 18:53:16 +0000542Sema::OwningExprResult
543Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
544 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor17330012009-02-04 15:01:18 +0000545 const CXXScopeSpec *SS,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000546 bool isAddressOfOperand) {
Chris Lattner8a934232008-03-31 00:36:02 +0000547 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000548 if (SS && SS->isInvalid())
549 return ExprError();
550 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000551
Douglas Gregor17330012009-02-04 15:01:18 +0000552 if (getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
553 HasTrailingLParen && Lookup.getKind() == LookupResult::NotFound) {
554 // We've seen something of the form
555 //
556 // identifier(
557 //
558 // and we did not find any entity by the name
559 // "identifier". However, this identifier is still subject to
560 // argument-dependent lookup, so keep track of the name.
561 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
562 Context.OverloadTy,
563 Loc));
564 }
565
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000566 NamedDecl *D = 0;
Sebastian Redlcd965b92009-01-18 18:53:16 +0000567 if (Lookup.isAmbiguous()) {
568 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
569 SS && SS->isSet() ? SS->getRange()
570 : SourceRange());
571 return ExprError();
572 } else
Douglas Gregor7176fff2009-01-15 00:26:24 +0000573 D = Lookup.getAsDecl();
Douglas Gregor5c37de72008-12-06 00:22:45 +0000574
Chris Lattner8a934232008-03-31 00:36:02 +0000575 // If this reference is in an Objective-C method, then ivar lookup happens as
576 // well.
Douglas Gregor10c42622008-11-18 15:03:34 +0000577 IdentifierInfo *II = Name.getAsIdentifierInfo();
578 if (II && getCurMethodDecl()) {
Chris Lattner8a934232008-03-31 00:36:02 +0000579 // There are two cases to handle here. 1) scoped lookup could have failed,
580 // in which case we should look for an ivar. 2) scoped lookup could have
581 // found a decl, but that decl is outside the current method (i.e. a global
582 // variable). In these two cases, we do a lookup for an ivar with this
583 // name, if the lookup suceeds, we replace it our current decl.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000584 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000585 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregor10c42622008-11-18 15:03:34 +0000586 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattner8a934232008-03-31 00:36:02 +0000587 // FIXME: This should use a new expr for a direct reference, don't turn
588 // this into Self->ivar, just return a BareIVarExpr or something.
589 IdentifierInfo &II = Context.Idents.get("self");
Sebastian Redlcd965b92009-01-18 18:53:16 +0000590 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000591 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
592 Loc, static_cast<Expr*>(SelfExpr.release()),
Sebastian Redlcd965b92009-01-18 18:53:16 +0000593 true, true);
Fariborz Jahanianefc4c4b2008-12-18 17:29:46 +0000594 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000595 return Owned(MRef);
Chris Lattner8a934232008-03-31 00:36:02 +0000596 }
597 }
Steve Naroff76de9d72008-08-10 19:10:41 +0000598 // Needed to implement property "super.method" notation.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000599 if (D == 0 && II->isStr("super")) {
Steve Naroffe3e9add2008-06-02 23:03:37 +0000600 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000601 getCurMethodDecl()->getClassInterface()));
Steve Naroff6ece14c2009-01-21 00:14:39 +0000602 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroffe3e9add2008-06-02 23:03:37 +0000603 }
Chris Lattner8a934232008-03-31 00:36:02 +0000604 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000605 if (D == 0) {
606 // Otherwise, this could be an implicitly declared function reference (legal
607 // in C90, extension in C99).
Douglas Gregor10c42622008-11-18 15:03:34 +0000608 if (HasTrailingLParen && II &&
Chris Lattner8a934232008-03-31 00:36:02 +0000609 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregor10c42622008-11-18 15:03:34 +0000610 D = ImplicitlyDefineFunction(Loc, *II, S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000611 else {
612 // If this name wasn't predeclared and if this is not a function call,
613 // diagnose the problem.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000614 if (SS && !SS->isEmpty())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000615 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
616 << Name << SS->getRange());
Douglas Gregor10c42622008-11-18 15:03:34 +0000617 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
618 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000619 return ExprError(Diag(Loc, diag::err_undeclared_use)
620 << Name.getAsString());
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000621 else
Sebastian Redlcd965b92009-01-18 18:53:16 +0000622 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000623 }
624 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000625
Sebastian Redlebc07d52009-02-03 20:19:35 +0000626 // If this is an expression of the form &Class::member, don't build an
627 // implicit member ref, because we want a pointer to the member in general,
628 // not any specific instance's member.
629 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Sebastian Redlebc07d52009-02-03 20:19:35 +0000630 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000631 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redlebc07d52009-02-03 20:19:35 +0000632 QualType DType;
633 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
634 DType = FD->getType().getNonReferenceType();
635 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
636 DType = Method->getType();
637 } else if (isa<OverloadedFunctionDecl>(D)) {
638 DType = Context.OverloadTy;
639 }
640 // Could be an inner type. That's diagnosed below, so ignore it here.
641 if (!DType.isNull()) {
642 // The pointer is type- and value-dependent if it points into something
643 // dependent.
644 bool Dependent = false;
645 for (; DC; DC = DC->getParent()) {
646 // FIXME: could stop early at namespace scope.
647 if (DC->isRecord()) {
648 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
649 if (Context.getTypeDeclType(Record)->isDependentType()) {
650 Dependent = true;
651 break;
652 }
653 }
654 }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000655 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redlebc07d52009-02-03 20:19:35 +0000656 }
657 }
658 }
659
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000660 // We may have found a field within an anonymous union or struct
661 // (C++ [class.union]).
662 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
663 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
664 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000665
Douglas Gregor88a35142008-12-22 05:46:06 +0000666 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
667 if (!MD->isStatic()) {
668 // C++ [class.mfct.nonstatic]p2:
669 // [...] if name lookup (3.4.1) resolves the name in the
670 // id-expression to a nonstatic nontype member of class X or of
671 // a base class of X, the id-expression is transformed into a
672 // class member access expression (5.2.5) using (*this) (9.3.2)
673 // as the postfix-expression to the left of the '.' operator.
674 DeclContext *Ctx = 0;
675 QualType MemberType;
676 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
677 Ctx = FD->getDeclContext();
678 MemberType = FD->getType();
679
680 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
681 MemberType = RefType->getPointeeType();
682 else if (!FD->isMutable()) {
683 unsigned combinedQualifiers
684 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
685 MemberType = MemberType.getQualifiedType(combinedQualifiers);
686 }
687 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
688 if (!Method->isStatic()) {
689 Ctx = Method->getParent();
690 MemberType = Method->getType();
691 }
692 } else if (OverloadedFunctionDecl *Ovl
693 = dyn_cast<OverloadedFunctionDecl>(D)) {
694 for (OverloadedFunctionDecl::function_iterator
695 Func = Ovl->function_begin(),
696 FuncEnd = Ovl->function_end();
697 Func != FuncEnd; ++Func) {
698 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
699 if (!DMethod->isStatic()) {
700 Ctx = Ovl->getDeclContext();
701 MemberType = Context.OverloadTy;
702 break;
703 }
704 }
705 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000706
707 if (Ctx && Ctx->isRecord()) {
Douglas Gregor88a35142008-12-22 05:46:06 +0000708 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
709 QualType ThisType = Context.getTagDeclType(MD->getParent());
710 if ((Context.getCanonicalType(CtxType)
711 == Context.getCanonicalType(ThisType)) ||
712 IsDerivedFrom(ThisType, CtxType)) {
713 // Build the implicit member access expression.
Steve Naroff6ece14c2009-01-21 00:14:39 +0000714 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor88a35142008-12-22 05:46:06 +0000715 MD->getThisType(Context));
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000716 return Owned(new (Context) MemberExpr(This, true, D,
Sebastian Redlcd965b92009-01-18 18:53:16 +0000717 SourceLocation(), MemberType));
Douglas Gregor88a35142008-12-22 05:46:06 +0000718 }
719 }
720 }
721 }
722
Douglas Gregor44b43212008-12-11 16:49:14 +0000723 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000724 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
725 if (MD->isStatic())
726 // "invalid use of member 'x' in static member function"
Sebastian Redlcd965b92009-01-18 18:53:16 +0000727 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
728 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000729 }
730
Douglas Gregor88a35142008-12-22 05:46:06 +0000731 // Any other ways we could have found the field in a well-formed
732 // program would have been turned into implicit member expressions
733 // above.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000734 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
735 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000736 }
Douglas Gregor88a35142008-12-22 05:46:06 +0000737
Reid Spencer5f016e22007-07-11 17:01:13 +0000738 if (isa<TypedefDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000739 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000740 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000741 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000742 if (isa<NamespaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000743 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000744
Steve Naroffdd972f22008-09-05 22:11:13 +0000745 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000746 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000747 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
748 false, false, SS));
Douglas Gregorc15cb382009-02-09 23:23:08 +0000749 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
750 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
751 false, false, SS));
Steve Naroffdd972f22008-09-05 22:11:13 +0000752 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000753
Steve Naroffdd972f22008-09-05 22:11:13 +0000754 // check if referencing an identifier with __attribute__((deprecated)).
755 if (VD->getAttr<DeprecatedAttr>())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000756 ExprError(Diag(Loc, diag::warn_deprecated) << VD->getDeclName());
757
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000758 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
759 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
760 Scope *CheckS = S;
761 while (CheckS) {
762 if (CheckS->isWithinElse() &&
763 CheckS->getControlParent()->isDeclScope(Var)) {
764 if (Var->getType()->isBooleanType())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000765 ExprError(Diag(Loc, diag::warn_value_always_false)
766 << Var->getDeclName());
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000767 else
Sebastian Redlcd965b92009-01-18 18:53:16 +0000768 ExprError(Diag(Loc, diag::warn_value_always_zero)
769 << Var->getDeclName());
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000770 break;
771 }
772
773 // Move up one more control parent to check again.
774 CheckS = CheckS->getControlParent();
775 if (CheckS)
776 CheckS = CheckS->getParent();
777 }
778 }
779 }
Steve Naroffdd972f22008-09-05 22:11:13 +0000780
781 // Only create DeclRefExpr's for valid Decl's.
782 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000783 return ExprError();
784
Chris Lattner639e2d32008-10-20 05:16:36 +0000785 // If the identifier reference is inside a block, and it refers to a value
786 // that is outside the block, create a BlockDeclRefExpr instead of a
787 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
788 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +0000789 //
Chris Lattner639e2d32008-10-20 05:16:36 +0000790 // We do not do this for things like enum constants, global variables, etc,
791 // as they do not get snapshotted.
792 //
793 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff090276f2008-10-10 01:28:17 +0000794 // The BlocksAttr indicates the variable is bound by-reference.
795 if (VD->getAttr<BlocksAttr>())
Steve Naroff6ece14c2009-01-21 00:14:39 +0000796 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroff0a473932009-01-20 19:53:53 +0000797 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd965b92009-01-18 18:53:16 +0000798
Steve Naroff090276f2008-10-10 01:28:17 +0000799 // Variable will be bound by-copy, make it const within the closure.
800 VD->getType().addConst();
Steve Naroff6ece14c2009-01-21 00:14:39 +0000801 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroff0a473932009-01-20 19:53:53 +0000802 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff090276f2008-10-10 01:28:17 +0000803 }
804 // If this reference is not in a block or if the referenced variable is
805 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +0000806
Douglas Gregor898574e2008-12-05 23:32:09 +0000807 bool TypeDependent = false;
Douglas Gregor83f96f62008-12-10 20:57:37 +0000808 bool ValueDependent = false;
809 if (getLangOptions().CPlusPlus) {
810 // C++ [temp.dep.expr]p3:
811 // An id-expression is type-dependent if it contains:
812 // - an identifier that was declared with a dependent type,
813 if (VD->getType()->isDependentType())
814 TypeDependent = true;
815 // - FIXME: a template-id that is dependent,
816 // - a conversion-function-id that specifies a dependent type,
817 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
818 Name.getCXXNameType()->isDependentType())
819 TypeDependent = true;
820 // - a nested-name-specifier that contains a class-name that
821 // names a dependent type.
822 else if (SS && !SS->isEmpty()) {
823 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
824 DC; DC = DC->getParent()) {
825 // FIXME: could stop early at namespace scope.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000826 if (DC->isRecord()) {
Douglas Gregor83f96f62008-12-10 20:57:37 +0000827 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
828 if (Context.getTypeDeclType(Record)->isDependentType()) {
829 TypeDependent = true;
830 break;
831 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000832 }
833 }
834 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000835
Douglas Gregor83f96f62008-12-10 20:57:37 +0000836 // C++ [temp.dep.constexpr]p2:
837 //
838 // An identifier is value-dependent if it is:
839 // - a name declared with a dependent type,
840 if (TypeDependent)
841 ValueDependent = true;
842 // - the name of a non-type template parameter,
843 else if (isa<NonTypeTemplateParmDecl>(VD))
844 ValueDependent = true;
845 // - a constant with integral or enumeration type and is
846 // initialized with an expression that is value-dependent
847 // (FIXME!).
848 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000849
Sebastian Redlcd965b92009-01-18 18:53:16 +0000850 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
851 TypeDependent, ValueDependent, SS));
Reid Spencer5f016e22007-07-11 17:01:13 +0000852}
853
Sebastian Redlcd965b92009-01-18 18:53:16 +0000854Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
855 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +0000856 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +0000857
Reid Spencer5f016e22007-07-11 17:01:13 +0000858 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +0000859 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +0000860 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
861 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
862 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000863 }
Chris Lattner1423ea42008-01-12 18:39:25 +0000864
Chris Lattnerfa28b302008-01-12 08:14:25 +0000865 // Pre-defined identifiers are of type char[x], where x is the length of the
866 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +0000867 unsigned Length;
Chris Lattner371f2582008-12-04 23:50:19 +0000868 if (FunctionDecl *FD = getCurFunctionDecl())
869 Length = FD->getIdentifier()->getLength();
Chris Lattnerb0da9232008-12-12 05:05:20 +0000870 else if (ObjCMethodDecl *MD = getCurMethodDecl())
871 Length = MD->getSynthesizedMethodSize();
872 else {
873 Diag(Loc, diag::ext_predef_outside_function);
874 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
875 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
876 }
Sebastian Redlcd965b92009-01-18 18:53:16 +0000877
878
Chris Lattner8f978d52008-01-12 19:32:28 +0000879 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +0000880 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +0000881 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000882 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +0000883}
884
Sebastian Redlcd965b92009-01-18 18:53:16 +0000885Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000886 llvm::SmallString<16> CharBuffer;
887 CharBuffer.resize(Tok.getLength());
888 const char *ThisTokBegin = &CharBuffer[0];
889 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000890
Reid Spencer5f016e22007-07-11 17:01:13 +0000891 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
892 Tok.getLocation(), PP);
893 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000894 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +0000895
896 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
897
Sebastian Redle91b3bc2009-01-20 22:23:13 +0000898 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
899 Literal.isWide(),
900 type, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000901}
902
Sebastian Redlcd965b92009-01-18 18:53:16 +0000903Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
904 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +0000905 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
906 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +0000907 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +0000908 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +0000909 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +0000910 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000911 }
Ted Kremenek28396602009-01-13 23:19:12 +0000912
Reid Spencer5f016e22007-07-11 17:01:13 +0000913 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +0000914 // Add padding so that NumericLiteralParser can overread by one character.
915 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000916 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +0000917
Reid Spencer5f016e22007-07-11 17:01:13 +0000918 // Get the spelling of the token, which eliminates trigraphs, etc.
919 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000920
Reid Spencer5f016e22007-07-11 17:01:13 +0000921 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
922 Tok.getLocation(), PP);
923 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000924 return ExprError();
925
Chris Lattner5d661452007-08-26 03:42:43 +0000926 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +0000927
Chris Lattner5d661452007-08-26 03:42:43 +0000928 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000929 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000930 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +0000931 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000932 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +0000933 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000934 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000935 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000936
937 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
938
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000939 // isExact will be set by GetFloatValue().
940 bool isExact = false;
Sebastian Redle91b3bc2009-01-20 22:23:13 +0000941 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
942 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +0000943
Chris Lattner5d661452007-08-26 03:42:43 +0000944 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000945 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +0000946 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000947 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +0000948
Neil Boothb9449512007-08-29 22:00:19 +0000949 // long long is a C99 feature.
950 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000951 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000952 Diag(Tok.getLocation(), diag::ext_longlong);
953
Reid Spencer5f016e22007-07-11 17:01:13 +0000954 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +0000955 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000956
Reid Spencer5f016e22007-07-11 17:01:13 +0000957 if (Literal.GetIntegerValue(ResultVal)) {
958 // If this value didn't fit into uintmax_t, warn and force to ull.
959 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000960 Ty = Context.UnsignedLongLongTy;
961 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +0000962 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000963 } else {
964 // If this value fits into a ULL, try to figure out what else it fits into
965 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000966
Reid Spencer5f016e22007-07-11 17:01:13 +0000967 // Octal, Hexadecimal, and integers with a U suffix are allowed to
968 // be an unsigned int.
969 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
970
971 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000972 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +0000973 if (!Literal.isLong && !Literal.isLongLong) {
974 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000975 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000976
Reid Spencer5f016e22007-07-11 17:01:13 +0000977 // Does it fit in a unsigned int?
978 if (ResultVal.isIntN(IntSize)) {
979 // Does it fit in a signed int?
980 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000981 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000982 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000983 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000984 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000985 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000986 }
Sebastian Redlcd965b92009-01-18 18:53:16 +0000987
Reid Spencer5f016e22007-07-11 17:01:13 +0000988 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +0000989 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000990 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000991
Reid Spencer5f016e22007-07-11 17:01:13 +0000992 // Does it fit in a unsigned long?
993 if (ResultVal.isIntN(LongSize)) {
994 // Does it fit in a signed long?
995 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000996 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000997 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000998 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000999 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001000 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001001 }
1002
Reid Spencer5f016e22007-07-11 17:01:13 +00001003 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001004 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001005 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001006
Reid Spencer5f016e22007-07-11 17:01:13 +00001007 // Does it fit in a unsigned long long?
1008 if (ResultVal.isIntN(LongLongSize)) {
1009 // Does it fit in a signed long long?
1010 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001011 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001012 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001013 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001014 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001015 }
1016 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001017
Reid Spencer5f016e22007-07-11 17:01:13 +00001018 // If we still couldn't decide a type, we probably have something that
1019 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001020 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001021 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001022 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001023 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001024 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001025
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001026 if (ResultVal.getBitWidth() != Width)
1027 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001028 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001029 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001030 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001031
Chris Lattner5d661452007-08-26 03:42:43 +00001032 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1033 if (Literal.isImaginary)
Steve Naroff6ece14c2009-01-21 00:14:39 +00001034 Res = new (Context) ImaginaryLiteral(Res,
1035 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001036
1037 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001038}
1039
Sebastian Redlcd965b92009-01-18 18:53:16 +00001040Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1041 SourceLocation R, ExprArg Val) {
1042 Expr *E = (Expr *)Val.release();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001043 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001044 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001045}
1046
1047/// The UsualUnaryConversions() function is *not* called by this routine.
1048/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl05189992008-11-11 17:56:53 +00001049bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1050 SourceLocation OpLoc,
1051 const SourceRange &ExprRange,
1052 bool isSizeof) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001053 // C99 6.5.3.4p1:
Chris Lattner01072922009-01-24 19:46:37 +00001054 if (isa<FunctionType>(exprType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001055 // alignof(function) is allowed.
Chris Lattner01072922009-01-24 19:46:37 +00001056 if (isSizeof)
1057 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1058 return false;
1059 }
1060
1061 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001062 Diag(OpLoc, diag::ext_sizeof_void_type)
1063 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001064 return false;
1065 }
Sebastian Redl05189992008-11-11 17:56:53 +00001066
Chris Lattner01072922009-01-24 19:46:37 +00001067 return DiagnoseIncompleteType(OpLoc, exprType,
1068 isSizeof ? diag::err_sizeof_incomplete_type :
1069 diag::err_alignof_incomplete_type,
1070 ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +00001071}
1072
Chris Lattner31e21e02009-01-24 20:17:12 +00001073bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1074 const SourceRange &ExprRange) {
1075 E = E->IgnoreParens();
1076
1077 // alignof decl is always ok.
1078 if (isa<DeclRefExpr>(E))
1079 return false;
1080
1081 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1082 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1083 if (FD->isBitField()) {
Chris Lattnerda027472009-01-24 21:29:22 +00001084 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner31e21e02009-01-24 20:17:12 +00001085 return true;
1086 }
1087 // Other fields are ok.
1088 return false;
1089 }
1090 }
1091 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1092}
1093
Sebastian Redl05189992008-11-11 17:56:53 +00001094/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1095/// the same for @c alignof and @c __alignof
1096/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001097Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001098Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1099 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001100 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001101 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001102
Sebastian Redl05189992008-11-11 17:56:53 +00001103 QualType ArgTy;
1104 SourceRange Range;
1105 if (isType) {
1106 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1107 Range = ArgRange;
Chris Lattner694b1e42009-01-24 19:49:13 +00001108
1109 // Verify that the operand is valid.
1110 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1111 return ExprError();
Sebastian Redl05189992008-11-11 17:56:53 +00001112 } else {
1113 // Get the end location.
1114 Expr *ArgEx = (Expr *)TyOrEx;
1115 Range = ArgEx->getSourceRange();
1116 ArgTy = ArgEx->getType();
Chris Lattner694b1e42009-01-24 19:49:13 +00001117
1118 // Verify that the operand is valid.
Chris Lattner31e21e02009-01-24 20:17:12 +00001119 bool isInvalid;
Chris Lattnerda027472009-01-24 21:29:22 +00001120 if (!isSizeof) {
Chris Lattner31e21e02009-01-24 20:17:12 +00001121 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattnerda027472009-01-24 21:29:22 +00001122 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1123 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1124 isInvalid = true;
1125 } else {
1126 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1127 }
Chris Lattner31e21e02009-01-24 20:17:12 +00001128
1129 if (isInvalid) {
Chris Lattner694b1e42009-01-24 19:49:13 +00001130 DeleteExpr(ArgEx);
1131 return ExprError();
1132 }
Sebastian Redl05189992008-11-11 17:56:53 +00001133 }
1134
Sebastian Redl05189992008-11-11 17:56:53 +00001135 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001136 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner01072922009-01-24 19:46:37 +00001137 Context.getSizeType(), OpLoc,
1138 Range.getEnd()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001139}
1140
Chris Lattner5d794252007-08-24 21:41:10 +00001141QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +00001142 DefaultFunctionArrayConversion(V);
1143
Chris Lattnercc26ed72007-08-26 05:39:26 +00001144 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +00001145 if (const ComplexType *CT = V->getType()->getAsComplexType())
1146 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +00001147
1148 // Otherwise they pass through real integer and floating point types here.
1149 if (V->getType()->isArithmeticType())
1150 return V->getType();
1151
1152 // Reject anything else.
Chris Lattnerd1625842008-11-24 06:25:27 +00001153 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnercc26ed72007-08-26 05:39:26 +00001154 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001155}
1156
1157
Reid Spencer5f016e22007-07-11 17:01:13 +00001158
Sebastian Redl0eb23302009-01-19 00:08:26 +00001159Action::OwningExprResult
1160Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1161 tok::TokenKind Kind, ExprArg Input) {
1162 Expr *Arg = (Expr *)Input.get();
Douglas Gregor74253732008-11-19 15:42:04 +00001163
Reid Spencer5f016e22007-07-11 17:01:13 +00001164 UnaryOperator::Opcode Opc;
1165 switch (Kind) {
1166 default: assert(0 && "Unknown unary op!");
1167 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1168 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1169 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001170
Douglas Gregor74253732008-11-19 15:42:04 +00001171 if (getLangOptions().CPlusPlus &&
1172 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1173 // Which overloaded operator?
Sebastian Redl0eb23302009-01-19 00:08:26 +00001174 OverloadedOperatorKind OverOp =
Douglas Gregor74253732008-11-19 15:42:04 +00001175 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1176
1177 // C++ [over.inc]p1:
1178 //
1179 // [...] If the function is a member function with one
1180 // parameter (which shall be of type int) or a non-member
1181 // function with two parameters (the second of which shall be
1182 // of type int), it defines the postfix increment operator ++
1183 // for objects of that type. When the postfix increment is
1184 // called as a result of using the ++ operator, the int
1185 // argument will have value zero.
1186 Expr *Args[2] = {
1187 Arg,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001188 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1189 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor74253732008-11-19 15:42:04 +00001190 };
1191
1192 // Build the candidate set for overloading
1193 OverloadCandidateSet CandidateSet;
Douglas Gregorf680a0f2009-02-04 16:44:47 +00001194 if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet))
1195 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001196
1197 // Perform overload resolution.
1198 OverloadCandidateSet::iterator Best;
1199 switch (BestViableFunction(CandidateSet, Best)) {
1200 case OR_Success: {
1201 // We found a built-in operator or an overloaded operator.
1202 FunctionDecl *FnDecl = Best->Function;
1203
1204 if (FnDecl) {
1205 // We matched an overloaded operator. Build a call to that
1206 // operator.
1207
1208 // Convert the arguments.
1209 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1210 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001211 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001212 } else {
1213 // Convert the arguments.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001214 if (PerformCopyInitialization(Arg,
Douglas Gregor74253732008-11-19 15:42:04 +00001215 FnDecl->getParamDecl(0)->getType(),
1216 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001217 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001218 }
1219
1220 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00001221 QualType ResultTy
Douglas Gregor74253732008-11-19 15:42:04 +00001222 = FnDecl->getType()->getAsFunctionType()->getResultType();
1223 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001224
Douglas Gregor74253732008-11-19 15:42:04 +00001225 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001226 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor74253732008-11-19 15:42:04 +00001227 SourceLocation());
1228 UsualUnaryConversions(FnExpr);
1229
Sebastian Redl0eb23302009-01-19 00:08:26 +00001230 Input.release();
Ted Kremenek668bf912009-02-09 20:51:47 +00001231 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
1232 ResultTy, OpLoc));
Douglas Gregor74253732008-11-19 15:42:04 +00001233 } else {
1234 // We matched a built-in operator. Convert the arguments, then
1235 // break out so that we will build the appropriate built-in
1236 // operator node.
1237 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1238 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001239 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001240
1241 break;
Sebastian Redl0eb23302009-01-19 00:08:26 +00001242 }
Douglas Gregor74253732008-11-19 15:42:04 +00001243 }
1244
1245 case OR_No_Viable_Function:
1246 // No viable function; fall through to handling this as a
1247 // built-in operator, which will produce an error message for us.
1248 break;
1249
1250 case OR_Ambiguous:
1251 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1252 << UnaryOperator::getOpcodeStr(Opc)
1253 << Arg->getSourceRange();
1254 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001255 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001256 }
1257
1258 // Either we found no viable overloaded operator or we matched a
1259 // built-in operator. In either case, fall through to trying to
1260 // build a built-in operation.
1261 }
1262
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00001263 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1264 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001265 if (result.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001266 return ExprError();
1267 Input.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001268 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001269}
1270
Sebastian Redl0eb23302009-01-19 00:08:26 +00001271Action::OwningExprResult
1272Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1273 ExprArg Idx, SourceLocation RLoc) {
1274 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1275 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner12d9ff62007-07-16 00:14:47 +00001276
Douglas Gregor337c6b92008-11-19 17:17:41 +00001277 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00001278 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00001279 LHSExp->getType()->isEnumeralType() ||
1280 RHSExp->getType()->isRecordType() ||
1281 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor337c6b92008-11-19 17:17:41 +00001282 // Add the appropriate overloaded operators (C++ [over.match.oper])
1283 // to the candidate set.
1284 OverloadCandidateSet CandidateSet;
1285 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregorf680a0f2009-02-04 16:44:47 +00001286 if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1287 SourceRange(LLoc, RLoc)))
1288 return ExprError();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001289
Douglas Gregor337c6b92008-11-19 17:17:41 +00001290 // Perform overload resolution.
1291 OverloadCandidateSet::iterator Best;
1292 switch (BestViableFunction(CandidateSet, Best)) {
1293 case OR_Success: {
1294 // We found a built-in operator or an overloaded operator.
1295 FunctionDecl *FnDecl = Best->Function;
1296
1297 if (FnDecl) {
1298 // We matched an overloaded operator. Build a call to that
1299 // operator.
1300
1301 // Convert the arguments.
1302 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1303 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1304 PerformCopyInitialization(RHSExp,
1305 FnDecl->getParamDecl(0)->getType(),
1306 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001307 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001308 } else {
1309 // Convert the arguments.
1310 if (PerformCopyInitialization(LHSExp,
1311 FnDecl->getParamDecl(0)->getType(),
1312 "passing") ||
1313 PerformCopyInitialization(RHSExp,
1314 FnDecl->getParamDecl(1)->getType(),
1315 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001316 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001317 }
1318
1319 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00001320 QualType ResultTy
Douglas Gregor337c6b92008-11-19 17:17:41 +00001321 = FnDecl->getType()->getAsFunctionType()->getResultType();
1322 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001323
Douglas Gregor337c6b92008-11-19 17:17:41 +00001324 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001325 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor337c6b92008-11-19 17:17:41 +00001326 SourceLocation());
1327 UsualUnaryConversions(FnExpr);
1328
Sebastian Redl0eb23302009-01-19 00:08:26 +00001329 Base.release();
1330 Idx.release();
Ted Kremenek668bf912009-02-09 20:51:47 +00001331 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001332 ResultTy, LLoc));
Douglas Gregor337c6b92008-11-19 17:17:41 +00001333 } else {
1334 // We matched a built-in operator. Convert the arguments, then
1335 // break out so that we will build the appropriate built-in
1336 // operator node.
1337 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1338 "passing") ||
1339 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1340 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001341 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001342
1343 break;
1344 }
1345 }
1346
1347 case OR_No_Viable_Function:
1348 // No viable function; fall through to handling this as a
1349 // built-in operator, which will produce an error message for us.
1350 break;
1351
1352 case OR_Ambiguous:
1353 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1354 << "[]"
1355 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1356 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001357 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001358 }
1359
1360 // Either we found no viable overloaded operator or we matched a
1361 // built-in operator. In either case, fall through to trying to
1362 // build a built-in operation.
1363 }
1364
Chris Lattner12d9ff62007-07-16 00:14:47 +00001365 // Perform default conversions.
1366 DefaultFunctionArrayConversion(LHSExp);
1367 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001368
Chris Lattner12d9ff62007-07-16 00:14:47 +00001369 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001370
Reid Spencer5f016e22007-07-11 17:01:13 +00001371 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001372 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +00001373 // in the subscript position. As a result, we need to derive the array base
1374 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001375 Expr *BaseExpr, *IndexExpr;
1376 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +00001377 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001378 BaseExpr = LHSExp;
1379 IndexExpr = RHSExp;
1380 // FIXME: need to deal with const...
1381 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +00001382 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001383 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001384 BaseExpr = RHSExp;
1385 IndexExpr = LHSExp;
1386 // FIXME: need to deal with const...
1387 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +00001388 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1389 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001390 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00001391
Chris Lattner12d9ff62007-07-16 00:14:47 +00001392 // FIXME: need to deal with const...
1393 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001394 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00001395 return ExprError(Diag(LHSExp->getLocStart(),
1396 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1397 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001398 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +00001399 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001400 return ExprError(Diag(IndexExpr->getLocStart(),
1401 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001402
Chris Lattner12d9ff62007-07-16 00:14:47 +00001403 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1404 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001405 // void (*)(int)) and pointers to incomplete types. Functions are not
1406 // objects in C99.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001407 if (!ResultType->isObjectType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001408 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001409 diag::err_typecheck_subscript_not_object)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001410 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner12d9ff62007-07-16 00:14:47 +00001411
Sebastian Redl0eb23302009-01-19 00:08:26 +00001412 Base.release();
1413 Idx.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001414 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1415 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001416}
1417
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001418QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001419CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001420 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +00001421 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +00001422
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001423 // The vector accessor can't exceed the number of elements.
1424 const char *compStr = CompName.getName();
Nate Begeman353417a2009-01-18 01:47:54 +00001425
1426 // This flag determines whether or not the component is one of the four
1427 // special names that indicate a subset of exactly half the elements are
1428 // to be selected.
1429 bool HalvingSwizzle = false;
1430
1431 // This flag determines whether or not CompName has an 's' char prefix,
1432 // indicating that it is a string of hex values to be used as vector indices.
1433 bool HexSwizzle = *compStr == 's';
Nate Begeman8a997642008-05-09 06:41:27 +00001434
1435 // Check that we've found one of the special components, or that the component
1436 // names must come from the same set.
1437 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00001438 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1439 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00001440 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001441 do
1442 compStr++;
1443 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00001444 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001445 do
1446 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001447 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00001448 }
Nate Begeman353417a2009-01-18 01:47:54 +00001449
1450 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001451 // We didn't get to the end of the string. This means the component names
1452 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001453 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1454 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001455 return QualType();
1456 }
Nate Begeman353417a2009-01-18 01:47:54 +00001457
1458 // Ensure no component accessor exceeds the width of the vector type it
1459 // operates on.
1460 if (!HalvingSwizzle) {
1461 compStr = CompName.getName();
1462
1463 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001464 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001465
1466 while (*compStr) {
1467 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1468 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1469 << baseType << SourceRange(CompLoc);
1470 return QualType();
1471 }
1472 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001473 }
Nate Begeman8a997642008-05-09 06:41:27 +00001474
Nate Begeman353417a2009-01-18 01:47:54 +00001475 // If this is a halving swizzle, verify that the base type has an even
1476 // number of elements.
1477 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001478 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00001479 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00001480 return QualType();
1481 }
1482
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001483 // The component accessor looks fine - now we need to compute the actual type.
1484 // The vector type is implied by the component accessor. For example,
1485 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00001486 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00001487 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman353417a2009-01-18 01:47:54 +00001488 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1489 : CompName.getLength();
1490 if (HexSwizzle)
1491 CompSize--;
1492
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001493 if (CompSize == 1)
1494 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +00001495
Nate Begeman213541a2008-04-18 23:10:10 +00001496 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroffbea0b342007-07-29 16:33:31 +00001497 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00001498 // diagostics look bad. We want extended vector types to appear built-in.
1499 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1500 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1501 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00001502 }
1503 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001504}
1505
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001506/// constructSetterName - Return the setter name for the given
1507/// identifier, i.e. "set" + Name where the initial character of Name
1508/// has been capitalized.
1509// FIXME: Merge with same routine in Parser. But where should this
1510// live?
1511static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1512 const IdentifierInfo *Name) {
1513 llvm::SmallString<100> SelectorName;
1514 SelectorName = "set";
1515 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1516 SelectorName[3] = toupper(SelectorName[3]);
1517 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1518}
1519
Sebastian Redl0eb23302009-01-19 00:08:26 +00001520Action::OwningExprResult
1521Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1522 tok::TokenKind OpKind, SourceLocation MemberLoc,
1523 IdentifierInfo &Member) {
1524 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001525 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +00001526
1527 // Perform default conversions.
1528 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001529
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001530 QualType BaseType = BaseExpr->getType();
1531 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00001532
Chris Lattner68a057b2008-07-21 04:36:39 +00001533 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1534 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +00001535 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +00001536 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001537 BaseType = PT->getPointeeType();
Douglas Gregor8ba10742008-11-20 16:27:02 +00001538 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001539 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1540 MemberLoc, Member));
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001541 else
Sebastian Redl0eb23302009-01-19 00:08:26 +00001542 return ExprError(Diag(MemberLoc,
1543 diag::err_typecheck_member_reference_arrow)
1544 << BaseType << BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001545 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001546
Chris Lattner68a057b2008-07-21 04:36:39 +00001547 // Handle field access to simple records. This also handles access to fields
1548 // of the ObjC 'id' struct.
Chris Lattnerc8629632007-07-31 19:29:30 +00001549 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001550 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00001551 if (DiagnoseIncompleteType(OpLoc, BaseType,
1552 diag::err_typecheck_incomplete_tag,
1553 BaseExpr->getSourceRange()))
1554 return ExprError();
1555
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001556 // The record definition is complete, now make sure the member is valid.
Douglas Gregor44b43212008-12-11 16:49:14 +00001557 // FIXME: Qualified name lookup for C++ is a bit more complicated
1558 // than this.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001559 LookupResult Result
Douglas Gregor7176fff2009-01-15 00:26:24 +00001560 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001561 LookupMemberName, false);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001562
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001563 NamedDecl *MemberDecl = 0;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001564 if (!Result)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001565 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1566 << &Member << BaseExpr->getSourceRange());
1567 else if (Result.isAmbiguous()) {
1568 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1569 MemberLoc, BaseExpr->getSourceRange());
1570 return ExprError();
1571 } else
Douglas Gregor7176fff2009-01-15 00:26:24 +00001572 MemberDecl = Result;
Douglas Gregor44b43212008-12-11 16:49:14 +00001573
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001574 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001575 // We may have found a field within an anonymous union or struct
1576 // (C++ [class.union]).
1577 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001578 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001579 BaseExpr, OpLoc);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001580
Douglas Gregor86f19402008-12-20 23:49:58 +00001581 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1582 // FIXME: Handle address space modifiers
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001583 QualType MemberType = FD->getType();
Douglas Gregor86f19402008-12-20 23:49:58 +00001584 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1585 MemberType = Ref->getPointeeType();
1586 else {
1587 unsigned combinedQualifiers =
1588 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001589 if (FD->isMutable())
Douglas Gregor86f19402008-12-20 23:49:58 +00001590 combinedQualifiers &= ~QualType::Const;
1591 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1592 }
Eli Friedman51019072008-02-06 22:48:16 +00001593
Steve Naroff6ece14c2009-01-21 00:14:39 +00001594 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1595 MemberLoc, MemberType));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001596 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001597 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001598 Var, MemberLoc,
1599 Var->getType().getNonReferenceType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001600 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001601 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1602 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00001603 else if (OverloadedFunctionDecl *Ovl
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001604 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001605 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001606 MemberLoc, Context.OverloadTy));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001607 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001608 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Enum,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001609 MemberLoc, Enum->getType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001610 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001611 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1612 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman51019072008-02-06 22:48:16 +00001613
Douglas Gregor86f19402008-12-20 23:49:58 +00001614 // We found a declaration kind that we didn't expect. This is a
1615 // generic error message that tells the user that she can't refer
1616 // to this member with '.' or '->'.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001617 return ExprError(Diag(MemberLoc,
1618 diag::err_typecheck_member_reference_unknown)
1619 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001620 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001621
Chris Lattnera38e6b12008-07-21 04:59:05 +00001622 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1623 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +00001624 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00001625 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Steve Naroff6ece14c2009-01-21 00:14:39 +00001626 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1627 MemberLoc, BaseExpr,
Fariborz Jahanianefc4c4b2008-12-18 17:29:46 +00001628 OpKind == tok::arrow);
1629 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001630 return Owned(MRef);
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00001631 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001632 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1633 << IFTy->getDecl()->getDeclName() << &Member
1634 << BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001635 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001636
Chris Lattnera38e6b12008-07-21 04:59:05 +00001637 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1638 // pointer to a (potentially qualified) interface type.
1639 const PointerType *PTy;
1640 const ObjCInterfaceType *IFTy;
1641 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1642 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1643 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001644
Daniel Dunbar2307d312008-09-03 01:05:41 +00001645 // Search for a declared property first.
Chris Lattnera38e6b12008-07-21 04:59:05 +00001646 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001647 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl0eb23302009-01-19 00:08:26 +00001648 MemberLoc, BaseExpr));
1649
Daniel Dunbar2307d312008-09-03 01:05:41 +00001650 // Check protocols on qualified interfaces.
Chris Lattner9baefc22008-07-21 05:20:01 +00001651 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1652 E = IFTy->qual_end(); I != E; ++I)
1653 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001654 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl0eb23302009-01-19 00:08:26 +00001655 MemberLoc, BaseExpr));
Daniel Dunbar2307d312008-09-03 01:05:41 +00001656
1657 // If that failed, look for an "implicit" property by seeing if the nullary
1658 // selector is implemented.
1659
1660 // FIXME: The logic for looking up nullary and unary selectors should be
1661 // shared with the code in ActOnInstanceMessage.
1662
1663 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1664 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001665
Daniel Dunbar2307d312008-09-03 01:05:41 +00001666 // If this reference is in an @implementation, check for 'private' methods.
1667 if (!Getter)
1668 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1669 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1670 if (ObjCImplementationDecl *ImpDecl =
1671 ObjCImplementations[ClassDecl->getIdentifier()])
1672 Getter = ImpDecl->getInstanceMethod(Sel);
1673
Steve Naroff7692ed62008-10-22 19:16:27 +00001674 // Look through local category implementations associated with the class.
1675 if (!Getter) {
1676 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1677 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1678 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1679 }
1680 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00001681 if (Getter) {
1682 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001683 // will look for the matching setter, in case it is needed.
1684 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1685 &Member);
1686 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1687 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1688 if (!Setter) {
1689 // If this reference is in an @implementation, also check for 'private'
1690 // methods.
1691 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1692 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1693 if (ObjCImplementationDecl *ImpDecl =
1694 ObjCImplementations[ClassDecl->getIdentifier()])
1695 Setter = ImpDecl->getInstanceMethod(SetterSel);
1696 }
1697 // Look through local category implementations associated with the class.
1698 if (!Setter) {
1699 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1700 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1701 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1702 }
1703 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001704
1705 // FIXME: we must check that the setter has property type.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001706 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
1707 Setter, MemberLoc, BaseExpr));
Daniel Dunbar2307d312008-09-03 01:05:41 +00001708 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001709
1710 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1711 << &Member << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00001712 }
Steve Naroff18bc1642008-10-20 22:53:06 +00001713 // Handle properties on qualified "id" protocols.
1714 const ObjCQualifiedIdType *QIdTy;
1715 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1716 // Check protocols on qualified interfaces.
1717 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001718 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroff18bc1642008-10-20 22:53:06 +00001719 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001720 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl0eb23302009-01-19 00:08:26 +00001721 MemberLoc, BaseExpr));
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001722 // Also must look for a getter name which uses property syntax.
1723 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1724 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Steve Naroff6ece14c2009-01-21 00:14:39 +00001725 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
1726 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001727 }
1728 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001729
1730 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1731 << &Member << BaseType);
1732 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001733 // Handle 'field access' to vectors, such as 'V.xx'.
1734 if (BaseType->isExtVectorType() && OpKind == tok::period) {
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001735 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1736 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001737 return ExprError();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001738 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
1739 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001740 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001741
1742 return ExprError(Diag(MemberLoc,
1743 diag::err_typecheck_member_reference_struct_union)
1744 << BaseType << BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001745}
1746
Douglas Gregor88a35142008-12-22 05:46:06 +00001747/// ConvertArgumentsForCall - Converts the arguments specified in
1748/// Args/NumArgs to the parameter types of the function FDecl with
1749/// function prototype Proto. Call is the call expression itself, and
1750/// Fn is the function expression. For a C++ member function, this
1751/// routine does not attempt to convert the object argument. Returns
1752/// true if the call is ill-formed.
1753bool
1754Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1755 FunctionDecl *FDecl,
1756 const FunctionTypeProto *Proto,
1757 Expr **Args, unsigned NumArgs,
1758 SourceLocation RParenLoc) {
1759 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1760 // assignment, to the types of the corresponding parameter, ...
1761 unsigned NumArgsInProto = Proto->getNumArgs();
1762 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor3fd56d72009-01-23 21:30:56 +00001763 bool Invalid = false;
1764
Douglas Gregor88a35142008-12-22 05:46:06 +00001765 // If too few arguments are available (and we don't have default
1766 // arguments for the remaining parameters), don't make the call.
1767 if (NumArgs < NumArgsInProto) {
1768 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1769 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1770 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1771 // Use default arguments for missing arguments
1772 NumArgsToCheck = NumArgsInProto;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001773 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00001774 }
1775
1776 // If too many are passed and not variadic, error on the extras and drop
1777 // them.
1778 if (NumArgs > NumArgsInProto) {
1779 if (!Proto->isVariadic()) {
1780 Diag(Args[NumArgsInProto]->getLocStart(),
1781 diag::err_typecheck_call_too_many_args)
1782 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1783 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1784 Args[NumArgs-1]->getLocEnd());
1785 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001786 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3fd56d72009-01-23 21:30:56 +00001787 Invalid = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00001788 }
1789 NumArgsToCheck = NumArgsInProto;
1790 }
1791
1792 // Continue to check argument types (even if we have too few/many args).
1793 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1794 QualType ProtoArgType = Proto->getArgType(i);
1795
1796 Expr *Arg;
Douglas Gregor61366e92008-12-24 00:01:03 +00001797 if (i < NumArgs) {
Douglas Gregor88a35142008-12-22 05:46:06 +00001798 Arg = Args[i];
Douglas Gregor61366e92008-12-24 00:01:03 +00001799
1800 // Pass the argument.
1801 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1802 return true;
1803 } else
1804 // We already type-checked the argument, so we know it works.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001805 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor88a35142008-12-22 05:46:06 +00001806 QualType ArgType = Arg->getType();
Douglas Gregor61366e92008-12-24 00:01:03 +00001807
Douglas Gregor88a35142008-12-22 05:46:06 +00001808 Call->setArg(i, Arg);
1809 }
1810
1811 // If this is a variadic call, handle args passed through "...".
1812 if (Proto->isVariadic()) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +00001813 VariadicCallType CallType = VariadicFunction;
1814 if (Fn->getType()->isBlockPointerType())
1815 CallType = VariadicBlock; // Block
1816 else if (isa<MemberExpr>(Fn))
1817 CallType = VariadicMethod;
1818
Douglas Gregor88a35142008-12-22 05:46:06 +00001819 // Promote the arguments (C99 6.5.2.2p7).
1820 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1821 Expr *Arg = Args[i];
Anders Carlssondce5e2c2009-01-16 16:48:51 +00001822 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor88a35142008-12-22 05:46:06 +00001823 Call->setArg(i, Arg);
1824 }
1825 }
1826
Douglas Gregor3fd56d72009-01-23 21:30:56 +00001827 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00001828}
1829
Steve Narofff69936d2007-09-16 03:34:24 +00001830/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00001831/// This provides the location of the left/right parens and a list of comma
1832/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001833Action::OwningExprResult
1834Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1835 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00001836 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00001837 unsigned NumArgs = args.size();
1838 Expr *Fn = static_cast<Expr *>(fn.release());
1839 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00001840 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00001841 FunctionDecl *FDecl = NULL;
Douglas Gregor17330012009-02-04 15:01:18 +00001842 DeclarationName UnqualifiedName;
Douglas Gregor88a35142008-12-22 05:46:06 +00001843
Douglas Gregor88a35142008-12-22 05:46:06 +00001844 if (getLangOptions().CPlusPlus) {
Douglas Gregor17330012009-02-04 15:01:18 +00001845 // Determine whether this is a dependent call inside a C++ template,
1846 // in which case we won't do any semantic analysis now.
1847 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
1848 bool Dependent = false;
1849 if (Fn->isTypeDependent())
1850 Dependent = true;
1851 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1852 Dependent = true;
1853
1854 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00001855 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00001856 Context.DependentTy, RParenLoc));
1857
1858 // Determine whether this is a call to an object (C++ [over.call.object]).
1859 if (Fn->getType()->isRecordType())
1860 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1861 CommaLocs, RParenLoc));
1862
Douglas Gregorfa047642009-02-04 00:32:51 +00001863 // Determine whether this is a call to a member function.
Douglas Gregor88a35142008-12-22 05:46:06 +00001864 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1865 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1866 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001867 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1868 CommaLocs, RParenLoc));
Douglas Gregor88a35142008-12-22 05:46:06 +00001869 }
1870
Douglas Gregorfa047642009-02-04 00:32:51 +00001871 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor1a49af92009-01-06 05:10:23 +00001872 DeclRefExpr *DRExpr = NULL;
Douglas Gregorfa047642009-02-04 00:32:51 +00001873 Expr *FnExpr = Fn;
1874 bool ADL = true;
1875 while (true) {
1876 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
1877 FnExpr = IcExpr->getSubExpr();
1878 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Douglas Gregor17330012009-02-04 15:01:18 +00001879 // Parentheses around a function disable ADL
1880 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregorfa047642009-02-04 00:32:51 +00001881 ADL = false;
1882 FnExpr = PExpr->getSubExpr();
1883 } else if (isa<UnaryOperator>(FnExpr) &&
1884 cast<UnaryOperator>(FnExpr)->getOpcode()
1885 == UnaryOperator::AddrOf) {
1886 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
1887 } else {
Douglas Gregor17330012009-02-04 15:01:18 +00001888 if (isa<DeclRefExpr>(FnExpr)) {
1889 DRExpr = cast<DeclRefExpr>(FnExpr);
1890
1891 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
1892 ADL = ADL && !isa<QualifiedDeclRefExpr>(DRExpr);
1893 }
1894 else if (UnresolvedFunctionNameExpr *DepName
1895 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr))
1896 UnqualifiedName = DepName->getName();
1897 else {
1898 // Any kind of name that does not refer to a declaration (or
1899 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
1900 ADL = false;
1901 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001902 break;
1903 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001904 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001905
Douglas Gregor17330012009-02-04 15:01:18 +00001906 OverloadedFunctionDecl *Ovl = 0;
1907 if (DRExpr) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001908 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor17330012009-02-04 15:01:18 +00001909 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1910 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001911
Douglas Gregorf9201e02009-02-11 23:02:49 +00001912 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001913 // We don't perform ADL for builtins.
1914 if (FDecl && FDecl->getIdentifier() &&
1915 FDecl->getIdentifier()->getBuiltinID())
1916 ADL = false;
1917
Douglas Gregorf9201e02009-02-11 23:02:49 +00001918 // We don't perform ADL in C.
1919 if (!getLangOptions().CPlusPlus)
1920 ADL = false;
1921
Douglas Gregor17330012009-02-04 15:01:18 +00001922 if (Ovl || ADL) {
1923 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
1924 UnqualifiedName, LParenLoc, Args,
Douglas Gregorfa047642009-02-04 00:32:51 +00001925 NumArgs, CommaLocs, RParenLoc, ADL);
1926 if (!FDecl)
1927 return ExprError();
1928
1929 // Update Fn to refer to the actual function selected.
1930 Expr *NewFn = 0;
1931 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor17330012009-02-04 15:01:18 +00001932 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Douglas Gregorfa047642009-02-04 00:32:51 +00001933 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
1934 QDRExpr->getLocation(),
1935 false, false,
1936 QDRExpr->getSourceRange().getBegin());
1937 else
1938 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
1939 Fn->getSourceRange().getBegin());
1940 Fn->Destroy(Context);
1941 Fn = NewFn;
1942 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001943 }
Chris Lattner04421082008-04-08 04:40:51 +00001944
1945 // Promote the function operand.
1946 UsualUnaryConversions(Fn);
1947
Chris Lattner925e60d2007-12-28 05:29:59 +00001948 // Make the call expr early, before semantic checks. This guarantees cleanup
1949 // of arguments and function on error.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001950 // FIXME: Except that llvm::OwningPtr uses delete, when it really must be
1951 // Destroy(), or nothing gets cleaned up.
Ted Kremenek668bf912009-02-09 20:51:47 +00001952 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
1953 Args, NumArgs,
1954 Context.BoolTy,
1955 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00001956
Steve Naroffdd972f22008-09-05 22:11:13 +00001957 const FunctionType *FuncT;
1958 if (!Fn->getType()->isBlockPointerType()) {
1959 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1960 // have type pointer to function".
1961 const PointerType *PT = Fn->getType()->getAsPointerType();
1962 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001963 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1964 << Fn->getType() << Fn->getSourceRange());
Steve Naroffdd972f22008-09-05 22:11:13 +00001965 FuncT = PT->getPointeeType()->getAsFunctionType();
1966 } else { // This is a block call.
1967 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1968 getAsFunctionType();
1969 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001970 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001971 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1972 << Fn->getType() << Fn->getSourceRange());
1973
Chris Lattner925e60d2007-12-28 05:29:59 +00001974 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001975 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001976
Chris Lattner925e60d2007-12-28 05:29:59 +00001977 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00001978 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
1979 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001980 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00001981 } else {
1982 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00001983
Steve Naroffb291ab62007-08-28 23:30:39 +00001984 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00001985 for (unsigned i = 0; i != NumArgs; i++) {
1986 Expr *Arg = Args[i];
1987 DefaultArgumentPromotion(Arg);
1988 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001989 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001990 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001991
Douglas Gregor88a35142008-12-22 05:46:06 +00001992 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
1993 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001994 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
1995 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00001996
Chris Lattner59907c42007-08-10 20:18:51 +00001997 // Do special checking on direct calls to functions.
Eli Friedmand38617c2008-05-14 19:38:39 +00001998 if (FDecl)
1999 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +00002000
Sebastian Redl0eb23302009-01-19 00:08:26 +00002001 return Owned(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00002002}
2003
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002004Action::OwningExprResult
2005Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2006 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00002007 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +00002008 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00002009 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00002010 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002011 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00002012
Eli Friedman6223c222008-05-20 05:22:08 +00002013 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002014 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002015 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2016 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002017 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2018 diag::err_typecheck_decl_incomplete_type,
2019 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002020 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00002021
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002022 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002023 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002024 return ExprError();
Steve Naroffe9b12192008-01-14 18:19:28 +00002025
Chris Lattner371f2582008-12-04 23:50:19 +00002026 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00002027 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00002028 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002029 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002030 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002031 InitExpr.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00002032 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
2033 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00002034}
2035
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002036Action::OwningExprResult
2037Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2038 InitListDesignations &Designators,
2039 SourceLocation RBraceLoc) {
2040 unsigned NumInit = initlist.size();
2041 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00002042
Steve Naroff08d92e42007-09-15 18:49:24 +00002043 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +00002044 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002045
Steve Naroff6ece14c2009-01-21 00:14:39 +00002046 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00002047 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002048 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002049 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00002050}
2051
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002052/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar58d5ebb2008-08-20 03:55:42 +00002053bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002054 UsualUnaryConversions(castExpr);
2055
2056 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2057 // type needs to be scalar.
2058 if (castType->isVoidType()) {
2059 // Cast to void allows any expr type.
Douglas Gregor898574e2008-12-05 23:32:09 +00002060 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2061 // We can't check any more until template instantiation time.
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002062 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00002063 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2064 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2065 (castType->isStructureType() || castType->isUnionType())) {
2066 // GCC struct/union extension: allow cast to self.
2067 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2068 << castType << castExpr->getSourceRange();
2069 } else if (castType->isUnionType()) {
2070 // GCC cast to union extension
2071 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2072 RecordDecl::field_iterator Field, FieldEnd;
2073 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2074 Field != FieldEnd; ++Field) {
2075 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2076 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2077 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2078 << castExpr->getSourceRange();
2079 break;
2080 }
2081 }
2082 if (Field == FieldEnd)
2083 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2084 << castExpr->getType() << castExpr->getSourceRange();
2085 } else {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002086 // Reject any other conversions to non-scalar types.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002087 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00002088 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002089 }
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002090 } else if (!castExpr->getType()->isScalarType() &&
2091 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002092 return Diag(castExpr->getLocStart(),
2093 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00002094 << castExpr->getType() << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002095 } else if (castExpr->getType()->isVectorType()) {
2096 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2097 return true;
2098 } else if (castType->isVectorType()) {
2099 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2100 return true;
2101 }
2102 return false;
2103}
2104
Chris Lattnerfe23e212007-12-20 00:44:32 +00002105bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00002106 assert(VectorTy->isVectorType() && "Not a vector type!");
2107
2108 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00002109 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00002110 return Diag(R.getBegin(),
2111 Ty->isVectorType() ?
2112 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002113 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002114 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00002115 } else
2116 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002117 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00002118 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00002119
2120 return false;
2121}
2122
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002123Action::OwningExprResult
2124Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2125 SourceLocation RParenLoc, ExprArg Op) {
2126 assert((Ty != 0) && (Op.get() != 0) &&
2127 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00002128
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002129 Expr *castExpr = static_cast<Expr*>(Op.release());
Steve Naroff16beff82007-07-16 23:25:18 +00002130 QualType castType = QualType::getFromOpaquePtr(Ty);
2131
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002132 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002133 return ExprError();
Steve Naroff6ece14c2009-01-21 00:14:39 +00002134 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002135 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002136}
2137
Chris Lattnera21ddb32007-11-26 01:40:58 +00002138/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2139/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +00002140inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +00002141 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002142 UsualUnaryConversions(cond);
2143 UsualUnaryConversions(lex);
2144 UsualUnaryConversions(rex);
2145 QualType condT = cond->getType();
2146 QualType lexT = lex->getType();
2147 QualType rexT = rex->getType();
2148
Reid Spencer5f016e22007-07-11 17:01:13 +00002149 // first, check the condition.
Douglas Gregor898574e2008-12-05 23:32:09 +00002150 if (!cond->isTypeDependent()) {
2151 if (!condT->isScalarType()) { // C99 6.5.15p2
2152 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
2153 return QualType();
2154 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002155 }
Chris Lattner70d67a92008-01-06 22:42:25 +00002156
2157 // Now check the two expressions.
Douglas Gregor898574e2008-12-05 23:32:09 +00002158 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
2159 return Context.DependentTy;
2160
Chris Lattner70d67a92008-01-06 22:42:25 +00002161 // If both operands have arithmetic type, do the usual arithmetic conversions
2162 // to find a common type: C99 6.5.15p3,5.
2163 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Steve Naroffa4332e22007-07-17 00:58:39 +00002164 UsualArithmeticConversions(lex, rex);
2165 return lex->getType();
2166 }
Chris Lattner70d67a92008-01-06 22:42:25 +00002167
2168 // If both operands are the same structure or union type, the result is that
2169 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002170 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner70d67a92008-01-06 22:42:25 +00002171 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +00002172 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner70d67a92008-01-06 22:42:25 +00002173 // "If both the operands have structure or union type, the result has
2174 // that type." This implies that CV qualifiers are dropped.
2175 return lexT.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002176 }
Chris Lattner70d67a92008-01-06 22:42:25 +00002177
2178 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00002179 // The following || allows only one side to be void (a GCC-ism).
2180 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedman0e724012008-06-04 19:47:51 +00002181 if (!lexT->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002182 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2183 << rex->getSourceRange();
Steve Naroffe701c0a2008-05-12 21:44:38 +00002184 if (!rexT->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002185 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2186 << lex->getSourceRange();
Eli Friedman0e724012008-06-04 19:47:51 +00002187 ImpCastExprToType(lex, Context.VoidTy);
2188 ImpCastExprToType(rex, Context.VoidTy);
2189 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00002190 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00002191 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2192 // the type of the other operand."
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002193 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2194 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssond2652772008-12-01 06:28:23 +00002195 rex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002196 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00002197 return lexT;
2198 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002199 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2200 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssond2652772008-12-01 06:28:23 +00002201 lex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002202 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00002203 return rexT;
2204 }
Chris Lattnerbd57d362008-01-06 22:50:31 +00002205 // Handle the case where both operands are pointers before we handle null
2206 // pointer constants in case both operands are null pointer constants.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002207 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2208 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2209 // get the "pointed to" types
2210 QualType lhptee = LHSPT->getPointeeType();
2211 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002212
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002213 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2214 if (lhptee->isVoidType() &&
Chris Lattnerd805bec2008-04-02 06:59:01 +00002215 rhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00002216 // Figure out necessary qualifiers (C99 6.5.15p6)
2217 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00002218 QualType destType = Context.getPointerType(destPointee);
2219 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2220 ImpCastExprToType(rex, destType); // promote to void*
2221 return destType;
2222 }
Chris Lattnerd805bec2008-04-02 06:59:01 +00002223 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00002224 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00002225 QualType destType = Context.getPointerType(destPointee);
2226 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2227 ImpCastExprToType(rex, destType); // promote to void*
2228 return destType;
2229 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002230
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002231 QualType compositeType = lexT;
2232
2233 // If either type is an Objective-C object type then check
2234 // compatibility according to Objective-C.
2235 if (Context.isObjCObjectPointerType(lexT) ||
2236 Context.isObjCObjectPointerType(rexT)) {
2237 // If both operands are interfaces and either operand can be
2238 // assigned to the other, use that type as the composite
2239 // type. This allows
2240 // xxx ? (A*) a : (B*) b
2241 // where B is a subclass of A.
2242 //
2243 // Additionally, as for assignment, if either type is 'id'
2244 // allow silent coercion. Finally, if the types are
2245 // incompatible then make sure to use 'id' as the composite
2246 // type so the result is acceptable for sending messages to.
2247
2248 // FIXME: This code should not be localized to here. Also this
2249 // should use a compatible check instead of abusing the
2250 // canAssignObjCInterfaces code.
2251 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2252 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2253 if (LHSIface && RHSIface &&
2254 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2255 compositeType = lexT;
2256 } else if (LHSIface && RHSIface &&
Douglas Gregor7ffd0de2008-11-26 06:43:45 +00002257 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002258 compositeType = rexT;
Steve Naroff389bf462009-02-12 17:52:19 +00002259 } else if (Context.isObjCIdStructType(lhptee) ||
2260 Context.isObjCIdStructType(rhptee)) {
2261 // FIXME: This code looks wrong, because isObjCIdStructType checks
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002262 // the struct but getObjCIdType returns the pointer to
2263 // struct. This is horrible and should be fixed.
2264 compositeType = Context.getObjCIdType();
2265 } else {
2266 QualType incompatTy = Context.getObjCIdType();
2267 ImpCastExprToType(lex, incompatTy);
2268 ImpCastExprToType(rex, incompatTy);
2269 return incompatTy;
2270 }
2271 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2272 rhptee.getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002273 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00002274 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002275 // In this situation, we assume void* type. No especially good
2276 // reason, but this is what gcc does, and we do have to pick
2277 // to get a consistent AST.
2278 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbara56f7462008-08-26 00:41:39 +00002279 ImpCastExprToType(lex, incompatTy);
2280 ImpCastExprToType(rex, incompatTy);
2281 return incompatTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002282 }
2283 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002284 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2285 // differently qualified versions of compatible types, the result type is
2286 // a pointer to an appropriately qualified version of the *composite*
2287 // type.
Eli Friedman5835ea22008-05-16 20:37:07 +00002288 // FIXME: Need to calculate the composite type.
Eli Friedmana541d532008-02-10 22:59:36 +00002289 // FIXME: Need to add qualifiers
Eli Friedman5835ea22008-05-16 20:37:07 +00002290 ImpCastExprToType(lex, compositeType);
2291 ImpCastExprToType(rex, compositeType);
2292 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002293 }
2294 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002295 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2296 // evaluates to "struct objc_object *" (and is handled above when comparing
2297 // id with statically typed objects).
2298 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2299 // GCC allows qualified id and any Objective-C type to devolve to
2300 // id. Currently localizing to here until clear this should be
2301 // part of ObjCQualifiedIdTypesAreCompatible.
2302 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2303 (lexT->isObjCQualifiedIdType() &&
2304 Context.isObjCObjectPointerType(rexT)) ||
2305 (rexT->isObjCQualifiedIdType() &&
2306 Context.isObjCObjectPointerType(lexT))) {
2307 // FIXME: This is not the correct composite type. This only
2308 // happens to work because id can more or less be used anywhere,
2309 // however this may change the type of method sends.
2310 // FIXME: gcc adds some type-checking of the arguments and emits
2311 // (confusing) incompatible comparison warnings in some
2312 // cases. Investigate.
2313 QualType compositeType = Context.getObjCIdType();
2314 ImpCastExprToType(lex, compositeType);
2315 ImpCastExprToType(rex, compositeType);
2316 return compositeType;
2317 }
2318 }
2319
Steve Naroff61f40a22008-09-10 19:17:48 +00002320 // Selection between block pointer types is ok as long as they are the same.
2321 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2322 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2323 return lexT;
2324
Chris Lattner70d67a92008-01-06 22:42:25 +00002325 // Otherwise, the operands are not compatible.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002326 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattnerd1625842008-11-24 06:25:27 +00002327 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002328 return QualType();
2329}
2330
Steve Narofff69936d2007-09-16 03:34:24 +00002331/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00002332/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002333Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2334 SourceLocation ColonLoc,
2335 ExprArg Cond, ExprArg LHS,
2336 ExprArg RHS) {
2337 Expr *CondExpr = (Expr *) Cond.get();
2338 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00002339
2340 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2341 // was the condition.
2342 bool isLHSNull = LHSExpr == 0;
2343 if (isLHSNull)
2344 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002345
2346 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00002347 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002348 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002349 return ExprError();
2350
2351 Cond.release();
2352 LHS.release();
2353 RHS.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00002354 return Owned(new (Context) ConditionalOperator(CondExpr,
2355 isLHSNull ? 0 : LHSExpr,
2356 RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00002357}
2358
Reid Spencer5f016e22007-07-11 17:01:13 +00002359
2360// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2361// being closely modeled after the C99 spec:-). The odd characteristic of this
2362// routine is it effectively iqnores the qualifiers on the top level pointee.
2363// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2364// FIXME: add a couple examples in this comment.
Chris Lattner5cf216b2008-01-04 18:04:52 +00002365Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00002366Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2367 QualType lhptee, rhptee;
2368
2369 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002370 lhptee = lhsType->getAsPointerType()->getPointeeType();
2371 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002372
2373 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00002374 lhptee = Context.getCanonicalType(lhptee);
2375 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00002376
Chris Lattner5cf216b2008-01-04 18:04:52 +00002377 AssignConvertType ConvTy = Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00002378
2379 // C99 6.5.16.1p1: This following citation is common to constraints
2380 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2381 // qualifiers of the type *pointed to* by the right;
Chris Lattnerf46699c2008-02-20 20:55:12 +00002382 // FIXME: Handle ASQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00002383 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00002384 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00002385
2386 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2387 // incomplete type and the other is a pointer to a qualified or unqualified
2388 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002389 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00002390 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00002391 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002392
2393 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00002394 assert(rhptee->isFunctionType());
2395 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002396 }
2397
2398 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00002399 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00002400 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002401
2402 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00002403 assert(lhptee->isFunctionType());
2404 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002405 }
Eli Friedman3d815e72008-08-22 00:56:42 +00002406
2407 // Check for ObjC interfaces
2408 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2409 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2410 if (LHSIface && RHSIface &&
2411 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2412 return ConvTy;
2413
2414 // ID acts sort of like void* for ObjC interfaces
Steve Naroff389bf462009-02-12 17:52:19 +00002415 if (LHSIface && Context.isObjCIdStructType(rhptee))
Eli Friedman3d815e72008-08-22 00:56:42 +00002416 return ConvTy;
Steve Naroff389bf462009-02-12 17:52:19 +00002417 if (RHSIface && Context.isObjCIdStructType(lhptee))
Eli Friedman3d815e72008-08-22 00:56:42 +00002418 return ConvTy;
2419
Reid Spencer5f016e22007-07-11 17:01:13 +00002420 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2421 // unqualified versions of compatible types, ...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002422 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2423 rhptee.getUnqualifiedType()))
2424 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00002425 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002426}
2427
Steve Naroff1c7d0672008-09-04 15:10:53 +00002428/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2429/// block pointer types are compatible or whether a block and normal pointer
2430/// are compatible. It is more restrict than comparing two function pointer
2431// types.
2432Sema::AssignConvertType
2433Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2434 QualType rhsType) {
2435 QualType lhptee, rhptee;
2436
2437 // get the "pointed to" type (ignoring qualifiers at the top level)
2438 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2439 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2440
2441 // make sure we operate on the canonical type
2442 lhptee = Context.getCanonicalType(lhptee);
2443 rhptee = Context.getCanonicalType(rhptee);
2444
2445 AssignConvertType ConvTy = Compatible;
2446
2447 // For blocks we enforce that qualifiers are identical.
2448 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2449 ConvTy = CompatiblePointerDiscardsQualifiers;
2450
2451 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2452 return IncompatibleBlockPointer;
2453 return ConvTy;
2454}
2455
Reid Spencer5f016e22007-07-11 17:01:13 +00002456/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2457/// has code to accommodate several GCC extensions when type checking
2458/// pointers. Here are some objectionable examples that GCC considers warnings:
2459///
2460/// int a, *pint;
2461/// short *pshort;
2462/// struct foo *pfoo;
2463///
2464/// pint = pshort; // warning: assignment from incompatible pointer type
2465/// a = pint; // warning: assignment makes integer from pointer without a cast
2466/// pint = a; // warning: assignment makes pointer from integer without a cast
2467/// pint = pfoo; // warning: assignment from incompatible pointer type
2468///
2469/// As a result, the code for dealing with pointers is more complex than the
2470/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00002471///
Chris Lattner5cf216b2008-01-04 18:04:52 +00002472Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00002473Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00002474 // Get canonical types. We're not formatting these types, just comparing
2475 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002476 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2477 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002478
2479 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00002480 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00002481
Douglas Gregor9d293df2008-10-28 00:22:11 +00002482 // If the left-hand side is a reference type, then we are in a
2483 // (rare!) case where we've allowed the use of references in C,
2484 // e.g., as a parameter type in a built-in function. In this case,
2485 // just make sure that the type referenced is compatible with the
2486 // right-hand side type. The caller is responsible for adjusting
2487 // lhsType so that the resulting expression does not have reference
2488 // type.
2489 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2490 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00002491 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002492 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002493 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002494
Chris Lattnereca7be62008-04-07 05:30:13 +00002495 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2496 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002497 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00002498 // Relax integer conversions like we do for pointers below.
2499 if (rhsType->isIntegerType())
2500 return IntToPointer;
2501 if (lhsType->isIntegerType())
2502 return PointerToInt;
Steve Naroff39579072008-10-14 22:18:38 +00002503 return IncompatibleObjCQualifiedId;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002504 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00002505
Nate Begemanbe2341d2008-07-14 18:02:46 +00002506 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002507 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00002508 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2509 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00002510 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002511
Nate Begemanbe2341d2008-07-14 18:02:46 +00002512 // If we are allowing lax vector conversions, and LHS and RHS are both
2513 // vectors, the total size only needs to be the same. This is a bitcast;
2514 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00002515 if (getLangOptions().LaxVectorConversions &&
2516 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002517 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00002518 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00002519 }
2520 return Incompatible;
2521 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002522
Chris Lattnere8b3e962008-01-04 23:32:24 +00002523 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002524 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002525
Chris Lattner78eca282008-04-07 06:49:41 +00002526 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002527 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00002528 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002529
Chris Lattner78eca282008-04-07 06:49:41 +00002530 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002531 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00002532
Steve Naroffb4406862008-09-29 18:10:17 +00002533 if (rhsType->getAsBlockPointerType()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00002534 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002535 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00002536
2537 // Treat block pointers as objects.
2538 if (getLangOptions().ObjC1 &&
2539 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2540 return Compatible;
2541 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002542 return Incompatible;
2543 }
2544
2545 if (isa<BlockPointerType>(lhsType)) {
2546 if (rhsType->isIntegerType())
2547 return IntToPointer;
2548
Steve Naroffb4406862008-09-29 18:10:17 +00002549 // Treat block pointers as objects.
2550 if (getLangOptions().ObjC1 &&
2551 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2552 return Compatible;
2553
Steve Naroff1c7d0672008-09-04 15:10:53 +00002554 if (rhsType->isBlockPointerType())
2555 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2556
2557 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2558 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002559 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002560 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00002561 return Incompatible;
2562 }
2563
Chris Lattner78eca282008-04-07 06:49:41 +00002564 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002565 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002566 if (lhsType == Context.BoolTy)
2567 return Compatible;
2568
2569 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00002570 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00002571
Chris Lattner78eca282008-04-07 06:49:41 +00002572 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002573 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00002574
2575 if (isa<BlockPointerType>(lhsType) &&
2576 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002577 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002578 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002579 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002580
Chris Lattnerfc144e22008-01-04 23:18:45 +00002581 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00002582 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002583 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00002584 }
2585 return Incompatible;
2586}
2587
Chris Lattner5cf216b2008-01-04 18:04:52 +00002588Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002589Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002590 if (getLangOptions().CPlusPlus) {
2591 if (!lhsType->isRecordType()) {
2592 // C++ 5.17p3: If the left operand is not of class type, the
2593 // expression is implicitly converted (C++ 4) to the
2594 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00002595 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2596 "assigning"))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002597 return Incompatible;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002598 else
Douglas Gregor98cd5992008-10-21 23:43:52 +00002599 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002600 }
2601
2602 // FIXME: Currently, we fall through and treat C++ classes like C
2603 // structures.
2604 }
2605
Steve Naroff529a4ad2007-11-27 17:58:44 +00002606 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2607 // a null pointer constant.
Steve Naroff39218df2008-09-04 16:56:14 +00002608 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2609 lhsType->isBlockPointerType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00002610 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002611 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00002612 return Compatible;
2613 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002614
2615 // We don't allow conversion of non-null-pointer constants to integers.
2616 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2617 return IntToBlockPointer;
2618
Chris Lattner943140e2007-10-16 02:55:40 +00002619 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00002620 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00002621 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00002622 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00002623 //
Douglas Gregor9d293df2008-10-28 00:22:11 +00002624 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00002625 if (!lhsType->isReferenceType())
2626 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00002627
Chris Lattner5cf216b2008-01-04 18:04:52 +00002628 Sema::AssignConvertType result =
2629 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Narofff1120de2007-08-24 22:33:52 +00002630
2631 // C99 6.5.16.1p2: The value of the right operand is converted to the
2632 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00002633 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2634 // so that we can use references in built-in functions even in C.
2635 // The getNonReferenceType() call makes sure that the resulting expression
2636 // does not have reference type.
Steve Narofff1120de2007-08-24 22:33:52 +00002637 if (rExpr->getType() != lhsType)
Douglas Gregor9d293df2008-10-28 00:22:11 +00002638 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Narofff1120de2007-08-24 22:33:52 +00002639 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00002640}
2641
Chris Lattner5cf216b2008-01-04 18:04:52 +00002642Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002643Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2644 return CheckAssignmentConstraints(lhsType, rhsType);
2645}
2646
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002647QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002648 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00002649 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002650 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00002651 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002652}
2653
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002654inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00002655 Expr *&rex) {
Nate Begeman1330b0e2008-04-04 01:30:25 +00002656 // For conversion purposes, we ignore any qualifiers.
2657 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002658 QualType lhsType =
2659 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2660 QualType rhsType =
2661 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002662
Nate Begemanbe2341d2008-07-14 18:02:46 +00002663 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00002664 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00002665 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00002666
Nate Begemanbe2341d2008-07-14 18:02:46 +00002667 // Handle the case of a vector & extvector type of the same size and element
2668 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00002669 if (getLangOptions().LaxVectorConversions) {
2670 // FIXME: Should we warn here?
2671 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002672 if (const VectorType *RV = rhsType->getAsVectorType())
2673 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00002674 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002675 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00002676 }
2677 }
2678 }
2679
Nate Begemanbe2341d2008-07-14 18:02:46 +00002680 // If the lhs is an extended vector and the rhs is a scalar of the same type
2681 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00002682 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002683 QualType eltType = V->getElementType();
2684
2685 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2686 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2687 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002688 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00002689 return lhsType;
2690 }
2691 }
2692
Nate Begemanbe2341d2008-07-14 18:02:46 +00002693 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00002694 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00002695 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002696 QualType eltType = V->getElementType();
2697
2698 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2699 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2700 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002701 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00002702 return rhsType;
2703 }
2704 }
2705
Reid Spencer5f016e22007-07-11 17:01:13 +00002706 // You cannot convert between vector values of different size.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002707 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00002708 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002709 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002710 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00002711}
2712
Reid Spencer5f016e22007-07-11 17:01:13 +00002713inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002714 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002715{
Daniel Dunbar69d1d002009-01-05 22:42:10 +00002716 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002717 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00002718
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002719 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002720
Steve Naroffa4332e22007-07-17 00:58:39 +00002721 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002722 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002723 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002724}
2725
2726inline QualType Sema::CheckRemainderOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002727 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002728{
Daniel Dunbar523aa602009-01-05 22:55:36 +00002729 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2730 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2731 return CheckVectorOperands(Loc, lex, rex);
2732 return InvalidOperands(Loc, lex, rex);
2733 }
Steve Naroff90045e82007-07-13 23:32:42 +00002734
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002735 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002736
Steve Naroffa4332e22007-07-17 00:58:39 +00002737 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002738 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002739 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002740}
2741
2742inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002743 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002744{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002745 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002746 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00002747
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002748 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand72d16e2008-05-18 18:08:51 +00002749
Reid Spencer5f016e22007-07-11 17:01:13 +00002750 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00002751 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002752 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002753
Eli Friedmand72d16e2008-05-18 18:08:51 +00002754 // Put any potential pointer into PExp
2755 Expr* PExp = lex, *IExp = rex;
2756 if (IExp->getType()->isPointerType())
2757 std::swap(PExp, IExp);
2758
2759 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2760 if (IExp->getType()->isIntegerType()) {
2761 // Check for arithmetic on pointers to incomplete types
2762 if (!PTy->getPointeeType()->isObjectType()) {
2763 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00002764 if (getLangOptions().CPlusPlus) {
2765 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2766 << lex->getSourceRange() << rex->getSourceRange();
2767 return QualType();
2768 }
2769
2770 // GNU extension: arithmetic on pointer to void
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002771 Diag(Loc, diag::ext_gnu_void_ptr)
2772 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002773 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00002774 if (getLangOptions().CPlusPlus) {
2775 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2776 << lex->getType() << lex->getSourceRange();
2777 return QualType();
2778 }
2779
2780 // GNU extension: arithmetic on pointer to function
2781 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00002782 << lex->getType() << lex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002783 } else {
2784 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2785 diag::err_typecheck_arithmetic_incomplete_type,
2786 lex->getSourceRange(), SourceRange(),
2787 lex->getType());
2788 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00002789 }
2790 }
2791 return PExp->getType();
2792 }
2793 }
2794
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002795 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002796}
2797
Chris Lattnereca7be62008-04-07 05:30:13 +00002798// C99 6.5.6
2799QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002800 SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00002801 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002802 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002803
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002804 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002805
Chris Lattner6e4ab612007-12-09 21:53:25 +00002806 // Enforce type constraints: C99 6.5.6p3.
2807
2808 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00002809 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002810 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00002811
2812 // Either ptr - int or ptr - ptr.
2813 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00002814 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman8e54ad02008-02-08 01:19:44 +00002815
Chris Lattner6e4ab612007-12-09 21:53:25 +00002816 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff2565eef2008-01-29 18:58:14 +00002817 if (!lpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002818 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002819 if (lpointee->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002820 Diag(Loc, diag::ext_gnu_void_ptr)
2821 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorc983b862009-01-23 00:36:41 +00002822 } else if (lpointee->isFunctionType()) {
2823 if (getLangOptions().CPlusPlus) {
2824 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2825 << lex->getType() << lex->getSourceRange();
2826 return QualType();
2827 }
2828
2829 // GNU extension: arithmetic on pointer to function
2830 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2831 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002832 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002833 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00002834 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002835 return QualType();
2836 }
2837 }
2838
2839 // The result type of a pointer-int computation is the pointer type.
2840 if (rex->getType()->isIntegerType())
2841 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00002842
Chris Lattner6e4ab612007-12-09 21:53:25 +00002843 // Handle pointer-pointer subtractions.
2844 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00002845 QualType rpointee = RHSPTy->getPointeeType();
2846
Chris Lattner6e4ab612007-12-09 21:53:25 +00002847 // RHS must be an object type, unless void (GNU).
Steve Naroff2565eef2008-01-29 18:58:14 +00002848 if (!rpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002849 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002850 if (rpointee->isVoidType()) {
2851 if (!lpointee->isVoidType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002852 Diag(Loc, diag::ext_gnu_void_ptr)
2853 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor08048882009-01-23 19:03:35 +00002854 } else if (rpointee->isFunctionType()) {
2855 if (getLangOptions().CPlusPlus) {
2856 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2857 << rex->getType() << rex->getSourceRange();
2858 return QualType();
2859 }
2860
2861 // GNU extension: arithmetic on pointer to function
2862 if (!lpointee->isFunctionType())
2863 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2864 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002865 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002866 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00002867 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002868 return QualType();
2869 }
2870 }
2871
2872 // Pointee types must be compatible.
Eli Friedmanf1c7b482008-09-02 05:09:35 +00002873 if (!Context.typesAreCompatible(
2874 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2875 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002876 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattnerd1625842008-11-24 06:25:27 +00002877 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002878 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002879 return QualType();
2880 }
2881
2882 return Context.getPointerDiffType();
2883 }
2884 }
2885
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002886 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002887}
2888
Chris Lattnereca7be62008-04-07 05:30:13 +00002889// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002890QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00002891 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00002892 // C99 6.5.7p2: Each of the operands shall have integer type.
2893 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002894 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002895
Chris Lattnerca5eede2007-12-12 05:47:28 +00002896 // Shifts don't perform usual arithmetic conversions, they just do integer
2897 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00002898 if (!isCompAssign)
2899 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00002900 UsualUnaryConversions(rex);
2901
2902 // "The type of the result is that of the promoted left operand."
2903 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002904}
2905
Chris Lattnereca7be62008-04-07 05:30:13 +00002906// C99 6.5.8
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002907QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00002908 bool isRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002909 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002910 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002911
Chris Lattnera5937dd2007-08-26 01:18:55 +00002912 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00002913 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2914 UsualArithmeticConversions(lex, rex);
2915 else {
2916 UsualUnaryConversions(lex);
2917 UsualUnaryConversions(rex);
2918 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002919 QualType lType = lex->getType();
2920 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002921
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002922 // For non-floating point types, check for self-comparisons of the form
2923 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2924 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002925 if (!lType->isFloatingType()) {
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00002926 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2927 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002928 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002929 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002930 }
2931
Douglas Gregor447b69e2008-11-19 03:25:36 +00002932 // The result of comparisons is 'bool' in C++, 'int' in C.
2933 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2934
Chris Lattnera5937dd2007-08-26 01:18:55 +00002935 if (isRelational) {
2936 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00002937 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00002938 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002939 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002940 if (lType->isFloatingType()) {
2941 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002942 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00002943 }
2944
Chris Lattnera5937dd2007-08-26 01:18:55 +00002945 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00002946 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00002947 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002948
Chris Lattnerd28f8152007-08-26 01:10:14 +00002949 bool LHSIsNull = lex->isNullPointerConstant(Context);
2950 bool RHSIsNull = rex->isNullPointerConstant(Context);
2951
Chris Lattnera5937dd2007-08-26 01:18:55 +00002952 // All of the following pointer related warnings are GCC extensions, except
2953 // when handling null pointer constants. One day, we can consider making them
2954 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00002955 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002956 QualType LCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002957 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00002958 QualType RCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002959 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman8e54ad02008-02-08 01:19:44 +00002960
Steve Naroff66296cb2007-11-13 14:57:38 +00002961 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002962 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2963 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman3d815e72008-08-22 00:56:42 +00002964 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff389bf462009-02-12 17:52:19 +00002965 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002966 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00002967 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002968 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00002969 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002970 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002971 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002972 // Handle block pointer types.
2973 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2974 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2975 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2976
2977 if (!LHSIsNull && !RHSIsNull &&
2978 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002979 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00002980 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00002981 }
2982 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002983 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002984 }
Steve Naroff59f53942008-09-28 01:11:11 +00002985 // Allow block pointers to be compared with null pointer constants.
2986 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2987 (lType->isPointerType() && rType->isBlockPointerType())) {
2988 if (!LHSIsNull && !RHSIsNull) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002989 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00002990 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00002991 }
2992 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002993 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00002994 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002995
Steve Naroff20373222008-06-03 14:04:54 +00002996 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00002997 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroffa8069f12008-11-17 19:49:16 +00002998 const PointerType *LPT = lType->getAsPointerType();
2999 const PointerType *RPT = rType->getAsPointerType();
3000 bool LPtrToVoid = LPT ?
3001 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
3002 bool RPtrToVoid = RPT ?
3003 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
3004
3005 if (!LPtrToVoid && !RPtrToVoid &&
3006 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003007 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00003008 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00003009 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00003010 return ResultTy;
Steve Naroffa5ad8632008-10-27 10:33:19 +00003011 }
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00003012 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00003013 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00003014 }
Steve Naroff20373222008-06-03 14:04:54 +00003015 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3016 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00003017 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00003018 } else {
3019 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003020 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003021 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00003022 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00003023 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00003024 }
Steve Naroff20373222008-06-03 14:04:54 +00003025 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00003026 }
Steve Naroff20373222008-06-03 14:04:54 +00003027 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
3028 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00003029 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003030 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003031 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00003032 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003033 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00003034 }
Steve Naroff20373222008-06-03 14:04:54 +00003035 if (lType->isIntegerType() &&
3036 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00003037 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003038 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003039 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00003040 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003041 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003042 }
Steve Naroff39218df2008-09-04 16:56:14 +00003043 // Handle block pointers.
3044 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3045 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003046 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003047 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00003048 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003049 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00003050 }
3051 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3052 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003053 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003054 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00003055 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003056 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00003057 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003058 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003059}
3060
Nate Begemanbe2341d2008-07-14 18:02:46 +00003061/// CheckVectorCompareOperands - vector comparisons are a clang extension that
3062/// operates on extended vector types. Instead of producing an IntTy result,
3063/// like a scalar comparison, a vector comparison produces a vector of integer
3064/// types.
3065QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003066 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00003067 bool isRelational) {
3068 // Check to make sure we're operating on vectors of the same type and width,
3069 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003070 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00003071 if (vType.isNull())
3072 return vType;
3073
3074 QualType lType = lex->getType();
3075 QualType rType = rex->getType();
3076
3077 // For non-floating point types, check for self-comparisons of the form
3078 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3079 // often indicate logic errors in the program.
3080 if (!lType->isFloatingType()) {
3081 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3082 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3083 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003084 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00003085 }
3086
3087 // Check for comparisons of floating point operands using != and ==.
3088 if (!isRelational && lType->isFloatingType()) {
3089 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003090 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00003091 }
3092
3093 // Return the type for the comparison, which is the same as vector type for
3094 // integer vectors, or an integer type of identical size and number of
3095 // elements for floating point vectors.
3096 if (lType->isIntegerType())
3097 return lType;
3098
3099 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanbe2341d2008-07-14 18:02:46 +00003100 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00003101 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00003102 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begeman59b5da62009-01-18 03:20:47 +00003103 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3104 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3105
3106 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3107 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00003108 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3109}
3110
Reid Spencer5f016e22007-07-11 17:01:13 +00003111inline QualType Sema::CheckBitwiseOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003112 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00003113{
Steve Naroff3e5e5562007-07-16 22:23:01 +00003114 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003115 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00003116
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003117 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00003118
Steve Naroffa4332e22007-07-17 00:58:39 +00003119 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003120 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003121 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003122}
3123
3124inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003125 Expr *&lex, Expr *&rex, SourceLocation Loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00003126{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003127 UsualUnaryConversions(lex);
3128 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003129
Eli Friedman5773a6c2008-05-13 20:16:47 +00003130 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00003131 return Context.IntTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003132 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003133}
3134
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00003135/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3136/// is a read-only property; return true if so. A readonly property expression
3137/// depends on various declarations and thus must be treated specially.
3138///
3139static bool IsReadonlyProperty(Expr *E, Sema &S)
3140{
3141 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3142 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3143 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3144 QualType BaseType = PropExpr->getBase()->getType();
3145 if (const PointerType *PTy = BaseType->getAsPointerType())
3146 if (const ObjCInterfaceType *IFTy =
3147 PTy->getPointeeType()->getAsObjCInterfaceType())
3148 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3149 if (S.isPropertyReadonly(PDecl, IFace))
3150 return true;
3151 }
3152 }
3153 return false;
3154}
3155
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003156/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3157/// emit an error and return true. If so, return false.
3158static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00003159 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3160 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3161 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003162 if (IsLV == Expr::MLV_Valid)
3163 return false;
3164
3165 unsigned Diag = 0;
3166 bool NeedType = false;
3167 switch (IsLV) { // C99 6.5.16p2
3168 default: assert(0 && "Unknown result from isModifiableLvalue!");
3169 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003170 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003171 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3172 NeedType = true;
3173 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003174 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003175 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3176 NeedType = true;
3177 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00003178 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003179 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3180 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003181 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003182 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3183 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003184 case Expr::MLV_IncompleteType:
3185 case Expr::MLV_IncompleteVoidType:
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003186 return S.DiagnoseIncompleteType(Loc, E->getType(),
3187 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3188 E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00003189 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003190 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3191 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00003192 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003193 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3194 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00003195 case Expr::MLV_ReadonlyProperty:
3196 Diag = diag::error_readonly_property_assignment;
3197 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00003198 case Expr::MLV_NoSetterProperty:
3199 Diag = diag::error_nosetter_property_assignment;
3200 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003201 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00003202
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003203 if (NeedType)
Chris Lattnerd1625842008-11-24 06:25:27 +00003204 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003205 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003206 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003207 return true;
3208}
3209
3210
3211
3212// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003213QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3214 SourceLocation Loc,
3215 QualType CompoundType) {
3216 // Verify that LHS is a modifiable lvalue, and emit error if not.
3217 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003218 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003219
3220 QualType LHSType = LHS->getType();
3221 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003222
Chris Lattner5cf216b2008-01-04 18:04:52 +00003223 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003224 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00003225 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003226 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003227 // Special case of NSObject attributes on c-style pointer types.
3228 if (ConvTy == IncompatiblePointer &&
3229 ((Context.isObjCNSObjectType(LHSType) &&
3230 Context.isObjCObjectPointerType(RHSType)) ||
3231 (Context.isObjCNSObjectType(RHSType) &&
3232 Context.isObjCObjectPointerType(LHSType))))
3233 ConvTy = Compatible;
3234
Chris Lattner2c156472008-08-21 18:04:13 +00003235 // If the RHS is a unary plus or minus, check to see if they = and + are
3236 // right next to each other. If so, the user may have typo'd "x =+ 4"
3237 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003238 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00003239 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3240 RHSCheck = ICE->getSubExpr();
3241 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3242 if ((UO->getOpcode() == UnaryOperator::Plus ||
3243 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003244 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00003245 // Only if the two operators are exactly adjacent.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003246 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003247 Diag(Loc, diag::warn_not_compound_assign)
3248 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3249 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner2c156472008-08-21 18:04:13 +00003250 }
3251 } else {
3252 // Compound assignment "x += y"
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003253 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00003254 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00003255
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003256 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3257 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00003258 return QualType();
3259
Reid Spencer5f016e22007-07-11 17:01:13 +00003260 // C99 6.5.16p3: The type of an assignment expression is the type of the
3261 // left operand unless the left operand has qualified type, in which case
3262 // it is the unqualified version of the type of the left operand.
3263 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3264 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003265 // C++ 5.17p1: the type of the assignment expression is that of its left
3266 // oprdu.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003267 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003268}
3269
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003270// C99 6.5.17
3271QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3272 // FIXME: what is required for LHS?
Chris Lattner53fcaa92008-07-25 20:54:07 +00003273
3274 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003275 DefaultFunctionArrayConversion(RHS);
3276 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003277}
3278
Steve Naroff49b45262007-07-13 16:58:59 +00003279/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3280/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003281QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3282 bool isInc) {
Chris Lattner3528d352008-11-21 07:05:48 +00003283 QualType ResType = Op->getType();
3284 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00003285
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003286 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3287 // Decrement of bool is not allowed.
3288 if (!isInc) {
3289 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3290 return QualType();
3291 }
3292 // Increment of bool sets it to true, but is deprecated.
3293 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3294 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00003295 // OK!
3296 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3297 // C99 6.5.2.4p2, 6.5.6p2
3298 if (PT->getPointeeType()->isObjectType()) {
3299 // Pointer to object is ok!
3300 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00003301 if (getLangOptions().CPlusPlus) {
3302 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3303 << Op->getSourceRange();
3304 return QualType();
3305 }
3306
3307 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00003308 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003309 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00003310 if (getLangOptions().CPlusPlus) {
3311 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3312 << Op->getType() << Op->getSourceRange();
3313 return QualType();
3314 }
3315
3316 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00003317 << ResType << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003318 return QualType();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003319 } else {
3320 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3321 diag::err_typecheck_arithmetic_incomplete_type,
3322 Op->getSourceRange(), SourceRange(),
3323 ResType);
3324 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003325 }
Chris Lattner3528d352008-11-21 07:05:48 +00003326 } else if (ResType->isComplexType()) {
3327 // C99 does not support ++/-- on complex types, we allow as an extension.
3328 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00003329 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00003330 } else {
3331 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00003332 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00003333 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003334 }
Steve Naroffdd10e022007-08-23 21:37:33 +00003335 // At this point, we know we have a real, complex or pointer type.
3336 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00003337 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00003338 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00003339 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00003340}
3341
Anders Carlsson369dee42008-02-01 07:15:58 +00003342/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00003343/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003344/// where the declaration is needed for type checking. We only need to
3345/// handle cases when the expression references a function designator
3346/// or is an lvalue. Here are some examples:
3347/// - &(x) => x
3348/// - &*****f => f for f a function designator.
3349/// - &s.xx => s
3350/// - &s.zz[1].yy -> s, if zz is an array
3351/// - *(x + 1) -> x, if x is an array
3352/// - &"123"[2] -> 0
3353/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003354static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00003355 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003356 case Stmt::DeclRefExprClass:
Douglas Gregor1a49af92009-01-06 05:10:23 +00003357 case Stmt::QualifiedDeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00003358 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003359 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00003360 // Fields cannot be declared with a 'register' storage class.
3361 // &X->f is always ok, even if X is declared register.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003362 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00003363 return 0;
Chris Lattnerf0467b32008-04-02 04:24:33 +00003364 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00003365 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003366 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson369dee42008-02-01 07:15:58 +00003367
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003368 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar48d04ae2008-10-21 21:22:32 +00003369 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlssonf2a4b842008-02-01 16:01:31 +00003370 if (!VD || VD->getType()->isPointerType())
Anders Carlsson369dee42008-02-01 07:15:58 +00003371 return 0;
3372 else
3373 return VD;
3374 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003375 case Stmt::UnaryOperatorClass: {
3376 UnaryOperator *UO = cast<UnaryOperator>(E);
3377
3378 switch(UO->getOpcode()) {
3379 case UnaryOperator::Deref: {
3380 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003381 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3382 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3383 if (!VD || VD->getType()->isPointerType())
3384 return 0;
3385 return VD;
3386 }
3387 return 0;
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003388 }
3389 case UnaryOperator::Real:
3390 case UnaryOperator::Imag:
3391 case UnaryOperator::Extension:
3392 return getPrimaryDecl(UO->getSubExpr());
3393 default:
3394 return 0;
3395 }
3396 }
3397 case Stmt::BinaryOperatorClass: {
3398 BinaryOperator *BO = cast<BinaryOperator>(E);
3399
3400 // Handle cases involving pointer arithmetic. The result of an
3401 // Assign or AddAssign is not an lvalue so they can be ignored.
3402
3403 // (x + n) or (n + x) => x
3404 if (BO->getOpcode() == BinaryOperator::Add) {
3405 if (BO->getLHS()->getType()->isPointerType()) {
3406 return getPrimaryDecl(BO->getLHS());
3407 } else if (BO->getRHS()->getType()->isPointerType()) {
3408 return getPrimaryDecl(BO->getRHS());
3409 }
3410 }
3411
3412 return 0;
3413 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003414 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00003415 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00003416 case Stmt::ImplicitCastExprClass:
3417 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003418 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00003419 default:
3420 return 0;
3421 }
3422}
3423
3424/// CheckAddressOfOperand - The operand of & must be either a function
3425/// designator or an lvalue designating an object. If it is an lvalue, the
3426/// object cannot be declared with storage class register or be a bit field.
3427/// Note: The usual conversions are *not* applied to the operand of the &
3428/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor904eed32008-11-10 20:40:00 +00003429/// In C++, the operand might be an overloaded function name, in which case
3430/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00003431QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregor9103bb22008-12-17 22:52:20 +00003432 if (op->isTypeDependent())
3433 return Context.DependentTy;
3434
Steve Naroff08f19672008-01-13 17:10:08 +00003435 if (getLangOptions().C99) {
3436 // Implement C99-only parts of addressof rules.
3437 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3438 if (uOp->getOpcode() == UnaryOperator::Deref)
3439 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3440 // (assuming the deref expression is valid).
3441 return uOp->getSubExpr()->getType();
3442 }
3443 // Technically, there should be a check for array subscript
3444 // expressions here, but the result of one is always an lvalue anyway.
3445 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003446 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00003447 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00003448
Reid Spencer5f016e22007-07-11 17:01:13 +00003449 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00003450 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3451 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003452 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3453 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003454 return QualType();
3455 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00003456 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor86f19402008-12-20 23:49:58 +00003457 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3458 if (Field->isBitField()) {
3459 Diag(OpLoc, diag::err_typecheck_address_of)
3460 << "bit-field" << op->getSourceRange();
3461 return QualType();
3462 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00003463 }
3464 // Check for Apple extension for accessing vector components.
3465 } else if (isa<ArraySubscriptExpr>(op) &&
3466 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003467 Diag(OpLoc, diag::err_typecheck_address_of)
3468 << "vector" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00003469 return QualType();
3470 } else if (dcl) { // C99 6.5.3.2p1
Reid Spencer5f016e22007-07-11 17:01:13 +00003471 // We have an lvalue with a decl. Make sure the decl is not declared
3472 // with the register storage-class specifier.
3473 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3474 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003475 Diag(OpLoc, diag::err_typecheck_address_of)
3476 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003477 return QualType();
3478 }
Douglas Gregor29882052008-12-10 21:26:49 +00003479 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00003480 return Context.OverloadTy;
Douglas Gregor29882052008-12-10 21:26:49 +00003481 } else if (isa<FieldDecl>(dcl)) {
3482 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00003483 // Could be a pointer to member, though, if there is an explicit
3484 // scope qualifier for the class.
3485 if (isa<QualifiedDeclRefExpr>(op)) {
3486 DeclContext *Ctx = dcl->getDeclContext();
3487 if (Ctx && Ctx->isRecord())
3488 return Context.getMemberPointerType(op->getType(),
3489 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3490 }
Nuno Lopes6fea8d22008-12-16 22:58:26 +00003491 } else if (isa<FunctionDecl>(dcl)) {
3492 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00003493 // As above.
3494 if (isa<QualifiedDeclRefExpr>(op)) {
3495 DeclContext *Ctx = dcl->getDeclContext();
3496 if (Ctx && Ctx->isRecord())
3497 return Context.getMemberPointerType(op->getType(),
3498 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3499 }
Douglas Gregor29882052008-12-10 21:26:49 +00003500 }
Nuno Lopes6fea8d22008-12-16 22:58:26 +00003501 else
Reid Spencer5f016e22007-07-11 17:01:13 +00003502 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00003503 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00003504
Reid Spencer5f016e22007-07-11 17:01:13 +00003505 // If the operand has type "type", the result has type "pointer to type".
3506 return Context.getPointerType(op->getType());
3507}
3508
Chris Lattner22caddc2008-11-23 09:13:29 +00003509QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3510 UsualUnaryConversions(Op);
3511 QualType Ty = Op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003512
Chris Lattner22caddc2008-11-23 09:13:29 +00003513 // Note that per both C89 and C99, this is always legal, even if ptype is an
3514 // incomplete type or void. It would be possible to warn about dereferencing
3515 // a void pointer, but it's completely well-defined, and such a warning is
3516 // unlikely to catch any mistakes.
3517 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff08f19672008-01-13 17:10:08 +00003518 return PT->getPointeeType();
Chris Lattner22caddc2008-11-23 09:13:29 +00003519
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003520 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00003521 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003522 return QualType();
3523}
3524
3525static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3526 tok::TokenKind Kind) {
3527 BinaryOperator::Opcode Opc;
3528 switch (Kind) {
3529 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00003530 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3531 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003532 case tok::star: Opc = BinaryOperator::Mul; break;
3533 case tok::slash: Opc = BinaryOperator::Div; break;
3534 case tok::percent: Opc = BinaryOperator::Rem; break;
3535 case tok::plus: Opc = BinaryOperator::Add; break;
3536 case tok::minus: Opc = BinaryOperator::Sub; break;
3537 case tok::lessless: Opc = BinaryOperator::Shl; break;
3538 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3539 case tok::lessequal: Opc = BinaryOperator::LE; break;
3540 case tok::less: Opc = BinaryOperator::LT; break;
3541 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3542 case tok::greater: Opc = BinaryOperator::GT; break;
3543 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3544 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3545 case tok::amp: Opc = BinaryOperator::And; break;
3546 case tok::caret: Opc = BinaryOperator::Xor; break;
3547 case tok::pipe: Opc = BinaryOperator::Or; break;
3548 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3549 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3550 case tok::equal: Opc = BinaryOperator::Assign; break;
3551 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3552 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3553 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3554 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3555 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3556 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3557 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3558 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3559 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3560 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3561 case tok::comma: Opc = BinaryOperator::Comma; break;
3562 }
3563 return Opc;
3564}
3565
3566static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3567 tok::TokenKind Kind) {
3568 UnaryOperator::Opcode Opc;
3569 switch (Kind) {
3570 default: assert(0 && "Unknown unary op!");
3571 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3572 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3573 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3574 case tok::star: Opc = UnaryOperator::Deref; break;
3575 case tok::plus: Opc = UnaryOperator::Plus; break;
3576 case tok::minus: Opc = UnaryOperator::Minus; break;
3577 case tok::tilde: Opc = UnaryOperator::Not; break;
3578 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003579 case tok::kw___real: Opc = UnaryOperator::Real; break;
3580 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3581 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3582 }
3583 return Opc;
3584}
3585
Douglas Gregoreaebc752008-11-06 23:29:22 +00003586/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3587/// operator @p Opc at location @c TokLoc. This routine only supports
3588/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003589Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3590 unsigned Op,
3591 Expr *lhs, Expr *rhs) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00003592 QualType ResultTy; // Result type of the binary operator.
3593 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3594 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3595
3596 switch (Opc) {
3597 default:
3598 assert(0 && "Unknown binary expr!");
3599 case BinaryOperator::Assign:
3600 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3601 break;
Sebastian Redl22460502009-02-07 00:15:38 +00003602 case BinaryOperator::PtrMemD:
3603 case BinaryOperator::PtrMemI:
3604 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3605 Opc == BinaryOperator::PtrMemI);
3606 break;
3607 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00003608 case BinaryOperator::Div:
3609 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3610 break;
3611 case BinaryOperator::Rem:
3612 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3613 break;
3614 case BinaryOperator::Add:
3615 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3616 break;
3617 case BinaryOperator::Sub:
3618 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3619 break;
Sebastian Redl22460502009-02-07 00:15:38 +00003620 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00003621 case BinaryOperator::Shr:
3622 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3623 break;
3624 case BinaryOperator::LE:
3625 case BinaryOperator::LT:
3626 case BinaryOperator::GE:
3627 case BinaryOperator::GT:
3628 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3629 break;
3630 case BinaryOperator::EQ:
3631 case BinaryOperator::NE:
3632 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3633 break;
3634 case BinaryOperator::And:
3635 case BinaryOperator::Xor:
3636 case BinaryOperator::Or:
3637 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3638 break;
3639 case BinaryOperator::LAnd:
3640 case BinaryOperator::LOr:
3641 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3642 break;
3643 case BinaryOperator::MulAssign:
3644 case BinaryOperator::DivAssign:
3645 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3646 if (!CompTy.isNull())
3647 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3648 break;
3649 case BinaryOperator::RemAssign:
3650 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3651 if (!CompTy.isNull())
3652 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3653 break;
3654 case BinaryOperator::AddAssign:
3655 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3656 if (!CompTy.isNull())
3657 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3658 break;
3659 case BinaryOperator::SubAssign:
3660 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3661 if (!CompTy.isNull())
3662 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3663 break;
3664 case BinaryOperator::ShlAssign:
3665 case BinaryOperator::ShrAssign:
3666 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3667 if (!CompTy.isNull())
3668 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3669 break;
3670 case BinaryOperator::AndAssign:
3671 case BinaryOperator::XorAssign:
3672 case BinaryOperator::OrAssign:
3673 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3674 if (!CompTy.isNull())
3675 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3676 break;
3677 case BinaryOperator::Comma:
3678 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3679 break;
3680 }
3681 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003682 return ExprError();
Steve Naroff6ece14c2009-01-21 00:14:39 +00003683 if (CompTy.isNull())
3684 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3685 else
3686 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Steve Naroff9e0b6002009-01-20 21:06:31 +00003687 CompTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00003688}
3689
Reid Spencer5f016e22007-07-11 17:01:13 +00003690// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003691Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3692 tok::TokenKind Kind,
3693 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003694 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003695 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Reid Spencer5f016e22007-07-11 17:01:13 +00003696
Steve Narofff69936d2007-09-16 03:34:24 +00003697 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3698 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00003699
Douglas Gregor898574e2008-12-05 23:32:09 +00003700 // If either expression is type-dependent, just build the AST.
3701 // FIXME: We'll need to perform some caching of the result of name
3702 // lookup for operator+.
3703 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff6ece14c2009-01-21 00:14:39 +00003704 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3705 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003706 Context.DependentTy,
3707 Context.DependentTy, TokLoc));
Steve Naroff6ece14c2009-01-21 00:14:39 +00003708 else
Sebastian Redl22460502009-02-07 00:15:38 +00003709 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc,
3710 Context.DependentTy, TokLoc));
Douglas Gregor898574e2008-12-05 23:32:09 +00003711 }
3712
Sebastian Redl22460502009-02-07 00:15:38 +00003713 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD &&
Douglas Gregoreaebc752008-11-06 23:29:22 +00003714 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3715 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003716 // If this is one of the assignment operators, we only perform
3717 // overload resolution if the left-hand side is a class or
3718 // enumeration type (C++ [expr.ass]p3).
3719 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3720 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3721 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3722 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003723
Douglas Gregoreaebc752008-11-06 23:29:22 +00003724 // Determine which overloaded operator we're dealing with.
3725 static const OverloadedOperatorKind OverOps[] = {
Sebastian Redl22460502009-02-07 00:15:38 +00003726 // Overloading .* is not possible.
3727 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar,
Douglas Gregoreaebc752008-11-06 23:29:22 +00003728 OO_Star, OO_Slash, OO_Percent,
3729 OO_Plus, OO_Minus,
3730 OO_LessLess, OO_GreaterGreater,
3731 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3732 OO_EqualEqual, OO_ExclaimEqual,
3733 OO_Amp,
3734 OO_Caret,
3735 OO_Pipe,
3736 OO_AmpAmp,
3737 OO_PipePipe,
3738 OO_Equal, OO_StarEqual,
3739 OO_SlashEqual, OO_PercentEqual,
3740 OO_PlusEqual, OO_MinusEqual,
3741 OO_LessLessEqual, OO_GreaterGreaterEqual,
3742 OO_AmpEqual, OO_CaretEqual,
3743 OO_PipeEqual,
3744 OO_Comma
3745 };
3746 OverloadedOperatorKind OverOp = OverOps[Opc];
3747
Douglas Gregor96176b32008-11-18 23:14:02 +00003748 // Add the appropriate overloaded operators (C++ [over.match.oper])
3749 // to the candidate set.
Douglas Gregor74253732008-11-19 15:42:04 +00003750 OverloadCandidateSet CandidateSet;
Douglas Gregoreaebc752008-11-06 23:29:22 +00003751 Expr *Args[2] = { lhs, rhs };
Douglas Gregorf680a0f2009-02-04 16:44:47 +00003752 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3753 return ExprError();
Douglas Gregoreaebc752008-11-06 23:29:22 +00003754
3755 // Perform overload resolution.
3756 OverloadCandidateSet::iterator Best;
3757 switch (BestViableFunction(CandidateSet, Best)) {
3758 case OR_Success: {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003759 // We found a built-in operator or an overloaded operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003760 FunctionDecl *FnDecl = Best->Function;
3761
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003762 if (FnDecl) {
3763 // We matched an overloaded operator. Build a call to that
3764 // operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003765
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003766 // Convert the arguments.
Douglas Gregor96176b32008-11-18 23:14:02 +00003767 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3768 if (PerformObjectArgumentInitialization(lhs, Method) ||
3769 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3770 "passing"))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003771 return ExprError();
Douglas Gregor96176b32008-11-18 23:14:02 +00003772 } else {
3773 // Convert the arguments.
3774 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3775 "passing") ||
3776 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3777 "passing"))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003778 return ExprError();
Douglas Gregor96176b32008-11-18 23:14:02 +00003779 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003780
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003781 // Determine the result type
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003782 QualType ResultTy
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003783 = FnDecl->getType()->getAsFunctionType()->getResultType();
3784 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003785
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003786 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00003787 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3788 SourceLocation());
Douglas Gregorb4609802008-11-14 16:09:21 +00003789 UsualUnaryConversions(FnExpr);
3790
Ted Kremenek668bf912009-02-09 20:51:47 +00003791 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003792 ResultTy, TokLoc));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003793 } else {
3794 // We matched a built-in operator. Convert the arguments, then
3795 // break out so that we will build the appropriate built-in
3796 // operator node.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003797 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3798 Best->Conversions[0], "passing") ||
3799 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3800 Best->Conversions[1], "passing"))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003801 return ExprError();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003802
3803 break;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003804 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003805 }
3806
3807 case OR_No_Viable_Function:
3808 // No viable function; fall through to handling this as a
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003809 // built-in operator, which will produce an error message for us.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003810 break;
3811
3812 case OR_Ambiguous:
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003813 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3814 << BinaryOperator::getOpcodeStr(Opc)
3815 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregoreaebc752008-11-06 23:29:22 +00003816 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003817 return ExprError();
Douglas Gregoreaebc752008-11-06 23:29:22 +00003818 }
3819
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003820 // Either we found no viable overloaded operator or we matched a
3821 // built-in operator. In either case, fall through to trying to
3822 // build a built-in operation.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003823 }
3824
Douglas Gregoreaebc752008-11-06 23:29:22 +00003825 // Build a built-in binary operation.
3826 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00003827}
3828
3829// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003830Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3831 tok::TokenKind Op, ExprArg input) {
3832 // FIXME: Input is modified later, but smart pointer not reassigned.
3833 Expr *Input = (Expr*)input.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00003834 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor74253732008-11-19 15:42:04 +00003835
3836 if (getLangOptions().CPlusPlus &&
3837 (Input->getType()->isRecordType()
3838 || Input->getType()->isEnumeralType())) {
3839 // Determine which overloaded operator we're dealing with.
3840 static const OverloadedOperatorKind OverOps[] = {
3841 OO_None, OO_None,
3842 OO_PlusPlus, OO_MinusMinus,
3843 OO_Amp, OO_Star,
3844 OO_Plus, OO_Minus,
3845 OO_Tilde, OO_Exclaim,
3846 OO_None, OO_None,
3847 OO_None,
3848 OO_None
3849 };
3850 OverloadedOperatorKind OverOp = OverOps[Opc];
3851
3852 // Add the appropriate overloaded operators (C++ [over.match.oper])
3853 // to the candidate set.
3854 OverloadCandidateSet CandidateSet;
Douglas Gregorf680a0f2009-02-04 16:44:47 +00003855 if (OverOp != OO_None &&
3856 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
3857 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00003858
3859 // Perform overload resolution.
3860 OverloadCandidateSet::iterator Best;
3861 switch (BestViableFunction(CandidateSet, Best)) {
3862 case OR_Success: {
3863 // We found a built-in operator or an overloaded operator.
3864 FunctionDecl *FnDecl = Best->Function;
3865
3866 if (FnDecl) {
3867 // We matched an overloaded operator. Build a call to that
3868 // operator.
3869
3870 // Convert the arguments.
3871 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3872 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003873 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00003874 } else {
3875 // Convert the arguments.
3876 if (PerformCopyInitialization(Input,
3877 FnDecl->getParamDecl(0)->getType(),
3878 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003879 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00003880 }
3881
3882 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00003883 QualType ResultTy
Douglas Gregor74253732008-11-19 15:42:04 +00003884 = FnDecl->getType()->getAsFunctionType()->getResultType();
3885 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003886
Douglas Gregor74253732008-11-19 15:42:04 +00003887 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00003888 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3889 SourceLocation());
Douglas Gregor74253732008-11-19 15:42:04 +00003890 UsualUnaryConversions(FnExpr);
3891
Sebastian Redl0eb23302009-01-19 00:08:26 +00003892 input.release();
Ted Kremenek668bf912009-02-09 20:51:47 +00003893 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input, 1,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003894 ResultTy, OpLoc));
Douglas Gregor74253732008-11-19 15:42:04 +00003895 } else {
3896 // We matched a built-in operator. Convert the arguments, then
3897 // break out so that we will build the appropriate built-in
3898 // operator node.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003899 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3900 Best->Conversions[0], "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003901 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00003902
3903 break;
Sebastian Redl0eb23302009-01-19 00:08:26 +00003904 }
Douglas Gregor74253732008-11-19 15:42:04 +00003905 }
3906
3907 case OR_No_Viable_Function:
3908 // No viable function; fall through to handling this as a
3909 // built-in operator, which will produce an error message for us.
3910 break;
3911
3912 case OR_Ambiguous:
3913 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3914 << UnaryOperator::getOpcodeStr(Opc)
3915 << Input->getSourceRange();
3916 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003917 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00003918 }
3919
3920 // Either we found no viable overloaded operator or we matched a
3921 // built-in operator. In either case, fall through to trying to
Sebastian Redl0eb23302009-01-19 00:08:26 +00003922 // build a built-in operation.
Douglas Gregor74253732008-11-19 15:42:04 +00003923 }
3924
Reid Spencer5f016e22007-07-11 17:01:13 +00003925 QualType resultType;
3926 switch (Opc) {
3927 default:
3928 assert(0 && "Unimplemented unary expr!");
3929 case UnaryOperator::PreInc:
3930 case UnaryOperator::PreDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003931 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3932 Opc == UnaryOperator::PreInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00003933 break;
3934 case UnaryOperator::AddrOf:
3935 resultType = CheckAddressOfOperand(Input, OpLoc);
3936 break;
3937 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00003938 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003939 resultType = CheckIndirectionOperand(Input, OpLoc);
3940 break;
3941 case UnaryOperator::Plus:
3942 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003943 UsualUnaryConversions(Input);
3944 resultType = Input->getType();
Douglas Gregor74253732008-11-19 15:42:04 +00003945 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3946 break;
3947 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3948 resultType->isEnumeralType())
3949 break;
3950 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3951 Opc == UnaryOperator::Plus &&
3952 resultType->isPointerType())
3953 break;
3954
Sebastian Redl0eb23302009-01-19 00:08:26 +00003955 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3956 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003957 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003958 UsualUnaryConversions(Input);
3959 resultType = Input->getType();
Chris Lattner02a65142008-07-25 23:52:49 +00003960 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3961 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3962 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003963 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00003964 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00003965 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003966 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3967 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003968 break;
3969 case UnaryOperator::LNot: // logical negation
3970 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003971 DefaultFunctionArrayConversion(Input);
3972 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003973 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00003974 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3975 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003976 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003977 // In C++, it's bool. C++ 5.3.1p8
3978 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003979 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00003980 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00003981 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00003982 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00003983 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003984 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00003985 resultType = Input->getType();
3986 break;
3987 }
3988 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003989 return ExprError();
3990 input.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00003991 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003992}
3993
Steve Naroff1b273c42007-09-16 14:56:35 +00003994/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3995Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00003996 SourceLocation LabLoc,
3997 IdentifierInfo *LabelII) {
3998 // Look up the record for this label identifier.
3999 LabelStmt *&LabelDecl = LabelMap[LabelII];
4000
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00004001 // If we haven't seen this label yet, create a forward reference. It
4002 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Reid Spencer5f016e22007-07-11 17:01:13 +00004003 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00004004 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00004005
4006 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff6ece14c2009-01-21 00:14:39 +00004007 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4008 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00004009}
4010
Steve Naroff1b273c42007-09-16 14:56:35 +00004011Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004012 SourceLocation RPLoc) { // "({..})"
4013 Stmt *SubStmt = static_cast<Stmt*>(substmt);
4014 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4015 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4016
Eli Friedmandca2b732009-01-24 23:09:00 +00004017 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4018 if (isFileScope) {
4019 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4020 }
4021
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004022 // FIXME: there are a variety of strange constraints to enforce here, for
4023 // example, it is not possible to goto into a stmt expression apparently.
4024 // More semantic analysis is needed.
4025
4026 // FIXME: the last statement in the compount stmt has its value used. We
4027 // should not warn about it being unused.
4028
4029 // If there are sub stmts in the compound stmt, take the type of the last one
4030 // as the type of the stmtexpr.
4031 QualType Ty = Context.VoidTy;
4032
Chris Lattner611b2ec2008-07-26 19:51:01 +00004033 if (!Compound->body_empty()) {
4034 Stmt *LastStmt = Compound->body_back();
4035 // If LastStmt is a label, skip down through into the body.
4036 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4037 LastStmt = Label->getSubStmt();
4038
4039 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004040 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00004041 }
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004042
Steve Naroff6ece14c2009-01-21 00:14:39 +00004043 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004044}
Steve Naroffd34e9152007-08-01 22:05:33 +00004045
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004046Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4047 SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004048 SourceLocation TypeLoc,
4049 TypeTy *argty,
4050 OffsetOfComponent *CompPtr,
4051 unsigned NumComponents,
4052 SourceLocation RPLoc) {
4053 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4054 assert(!ArgTy.isNull() && "Missing type argument!");
4055
4056 // We must have at least one component that refers to the type, and the first
4057 // one is known to be a field designator. Verify that the ArgTy represents
4058 // a struct/union/class.
4059 if (!ArgTy->isRecordType())
Chris Lattnerd1625842008-11-24 06:25:27 +00004060 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004061
4062 // Otherwise, create a compound literal expression as the base, and
4063 // iteratively process the offsetof designators.
Eli Friedman1d242592009-01-26 01:33:06 +00004064 InitListExpr *IList =
Douglas Gregor4c678342009-01-28 21:54:33 +00004065 new (Context) InitListExpr(SourceLocation(), 0, 0, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00004066 IList->setType(ArgTy);
4067 Expr *Res =
4068 new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, IList, false);
4069
Chris Lattner9e2b75c2007-08-31 21:49:13 +00004070 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4071 // GCC extension, diagnose them.
4072 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004073 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4074 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattner9e2b75c2007-08-31 21:49:13 +00004075
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004076 for (unsigned i = 0; i != NumComponents; ++i) {
4077 const OffsetOfComponent &OC = CompPtr[i];
4078 if (OC.isBrackets) {
4079 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004080 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004081 if (!AT) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00004082 Res->Destroy(Context);
Chris Lattnerd1625842008-11-24 06:25:27 +00004083 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004084 }
4085
Chris Lattner704fe352007-08-30 17:59:59 +00004086 // FIXME: C++: Verify that operator[] isn't overloaded.
4087
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004088 // C99 6.5.2.1p1
4089 Expr *Idx = static_cast<Expr*>(OC.U.E);
4090 if (!Idx->getType()->isIntegerType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004091 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4092 << Idx->getSourceRange();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004093
Steve Naroff6ece14c2009-01-21 00:14:39 +00004094 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4095 OC.LocEnd);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004096 continue;
4097 }
4098
4099 const RecordType *RC = Res->getType()->getAsRecordType();
4100 if (!RC) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00004101 Res->Destroy(Context);
Chris Lattnerd1625842008-11-24 06:25:27 +00004102 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004103 }
4104
4105 // Get the decl corresponding to this.
4106 RecordDecl *RD = RC->getDecl();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004107 FieldDecl *MemberDecl
Douglas Gregor4c921ae2009-01-30 01:04:22 +00004108 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4109 LookupMemberName)
4110 .getAsDecl());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004111 if (!MemberDecl)
Chris Lattner3c73c412008-11-19 08:23:25 +00004112 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4113 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner704fe352007-08-30 17:59:59 +00004114
4115 // FIXME: C++: Verify that MemberDecl isn't a static field.
4116 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman51019072008-02-06 22:48:16 +00004117 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4118 // matter here.
Steve Naroff6ece14c2009-01-21 00:14:39 +00004119 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4120 MemberDecl->getType().getNonReferenceType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004121 }
4122
Steve Naroff6ece14c2009-01-21 00:14:39 +00004123 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4124 Context.getSizeType(), BuiltinLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004125}
4126
4127
Steve Naroff1b273c42007-09-16 14:56:35 +00004128Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00004129 TypeTy *arg1, TypeTy *arg2,
4130 SourceLocation RPLoc) {
4131 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4132 QualType argT2 = QualType::getFromOpaquePtr(arg2);
4133
4134 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4135
Steve Naroff6ece14c2009-01-21 00:14:39 +00004136 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
4137 argT2, RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00004138}
4139
Steve Naroff1b273c42007-09-16 14:56:35 +00004140Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00004141 ExprTy *expr1, ExprTy *expr2,
4142 SourceLocation RPLoc) {
4143 Expr *CondExpr = static_cast<Expr*>(cond);
4144 Expr *LHSExpr = static_cast<Expr*>(expr1);
4145 Expr *RHSExpr = static_cast<Expr*>(expr2);
4146
4147 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4148
4149 // The conditional expression is required to be a constant expression.
4150 llvm::APSInt condEval(32);
4151 SourceLocation ExpLoc;
4152 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004153 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4154 << CondExpr->getSourceRange();
Steve Naroffd04fdd52007-08-03 21:21:27 +00004155
4156 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4157 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
4158 RHSExpr->getType();
Steve Naroff6ece14c2009-01-21 00:14:39 +00004159 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4160 resType, RPLoc);
Steve Naroffd04fdd52007-08-03 21:21:27 +00004161}
4162
Steve Naroff4eb206b2008-09-03 18:15:37 +00004163//===----------------------------------------------------------------------===//
4164// Clang Extensions.
4165//===----------------------------------------------------------------------===//
4166
4167/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00004168void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00004169 // Analyze block parameters.
4170 BlockSemaInfo *BSI = new BlockSemaInfo();
4171
4172 // Add BSI to CurBlock.
4173 BSI->PrevBlockInfo = CurBlock;
4174 CurBlock = BSI;
4175
4176 BSI->ReturnType = 0;
4177 BSI->TheScope = BlockScope;
4178
Steve Naroff090276f2008-10-10 01:28:17 +00004179 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00004180 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00004181}
4182
Mike Stump98eb8a72009-02-04 22:31:32 +00004183void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4184 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4185
4186 if (ParamInfo.getNumTypeObjects() == 0
4187 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4188 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4189
4190 // The type is entirely optional as well, if none, use DependentTy.
4191 if (T.isNull())
4192 T = Context.DependentTy;
4193
4194 // The parameter list is optional, if there was none, assume ().
4195 if (!T->isFunctionType())
4196 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4197
4198 CurBlock->hasPrototype = true;
4199 CurBlock->isVariadic = false;
4200 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4201 .getTypePtr();
4202
4203 if (!RetTy->isDependentType())
4204 CurBlock->ReturnType = RetTy;
4205 return;
4206 }
4207
Steve Naroff4eb206b2008-09-03 18:15:37 +00004208 // Analyze arguments to block.
4209 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4210 "Not a function declarator!");
4211 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump98eb8a72009-02-04 22:31:32 +00004212
Steve Naroff090276f2008-10-10 01:28:17 +00004213 CurBlock->hasPrototype = FTI.hasPrototype;
4214 CurBlock->isVariadic = true;
Steve Naroff4eb206b2008-09-03 18:15:37 +00004215
4216 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4217 // no arguments, not a function that takes a single void argument.
4218 if (FTI.hasPrototype &&
4219 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4220 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4221 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4222 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00004223 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00004224 } else if (FTI.hasPrototype) {
4225 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff090276f2008-10-10 01:28:17 +00004226 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4227 CurBlock->isVariadic = FTI.isVariadic;
Mike Stump98eb8a72009-02-04 22:31:32 +00004228 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4229
4230 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4231 .getTypePtr();
4232
4233 if (!RetTy->isDependentType())
4234 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00004235 }
Steve Naroff090276f2008-10-10 01:28:17 +00004236 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4237
4238 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4239 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4240 // If this has an identifier, add it to the scope stack.
4241 if ((*AI)->getIdentifier())
4242 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004243}
4244
4245/// ActOnBlockError - If there is an error parsing a block, this callback
4246/// is invoked to pop the information about the block from the action impl.
4247void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4248 // Ensure that CurBlock is deleted.
4249 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4250
4251 // Pop off CurBlock, handle nested blocks.
4252 CurBlock = CurBlock->PrevBlockInfo;
4253
4254 // FIXME: Delete the ParmVarDecl objects as well???
4255
4256}
4257
4258/// ActOnBlockStmtExpr - This is called when the body of a block statement
4259/// literal was successfully completed. ^(int x){...}
4260Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4261 Scope *CurScope) {
4262 // Ensure that CurBlock is deleted.
4263 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004264 ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body));
Steve Naroff4eb206b2008-09-03 18:15:37 +00004265
Steve Naroff090276f2008-10-10 01:28:17 +00004266 PopDeclContext();
4267
Steve Naroff4eb206b2008-09-03 18:15:37 +00004268 // Pop off CurBlock, handle nested blocks.
4269 CurBlock = CurBlock->PrevBlockInfo;
4270
4271 QualType RetTy = Context.VoidTy;
4272 if (BSI->ReturnType)
4273 RetTy = QualType(BSI->ReturnType, 0);
4274
4275 llvm::SmallVector<QualType, 8> ArgTypes;
4276 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4277 ArgTypes.push_back(BSI->Params[i]->getType());
4278
4279 QualType BlockTy;
4280 if (!BSI->hasPrototype)
4281 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4282 else
4283 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004284 BSI->isVariadic, 0);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004285
4286 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff56ee6892008-10-08 17:01:13 +00004287
Steve Naroff1c90bfc2008-10-08 18:44:00 +00004288 BSI->TheDecl->setBody(Body.take());
Steve Naroff6ece14c2009-01-21 00:14:39 +00004289 return new (Context) BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004290}
4291
Nate Begeman67295d02008-01-30 20:50:20 +00004292/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begemane2ce1d92008-01-17 17:46:27 +00004293/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begeman67295d02008-01-30 20:50:20 +00004294/// The number of arguments has already been validated to match the number of
4295/// arguments in FnType.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004296static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4297 ASTContext &Context) {
Nate Begemane2ce1d92008-01-17 17:46:27 +00004298 unsigned NumParams = FnType->getNumArgs();
Nate Begemand6595fa2008-04-18 23:35:14 +00004299 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00004300 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4301 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begemand6595fa2008-04-18 23:35:14 +00004302
4303 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begemane2ce1d92008-01-17 17:46:27 +00004304 return false;
Nate Begemand6595fa2008-04-18 23:35:14 +00004305 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00004306 return true;
4307}
4308
4309Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4310 SourceLocation *CommaLocs,
4311 SourceLocation BuiltinLoc,
4312 SourceLocation RParenLoc) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00004313 // __builtin_overload requires at least 2 arguments
4314 if (NumArgs < 2)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004315 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4316 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004317
Nate Begemane2ce1d92008-01-17 17:46:27 +00004318 // The first argument is required to be a constant expression. It tells us
4319 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begeman796ef3d2008-01-31 05:38:29 +00004320 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004321 Expr *NParamsExpr = Args[0];
4322 llvm::APSInt constEval(32);
4323 SourceLocation ExpLoc;
4324 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004325 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4326 << NParamsExpr->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004327
4328 // Verify that the number of parameters is > 0
4329 unsigned NumParams = constEval.getZExtValue();
4330 if (NumParams == 0)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004331 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4332 << NParamsExpr->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004333 // Verify that we have at least 1 + NumParams arguments to the builtin.
4334 if ((NumParams + 1) > NumArgs)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004335 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4336 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004337
4338 // Figure out the return type, by matching the args to one of the functions
Nate Begeman67295d02008-01-30 20:50:20 +00004339 // listed after the parameters.
Nate Begeman796ef3d2008-01-31 05:38:29 +00004340 OverloadExpr *OE = 0;
Nate Begemane2ce1d92008-01-17 17:46:27 +00004341 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4342 // UsualUnaryConversions will convert the function DeclRefExpr into a
4343 // pointer to function.
4344 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerb77792e2008-07-26 22:17:49 +00004345 const FunctionTypeProto *FnType = 0;
4346 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4347 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004348
4349 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4350 // parameters, and the number of parameters must match the value passed to
4351 // the builtin.
4352 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004353 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4354 << Fn->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004355
4356 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begeman67295d02008-01-30 20:50:20 +00004357 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begemane2ce1d92008-01-17 17:46:27 +00004358 // If they match, return a new OverloadExpr.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004359 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00004360 if (OE)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004361 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4362 << OE->getFn()->getSourceRange();
Nate Begeman796ef3d2008-01-31 05:38:29 +00004363 // Remember our match, and continue processing the remaining arguments
4364 // to catch any errors.
Ted Kremenekfb7413f2009-02-09 17:08:14 +00004365 OE = new (Context) OverloadExpr(Context, Args, NumArgs, i,
Douglas Gregor9d293df2008-10-28 00:22:11 +00004366 FnType->getResultType().getNonReferenceType(),
Nate Begeman796ef3d2008-01-31 05:38:29 +00004367 BuiltinLoc, RParenLoc);
4368 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00004369 }
Nate Begeman796ef3d2008-01-31 05:38:29 +00004370 // Return the newly created OverloadExpr node, if we succeded in matching
4371 // exactly one of the candidate functions.
4372 if (OE)
4373 return OE;
Nate Begemane2ce1d92008-01-17 17:46:27 +00004374
4375 // If we didn't find a matching function Expr in the __builtin_overload list
4376 // the return an error.
4377 std::string typeNames;
Nate Begeman67295d02008-01-30 20:50:20 +00004378 for (unsigned i = 0; i != NumParams; ++i) {
4379 if (i != 0) typeNames += ", ";
4380 typeNames += Args[i+1]->getType().getAsString();
4381 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00004382
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004383 return Diag(BuiltinLoc, diag::err_overload_no_match)
4384 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004385}
4386
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004387Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4388 ExprTy *expr, TypeTy *type,
Chris Lattner5cf216b2008-01-04 18:04:52 +00004389 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004390 Expr *E = static_cast<Expr*>(expr);
4391 QualType T = QualType::getFromOpaquePtr(type);
4392
4393 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00004394
4395 // Get the va_list type
4396 QualType VaListType = Context.getBuiltinVaListType();
4397 // Deal with implicit array decay; for example, on x86-64,
4398 // va_list is an array, but it's supposed to decay to
4399 // a pointer for va_arg.
4400 if (VaListType->isArrayType())
4401 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmanefbe85c2008-08-20 22:17:17 +00004402 // Make sure the input expression also decays appropriately.
4403 UsualUnaryConversions(E);
Eli Friedmanc34bcde2008-08-09 23:32:40 +00004404
4405 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004406 return Diag(E->getLocStart(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004407 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerd1625842008-11-24 06:25:27 +00004408 << E->getType() << E->getSourceRange();
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004409
4410 // FIXME: Warn if a non-POD type is passed in.
4411
Steve Naroff6ece14c2009-01-21 00:14:39 +00004412 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004413}
4414
Douglas Gregor2d8b2732008-11-29 04:51:27 +00004415Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4416 // The type of __null will be int or long, depending on the size of
4417 // pointers on the target.
4418 QualType Ty;
4419 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4420 Ty = Context.IntTy;
4421 else
4422 Ty = Context.LongTy;
4423
Steve Naroff6ece14c2009-01-21 00:14:39 +00004424 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregor2d8b2732008-11-29 04:51:27 +00004425}
4426
Chris Lattner5cf216b2008-01-04 18:04:52 +00004427bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4428 SourceLocation Loc,
4429 QualType DstType, QualType SrcType,
4430 Expr *SrcExpr, const char *Flavor) {
4431 // Decode the result (notice that AST's are still created for extensions).
4432 bool isInvalid = false;
4433 unsigned DiagKind;
4434 switch (ConvTy) {
4435 default: assert(0 && "Unknown conversion type");
4436 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00004437 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00004438 DiagKind = diag::ext_typecheck_convert_pointer_int;
4439 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00004440 case IntToPointer:
4441 DiagKind = diag::ext_typecheck_convert_int_pointer;
4442 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004443 case IncompatiblePointer:
4444 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4445 break;
4446 case FunctionVoidPointer:
4447 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4448 break;
4449 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00004450 // If the qualifiers lost were because we were applying the
4451 // (deprecated) C++ conversion from a string literal to a char*
4452 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4453 // Ideally, this check would be performed in
4454 // CheckPointerTypesForAssignment. However, that would require a
4455 // bit of refactoring (so that the second argument is an
4456 // expression, rather than a type), which should be done as part
4457 // of a larger effort to fix CheckPointerTypesForAssignment for
4458 // C++ semantics.
4459 if (getLangOptions().CPlusPlus &&
4460 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4461 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004462 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4463 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004464 case IntToBlockPointer:
4465 DiagKind = diag::err_int_to_block_pointer;
4466 break;
4467 case IncompatibleBlockPointer:
Steve Naroffba80c9a2008-09-24 23:31:10 +00004468 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004469 break;
Steve Naroff39579072008-10-14 22:18:38 +00004470 case IncompatibleObjCQualifiedId:
4471 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4472 // it can give a more specific diagnostic.
4473 DiagKind = diag::warn_incompatible_qualified_id;
4474 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004475 case IncompatibleVectors:
4476 DiagKind = diag::warn_incompatible_vectors;
4477 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004478 case Incompatible:
4479 DiagKind = diag::err_typecheck_convert_incompatible;
4480 isInvalid = true;
4481 break;
4482 }
4483
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004484 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4485 << SrcExpr->getSourceRange();
Chris Lattner5cf216b2008-01-04 18:04:52 +00004486 return isInvalid;
4487}
Anders Carlssone21555e2008-11-30 19:50:32 +00004488
4489bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4490{
4491 Expr::EvalResult EvalResult;
4492
4493 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4494 EvalResult.HasSideEffects) {
4495 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4496
4497 if (EvalResult.Diag) {
4498 // We only show the note if it's not the usual "invalid subexpression"
4499 // or if it's actually in a subexpression.
4500 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4501 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4502 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4503 }
4504
4505 return true;
4506 }
4507
4508 if (EvalResult.Diag) {
4509 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4510 E->getSourceRange();
4511
4512 // Print the reason it's not a constant.
4513 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4514 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4515 }
4516
4517 if (Result)
4518 *Result = EvalResult.Val.getInt();
4519 return false;
4520}