blob: 0c755f6d1f0b189bb583ce1866f269bc338dab2d [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"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
21#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000023#include "clang/Parse/DeclSpec.h"
Chris Lattner418f6c72008-10-26 23:43:26 +000024#include "clang/Parse/Designator.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000025#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026using namespace clang;
27
Chris Lattnere7a2e912008-07-25 21:10:04 +000028//===----------------------------------------------------------------------===//
29// Standard Promotions and Conversions
30//===----------------------------------------------------------------------===//
31
Chris Lattnere7a2e912008-07-25 21:10:04 +000032/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
33void Sema::DefaultFunctionArrayConversion(Expr *&E) {
34 QualType Ty = E->getType();
35 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
36
Chris Lattnere7a2e912008-07-25 21:10:04 +000037 if (Ty->isFunctionType())
38 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner67d33d82008-07-25 21:33:13 +000039 else if (Ty->isArrayType()) {
40 // In C90 mode, arrays only promote to pointers if the array expression is
41 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
42 // type 'array of type' is converted to an expression that has type 'pointer
43 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
44 // that has type 'array of type' ...". The relevant change is "an lvalue"
45 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +000046 //
47 // C++ 4.2p1:
48 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
49 // T" can be converted to an rvalue of type "pointer to T".
50 //
51 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
52 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner67d33d82008-07-25 21:33:13 +000053 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
54 }
Chris Lattnere7a2e912008-07-25 21:10:04 +000055}
56
57/// UsualUnaryConversions - Performs various conversions that are common to most
58/// operators (C99 6.3). The conversions of array and function types are
59/// sometimes surpressed. For example, the array->pointer conversion doesn't
60/// apply if the array is an argument to the sizeof or address (&) operators.
61/// In these instances, this routine should *not* be called.
62Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
63 QualType Ty = Expr->getType();
64 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
65
Chris Lattnere7a2e912008-07-25 21:10:04 +000066 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
67 ImpCastExprToType(Expr, Context.IntTy);
68 else
69 DefaultFunctionArrayConversion(Expr);
70
71 return Expr;
72}
73
Chris Lattner05faf172008-07-25 22:25:12 +000074/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
75/// do not have a prototype. Arguments that have type float are promoted to
76/// double. All other argument types are converted by UsualUnaryConversions().
77void Sema::DefaultArgumentPromotion(Expr *&Expr) {
78 QualType Ty = Expr->getType();
79 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
80
81 // If this is a 'float' (CVR qualified or typedef) promote to double.
82 if (const BuiltinType *BT = Ty->getAsBuiltinType())
83 if (BT->getKind() == BuiltinType::Float)
84 return ImpCastExprToType(Expr, Context.DoubleTy);
85
86 UsualUnaryConversions(Expr);
87}
88
Anders Carlssondce5e2c2009-01-16 16:48:51 +000089// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
90// will warn if the resulting type is not a POD type.
91void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT)
92
93{
94 DefaultArgumentPromotion(Expr);
95
96 if (!Expr->getType()->isPODType()) {
97 Diag(Expr->getLocStart(),
98 diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
99 Expr->getType() << CT;
100 }
101}
102
103
Chris Lattnere7a2e912008-07-25 21:10:04 +0000104/// UsualArithmeticConversions - Performs various conversions that are common to
105/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
106/// routine returns the first non-arithmetic type found. The client is
107/// responsible for emitting appropriate error diagnostics.
108/// FIXME: verify the conversion rules for "complex int" are consistent with
109/// GCC.
110QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
111 bool isCompAssign) {
112 if (!isCompAssign) {
113 UsualUnaryConversions(lhsExpr);
114 UsualUnaryConversions(rhsExpr);
115 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000116
Chris Lattnere7a2e912008-07-25 21:10:04 +0000117 // For conversion purposes, we ignore any qualifiers.
118 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000119 QualType lhs =
120 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
121 QualType rhs =
122 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000123
124 // If both types are identical, no conversion is needed.
125 if (lhs == rhs)
126 return lhs;
127
128 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
129 // The caller can deal with this (e.g. pointer + int).
130 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
131 return lhs;
132
133 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
134 if (!isCompAssign) {
135 ImpCastExprToType(lhsExpr, destType);
136 ImpCastExprToType(rhsExpr, destType);
137 }
138 return destType;
139}
140
141QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
142 // Perform the usual unary conversions. We do this early so that
143 // integral promotions to "int" can allow us to exit early, in the
144 // lhs == rhs check. Also, for conversion purposes, we ignore any
145 // qualifiers. For example, "const float" and "float" are
146 // equivalent.
Douglas Gregorbf3af052008-11-13 20:12:29 +0000147 if (lhs->isPromotableIntegerType()) lhs = Context.IntTy;
148 else lhs = lhs.getUnqualifiedType();
149 if (rhs->isPromotableIntegerType()) rhs = Context.IntTy;
150 else rhs = rhs.getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000151
Chris Lattnere7a2e912008-07-25 21:10:04 +0000152 // If both types are identical, no conversion is needed.
153 if (lhs == rhs)
154 return lhs;
155
156 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
157 // The caller can deal with this (e.g. pointer + int).
158 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
159 return lhs;
160
161 // At this point, we have two different arithmetic types.
162
163 // Handle complex types first (C99 6.3.1.8p1).
164 if (lhs->isComplexType() || rhs->isComplexType()) {
165 // if we have an integer operand, the result is the complex type.
166 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
167 // convert the rhs to the lhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000168 return lhs;
169 }
170 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
171 // convert the lhs to the rhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000172 return rhs;
173 }
174 // This handles complex/complex, complex/float, or float/complex.
175 // When both operands are complex, the shorter operand is converted to the
176 // type of the longer, and that is the type of the result. This corresponds
177 // to what is done when combining two real floating-point operands.
178 // The fun begins when size promotion occur across type domains.
179 // From H&S 6.3.4: When one operand is complex and the other is a real
180 // floating-point type, the less precise type is converted, within it's
181 // real or complex domain, to the precision of the other type. For example,
182 // when combining a "long double" with a "double _Complex", the
183 // "double _Complex" is promoted to "long double _Complex".
184 int result = Context.getFloatingTypeOrder(lhs, rhs);
185
186 if (result > 0) { // The left side is bigger, convert rhs.
187 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000188 } else if (result < 0) { // The right side is bigger, convert lhs.
189 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000190 }
191 // At this point, lhs and rhs have the same rank/size. Now, make sure the
192 // domains match. This is a requirement for our implementation, C99
193 // does not require this promotion.
194 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
195 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattnere7a2e912008-07-25 21:10:04 +0000196 return rhs;
197 } else { // handle "_Complex double, double".
Chris Lattnere7a2e912008-07-25 21:10:04 +0000198 return lhs;
199 }
200 }
201 return lhs; // The domain/size match exactly.
202 }
203 // Now handle "real" floating types (i.e. float, double, long double).
204 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
205 // if we have an integer operand, the result is the real floating type.
Anders Carlsson5b1f3f02008-12-10 23:30:05 +0000206 if (rhs->isIntegerType()) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000207 // convert rhs to the lhs floating point type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000208 return lhs;
209 }
Anders Carlsson5b1f3f02008-12-10 23:30:05 +0000210 if (rhs->isComplexIntegerType()) {
211 // convert rhs to the complex floating point type.
212 return Context.getComplexType(lhs);
213 }
214 if (lhs->isIntegerType()) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000215 // convert lhs to the rhs floating point type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000216 return rhs;
217 }
Anders Carlsson5b1f3f02008-12-10 23:30:05 +0000218 if (lhs->isComplexIntegerType()) {
219 // convert lhs to the complex floating point type.
220 return Context.getComplexType(rhs);
221 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000222 // We have two real floating types, float/complex combos were handled above.
223 // Convert the smaller operand to the bigger result.
224 int result = Context.getFloatingTypeOrder(lhs, rhs);
225
226 if (result > 0) { // convert the rhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000227 return lhs;
228 }
229 if (result < 0) { // convert the lhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000230 return rhs;
231 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000232 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
Chris Lattnere7a2e912008-07-25 21:10:04 +0000233 }
234 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
235 // Handle GCC complex int extension.
236 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
237 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
238
239 if (lhsComplexInt && rhsComplexInt) {
240 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
241 rhsComplexInt->getElementType()) >= 0) {
242 // convert the rhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000243 return lhs;
244 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000245 return rhs;
246 } else if (lhsComplexInt && rhs->isIntegerType()) {
247 // convert the rhs to the lhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000248 return lhs;
249 } else if (rhsComplexInt && lhs->isIntegerType()) {
250 // convert the lhs to the rhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000251 return rhs;
252 }
253 }
254 // Finally, we have two differing integer types.
255 // The rules for this case are in C99 6.3.1.8
256 int compare = Context.getIntegerTypeOrder(lhs, rhs);
257 bool lhsSigned = lhs->isSignedIntegerType(),
258 rhsSigned = rhs->isSignedIntegerType();
259 QualType destType;
260 if (lhsSigned == rhsSigned) {
261 // Same signedness; use the higher-ranked type
262 destType = compare >= 0 ? lhs : rhs;
263 } else if (compare != (lhsSigned ? 1 : -1)) {
264 // The unsigned type has greater than or equal rank to the
265 // signed type, so use the unsigned type
266 destType = lhsSigned ? rhs : lhs;
267 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
268 // The two types are different widths; if we are here, that
269 // means the signed type is larger than the unsigned type, so
270 // use the signed type.
271 destType = lhsSigned ? lhs : rhs;
272 } else {
273 // The signed type is higher-ranked than the unsigned type,
274 // but isn't actually any bigger (like unsigned int and long
275 // on most 32-bit systems). Use the unsigned type corresponding
276 // to the signed type.
277 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
278 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000279 return destType;
280}
281
282//===----------------------------------------------------------------------===//
283// Semantic Analysis for various Expression Types
284//===----------------------------------------------------------------------===//
285
286
Steve Narofff69936d2007-09-16 03:34:24 +0000287/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000288/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
289/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
290/// multiple tokens. However, the common case is that StringToks points to one
291/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000292///
293Action::OwningExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000294Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000295 assert(NumStringToks && "Must have at least one string!");
296
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000297 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000298 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000299 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000300
301 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
302 for (unsigned i = 0; i != NumStringToks; ++i)
303 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000304
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000305 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000306 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000307 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000308
309 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
310 if (getLangOptions().CPlusPlus)
311 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000312
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000313 // Get an array type for the string, according to C99 6.4.5. This includes
314 // the nul terminator character as well as the string length for pascal
315 // strings.
316 StrTy = Context.getConstantArrayType(StrTy,
317 llvm::APInt(32, Literal.GetStringLength()+1),
318 ArrayType::Normal, 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000319
Reid Spencer5f016e22007-07-11 17:01:13 +0000320 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Steve Naroff6ece14c2009-01-21 00:14:39 +0000321 return Owned(new (Context) StringLiteral(Literal.GetString(),
322 Literal.GetStringLength(),
Sebastian Redlcd965b92009-01-18 18:53:16 +0000323 Literal.AnyWide, StrTy,
324 StringToks[0].getLocation(),
325 StringToks[NumStringToks-1].getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000326}
327
Chris Lattner639e2d32008-10-20 05:16:36 +0000328/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
329/// CurBlock to VD should cause it to be snapshotted (as we do for auto
330/// variables defined outside the block) or false if this is not needed (e.g.
331/// for values inside the block or for globals).
332///
333/// FIXME: This will create BlockDeclRefExprs for global variables,
334/// function references, etc which is suboptimal :) and breaks
335/// things like "integer constant expression" tests.
336static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
337 ValueDecl *VD) {
338 // If the value is defined inside the block, we couldn't snapshot it even if
339 // we wanted to.
340 if (CurBlock->TheDecl == VD->getDeclContext())
341 return false;
342
343 // If this is an enum constant or function, it is constant, don't snapshot.
344 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
345 return false;
346
347 // If this is a reference to an extern, static, or global variable, no need to
348 // snapshot it.
349 // FIXME: What about 'const' variables in C++?
350 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
351 return Var->hasLocalStorage();
352
353 return true;
354}
355
356
357
Steve Naroff08d92e42007-09-15 18:49:24 +0000358/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +0000359/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroff0d755ad2008-03-19 23:46:26 +0000360/// identifier is used in a function call context.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000361/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000362/// class or namespace that the identifier must be a member of.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000363Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
364 IdentifierInfo &II,
365 bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000366 const CXXScopeSpec *SS,
367 bool isAddressOfOperand) {
368 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor17330012009-02-04 15:01:18 +0000369 isAddressOfOperand);
Douglas Gregor10c42622008-11-18 15:03:34 +0000370}
371
Douglas Gregor1a49af92009-01-06 05:10:23 +0000372/// BuildDeclRefExpr - Build either a DeclRefExpr or a
373/// QualifiedDeclRefExpr based on whether or not SS is a
374/// nested-name-specifier.
Sebastian Redlebc07d52009-02-03 20:19:35 +0000375DeclRefExpr *
376Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
377 bool TypeDependent, bool ValueDependent,
378 const CXXScopeSpec *SS) {
Steve Naroff6ece14c2009-01-21 00:14:39 +0000379 if (SS && !SS->isEmpty())
380 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Steve Naroff0a473932009-01-20 19:53:53 +0000381 ValueDependent, SS->getRange().getBegin());
Steve Naroff6ece14c2009-01-21 00:14:39 +0000382 else
383 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor1a49af92009-01-06 05:10:23 +0000384}
385
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000386/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
387/// variable corresponding to the anonymous union or struct whose type
388/// is Record.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000389static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000390 assert(Record->isAnonymousStructOrUnion() &&
391 "Record must be an anonymous struct or union!");
392
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000393 // FIXME: Once Decls are directly linked together, this will
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000394 // be an O(1) operation rather than a slow walk through DeclContext's
395 // vector (which itself will be eliminated). DeclGroups might make
396 // this even better.
397 DeclContext *Ctx = Record->getDeclContext();
398 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
399 DEnd = Ctx->decls_end();
400 D != DEnd; ++D) {
401 if (*D == Record) {
402 // The object for the anonymous struct/union directly
403 // follows its type in the list of declarations.
404 ++D;
405 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000406 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000407 return *D;
408 }
409 }
410
411 assert(false && "Missing object for anonymous record");
412 return 0;
413}
414
Sebastian Redlcd965b92009-01-18 18:53:16 +0000415Sema::OwningExprResult
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000416Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
417 FieldDecl *Field,
418 Expr *BaseObjectExpr,
419 SourceLocation OpLoc) {
420 assert(Field->getDeclContext()->isRecord() &&
421 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
422 && "Field must be stored inside an anonymous struct or union");
423
424 // Construct the sequence of field member references
425 // we'll have to perform to get to the field in the anonymous
426 // union/struct. The list of members is built from the field
427 // outward, so traverse it backwards to go from an object in
428 // the current context to the field we found.
429 llvm::SmallVector<FieldDecl *, 4> AnonFields;
430 AnonFields.push_back(Field);
431 VarDecl *BaseObject = 0;
432 DeclContext *Ctx = Field->getDeclContext();
433 do {
434 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000435 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000436 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
437 AnonFields.push_back(AnonField);
438 else {
439 BaseObject = cast<VarDecl>(AnonObject);
440 break;
441 }
442 Ctx = Ctx->getParent();
443 } while (Ctx->isRecord() &&
444 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
445
446 // Build the expression that refers to the base object, from
447 // which we will build a sequence of member references to each
448 // of the anonymous union objects and, eventually, the field we
449 // found via name lookup.
450 bool BaseObjectIsPointer = false;
451 unsigned ExtraQuals = 0;
452 if (BaseObject) {
453 // BaseObject is an anonymous struct/union variable (and is,
454 // therefore, not part of another non-anonymous record).
455 delete BaseObjectExpr;
456
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 Gregor8e9bebd2008-10-21 16:13:35 +0000749
Steve Naroffdd972f22008-09-05 22:11:13 +0000750 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000751
Steve Naroffdd972f22008-09-05 22:11:13 +0000752 // check if referencing an identifier with __attribute__((deprecated)).
753 if (VD->getAttr<DeprecatedAttr>())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000754 ExprError(Diag(Loc, diag::warn_deprecated) << VD->getDeclName());
755
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000756 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
757 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
758 Scope *CheckS = S;
759 while (CheckS) {
760 if (CheckS->isWithinElse() &&
761 CheckS->getControlParent()->isDeclScope(Var)) {
762 if (Var->getType()->isBooleanType())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000763 ExprError(Diag(Loc, diag::warn_value_always_false)
764 << Var->getDeclName());
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000765 else
Sebastian Redlcd965b92009-01-18 18:53:16 +0000766 ExprError(Diag(Loc, diag::warn_value_always_zero)
767 << Var->getDeclName());
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000768 break;
769 }
770
771 // Move up one more control parent to check again.
772 CheckS = CheckS->getControlParent();
773 if (CheckS)
774 CheckS = CheckS->getParent();
775 }
776 }
777 }
Steve Naroffdd972f22008-09-05 22:11:13 +0000778
779 // Only create DeclRefExpr's for valid Decl's.
780 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000781 return ExprError();
782
Chris Lattner639e2d32008-10-20 05:16:36 +0000783 // If the identifier reference is inside a block, and it refers to a value
784 // that is outside the block, create a BlockDeclRefExpr instead of a
785 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
786 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +0000787 //
Chris Lattner639e2d32008-10-20 05:16:36 +0000788 // We do not do this for things like enum constants, global variables, etc,
789 // as they do not get snapshotted.
790 //
791 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff090276f2008-10-10 01:28:17 +0000792 // The BlocksAttr indicates the variable is bound by-reference.
793 if (VD->getAttr<BlocksAttr>())
Steve Naroff6ece14c2009-01-21 00:14:39 +0000794 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroff0a473932009-01-20 19:53:53 +0000795 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd965b92009-01-18 18:53:16 +0000796
Steve Naroff090276f2008-10-10 01:28:17 +0000797 // Variable will be bound by-copy, make it const within the closure.
798 VD->getType().addConst();
Steve Naroff6ece14c2009-01-21 00:14:39 +0000799 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroff0a473932009-01-20 19:53:53 +0000800 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff090276f2008-10-10 01:28:17 +0000801 }
802 // If this reference is not in a block or if the referenced variable is
803 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +0000804
Douglas Gregor898574e2008-12-05 23:32:09 +0000805 bool TypeDependent = false;
Douglas Gregor83f96f62008-12-10 20:57:37 +0000806 bool ValueDependent = false;
807 if (getLangOptions().CPlusPlus) {
808 // C++ [temp.dep.expr]p3:
809 // An id-expression is type-dependent if it contains:
810 // - an identifier that was declared with a dependent type,
811 if (VD->getType()->isDependentType())
812 TypeDependent = true;
813 // - FIXME: a template-id that is dependent,
814 // - a conversion-function-id that specifies a dependent type,
815 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
816 Name.getCXXNameType()->isDependentType())
817 TypeDependent = true;
818 // - a nested-name-specifier that contains a class-name that
819 // names a dependent type.
820 else if (SS && !SS->isEmpty()) {
821 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
822 DC; DC = DC->getParent()) {
823 // FIXME: could stop early at namespace scope.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000824 if (DC->isRecord()) {
Douglas Gregor83f96f62008-12-10 20:57:37 +0000825 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
826 if (Context.getTypeDeclType(Record)->isDependentType()) {
827 TypeDependent = true;
828 break;
829 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000830 }
831 }
832 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000833
Douglas Gregor83f96f62008-12-10 20:57:37 +0000834 // C++ [temp.dep.constexpr]p2:
835 //
836 // An identifier is value-dependent if it is:
837 // - a name declared with a dependent type,
838 if (TypeDependent)
839 ValueDependent = true;
840 // - the name of a non-type template parameter,
841 else if (isa<NonTypeTemplateParmDecl>(VD))
842 ValueDependent = true;
843 // - a constant with integral or enumeration type and is
844 // initialized with an expression that is value-dependent
845 // (FIXME!).
846 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000847
Sebastian Redlcd965b92009-01-18 18:53:16 +0000848 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
849 TypeDependent, ValueDependent, SS));
Reid Spencer5f016e22007-07-11 17:01:13 +0000850}
851
Sebastian Redlcd965b92009-01-18 18:53:16 +0000852Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
853 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +0000854 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +0000855
Reid Spencer5f016e22007-07-11 17:01:13 +0000856 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +0000857 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +0000858 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
859 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
860 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000861 }
Chris Lattner1423ea42008-01-12 18:39:25 +0000862
Chris Lattnerfa28b302008-01-12 08:14:25 +0000863 // Pre-defined identifiers are of type char[x], where x is the length of the
864 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +0000865 unsigned Length;
Chris Lattner371f2582008-12-04 23:50:19 +0000866 if (FunctionDecl *FD = getCurFunctionDecl())
867 Length = FD->getIdentifier()->getLength();
Chris Lattnerb0da9232008-12-12 05:05:20 +0000868 else if (ObjCMethodDecl *MD = getCurMethodDecl())
869 Length = MD->getSynthesizedMethodSize();
870 else {
871 Diag(Loc, diag::ext_predef_outside_function);
872 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
873 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
874 }
Sebastian Redlcd965b92009-01-18 18:53:16 +0000875
876
Chris Lattner8f978d52008-01-12 19:32:28 +0000877 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +0000878 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +0000879 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000880 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +0000881}
882
Sebastian Redlcd965b92009-01-18 18:53:16 +0000883Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000884 llvm::SmallString<16> CharBuffer;
885 CharBuffer.resize(Tok.getLength());
886 const char *ThisTokBegin = &CharBuffer[0];
887 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000888
Reid Spencer5f016e22007-07-11 17:01:13 +0000889 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
890 Tok.getLocation(), PP);
891 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000892 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +0000893
894 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
895
Sebastian Redle91b3bc2009-01-20 22:23:13 +0000896 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
897 Literal.isWide(),
898 type, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000899}
900
Sebastian Redlcd965b92009-01-18 18:53:16 +0000901Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
902 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +0000903 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
904 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +0000905 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +0000906 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +0000907 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +0000908 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000909 }
Ted Kremenek28396602009-01-13 23:19:12 +0000910
Reid Spencer5f016e22007-07-11 17:01:13 +0000911 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +0000912 // Add padding so that NumericLiteralParser can overread by one character.
913 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000914 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +0000915
Reid Spencer5f016e22007-07-11 17:01:13 +0000916 // Get the spelling of the token, which eliminates trigraphs, etc.
917 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000918
Reid Spencer5f016e22007-07-11 17:01:13 +0000919 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
920 Tok.getLocation(), PP);
921 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000922 return ExprError();
923
Chris Lattner5d661452007-08-26 03:42:43 +0000924 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +0000925
Chris Lattner5d661452007-08-26 03:42:43 +0000926 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000927 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000928 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +0000929 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000930 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +0000931 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000932 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000933 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000934
935 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
936
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000937 // isExact will be set by GetFloatValue().
938 bool isExact = false;
Sebastian Redle91b3bc2009-01-20 22:23:13 +0000939 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
940 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +0000941
Chris Lattner5d661452007-08-26 03:42:43 +0000942 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000943 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +0000944 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000945 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +0000946
Neil Boothb9449512007-08-29 22:00:19 +0000947 // long long is a C99 feature.
948 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000949 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000950 Diag(Tok.getLocation(), diag::ext_longlong);
951
Reid Spencer5f016e22007-07-11 17:01:13 +0000952 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +0000953 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000954
Reid Spencer5f016e22007-07-11 17:01:13 +0000955 if (Literal.GetIntegerValue(ResultVal)) {
956 // If this value didn't fit into uintmax_t, warn and force to ull.
957 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000958 Ty = Context.UnsignedLongLongTy;
959 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +0000960 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000961 } else {
962 // If this value fits into a ULL, try to figure out what else it fits into
963 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000964
Reid Spencer5f016e22007-07-11 17:01:13 +0000965 // Octal, Hexadecimal, and integers with a U suffix are allowed to
966 // be an unsigned int.
967 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
968
969 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000970 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +0000971 if (!Literal.isLong && !Literal.isLongLong) {
972 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000973 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000974
Reid Spencer5f016e22007-07-11 17:01:13 +0000975 // Does it fit in a unsigned int?
976 if (ResultVal.isIntN(IntSize)) {
977 // Does it fit in a signed int?
978 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000979 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000980 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000981 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000982 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000983 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000984 }
Sebastian Redlcd965b92009-01-18 18:53:16 +0000985
Reid Spencer5f016e22007-07-11 17:01:13 +0000986 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +0000987 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000988 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000989
Reid Spencer5f016e22007-07-11 17:01:13 +0000990 // Does it fit in a unsigned long?
991 if (ResultVal.isIntN(LongSize)) {
992 // Does it fit in a signed long?
993 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000994 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000995 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000996 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000997 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000998 }
Sebastian Redlcd965b92009-01-18 18:53:16 +0000999 }
1000
Reid Spencer5f016e22007-07-11 17:01:13 +00001001 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001002 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001003 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001004
Reid Spencer5f016e22007-07-11 17:01:13 +00001005 // Does it fit in a unsigned long long?
1006 if (ResultVal.isIntN(LongLongSize)) {
1007 // Does it fit in a signed long long?
1008 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001009 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001010 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001011 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001012 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001013 }
1014 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001015
Reid Spencer5f016e22007-07-11 17:01:13 +00001016 // If we still couldn't decide a type, we probably have something that
1017 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001018 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001019 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001020 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001021 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001022 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001023
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001024 if (ResultVal.getBitWidth() != Width)
1025 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001026 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001027 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001028 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001029
Chris Lattner5d661452007-08-26 03:42:43 +00001030 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1031 if (Literal.isImaginary)
Steve Naroff6ece14c2009-01-21 00:14:39 +00001032 Res = new (Context) ImaginaryLiteral(Res,
1033 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001034
1035 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001036}
1037
Sebastian Redlcd965b92009-01-18 18:53:16 +00001038Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1039 SourceLocation R, ExprArg Val) {
1040 Expr *E = (Expr *)Val.release();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001041 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001042 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001043}
1044
1045/// The UsualUnaryConversions() function is *not* called by this routine.
1046/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl05189992008-11-11 17:56:53 +00001047bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1048 SourceLocation OpLoc,
1049 const SourceRange &ExprRange,
1050 bool isSizeof) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001051 // C99 6.5.3.4p1:
Chris Lattner01072922009-01-24 19:46:37 +00001052 if (isa<FunctionType>(exprType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001053 // alignof(function) is allowed.
Chris Lattner01072922009-01-24 19:46:37 +00001054 if (isSizeof)
1055 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1056 return false;
1057 }
1058
1059 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001060 Diag(OpLoc, diag::ext_sizeof_void_type)
1061 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001062 return false;
1063 }
Sebastian Redl05189992008-11-11 17:56:53 +00001064
Chris Lattner01072922009-01-24 19:46:37 +00001065 return DiagnoseIncompleteType(OpLoc, exprType,
1066 isSizeof ? diag::err_sizeof_incomplete_type :
1067 diag::err_alignof_incomplete_type,
1068 ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +00001069}
1070
Chris Lattner31e21e02009-01-24 20:17:12 +00001071bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1072 const SourceRange &ExprRange) {
1073 E = E->IgnoreParens();
1074
1075 // alignof decl is always ok.
1076 if (isa<DeclRefExpr>(E))
1077 return false;
1078
1079 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1080 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1081 if (FD->isBitField()) {
Chris Lattnerda027472009-01-24 21:29:22 +00001082 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner31e21e02009-01-24 20:17:12 +00001083 return true;
1084 }
1085 // Other fields are ok.
1086 return false;
1087 }
1088 }
1089 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1090}
1091
Sebastian Redl05189992008-11-11 17:56:53 +00001092/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1093/// the same for @c alignof and @c __alignof
1094/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001095Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001096Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1097 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001098 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001099 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001100
Sebastian Redl05189992008-11-11 17:56:53 +00001101 QualType ArgTy;
1102 SourceRange Range;
1103 if (isType) {
1104 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1105 Range = ArgRange;
Chris Lattner694b1e42009-01-24 19:49:13 +00001106
1107 // Verify that the operand is valid.
1108 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1109 return ExprError();
Sebastian Redl05189992008-11-11 17:56:53 +00001110 } else {
1111 // Get the end location.
1112 Expr *ArgEx = (Expr *)TyOrEx;
1113 Range = ArgEx->getSourceRange();
1114 ArgTy = ArgEx->getType();
Chris Lattner694b1e42009-01-24 19:49:13 +00001115
1116 // Verify that the operand is valid.
Chris Lattner31e21e02009-01-24 20:17:12 +00001117 bool isInvalid;
Chris Lattnerda027472009-01-24 21:29:22 +00001118 if (!isSizeof) {
Chris Lattner31e21e02009-01-24 20:17:12 +00001119 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattnerda027472009-01-24 21:29:22 +00001120 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1121 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1122 isInvalid = true;
1123 } else {
1124 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1125 }
Chris Lattner31e21e02009-01-24 20:17:12 +00001126
1127 if (isInvalid) {
Chris Lattner694b1e42009-01-24 19:49:13 +00001128 DeleteExpr(ArgEx);
1129 return ExprError();
1130 }
Sebastian Redl05189992008-11-11 17:56:53 +00001131 }
1132
Sebastian Redl05189992008-11-11 17:56:53 +00001133 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001134 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner01072922009-01-24 19:46:37 +00001135 Context.getSizeType(), OpLoc,
1136 Range.getEnd()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001137}
1138
Chris Lattner5d794252007-08-24 21:41:10 +00001139QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +00001140 DefaultFunctionArrayConversion(V);
1141
Chris Lattnercc26ed72007-08-26 05:39:26 +00001142 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +00001143 if (const ComplexType *CT = V->getType()->getAsComplexType())
1144 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +00001145
1146 // Otherwise they pass through real integer and floating point types here.
1147 if (V->getType()->isArithmeticType())
1148 return V->getType();
1149
1150 // Reject anything else.
Chris Lattnerd1625842008-11-24 06:25:27 +00001151 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnercc26ed72007-08-26 05:39:26 +00001152 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001153}
1154
1155
Reid Spencer5f016e22007-07-11 17:01:13 +00001156
Sebastian Redl0eb23302009-01-19 00:08:26 +00001157Action::OwningExprResult
1158Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1159 tok::TokenKind Kind, ExprArg Input) {
1160 Expr *Arg = (Expr *)Input.get();
Douglas Gregor74253732008-11-19 15:42:04 +00001161
Reid Spencer5f016e22007-07-11 17:01:13 +00001162 UnaryOperator::Opcode Opc;
1163 switch (Kind) {
1164 default: assert(0 && "Unknown unary op!");
1165 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1166 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1167 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001168
Douglas Gregor74253732008-11-19 15:42:04 +00001169 if (getLangOptions().CPlusPlus &&
1170 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1171 // Which overloaded operator?
Sebastian Redl0eb23302009-01-19 00:08:26 +00001172 OverloadedOperatorKind OverOp =
Douglas Gregor74253732008-11-19 15:42:04 +00001173 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1174
1175 // C++ [over.inc]p1:
1176 //
1177 // [...] If the function is a member function with one
1178 // parameter (which shall be of type int) or a non-member
1179 // function with two parameters (the second of which shall be
1180 // of type int), it defines the postfix increment operator ++
1181 // for objects of that type. When the postfix increment is
1182 // called as a result of using the ++ operator, the int
1183 // argument will have value zero.
1184 Expr *Args[2] = {
1185 Arg,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001186 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1187 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor74253732008-11-19 15:42:04 +00001188 };
1189
1190 // Build the candidate set for overloading
1191 OverloadCandidateSet CandidateSet;
Douglas Gregorf680a0f2009-02-04 16:44:47 +00001192 if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet))
1193 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001194
1195 // Perform overload resolution.
1196 OverloadCandidateSet::iterator Best;
1197 switch (BestViableFunction(CandidateSet, Best)) {
1198 case OR_Success: {
1199 // We found a built-in operator or an overloaded operator.
1200 FunctionDecl *FnDecl = Best->Function;
1201
1202 if (FnDecl) {
1203 // We matched an overloaded operator. Build a call to that
1204 // operator.
1205
1206 // Convert the arguments.
1207 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1208 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001209 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001210 } else {
1211 // Convert the arguments.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001212 if (PerformCopyInitialization(Arg,
Douglas Gregor74253732008-11-19 15:42:04 +00001213 FnDecl->getParamDecl(0)->getType(),
1214 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001215 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001216 }
1217
1218 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00001219 QualType ResultTy
Douglas Gregor74253732008-11-19 15:42:04 +00001220 = FnDecl->getType()->getAsFunctionType()->getResultType();
1221 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001222
Douglas Gregor74253732008-11-19 15:42:04 +00001223 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001224 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor74253732008-11-19 15:42:04 +00001225 SourceLocation());
1226 UsualUnaryConversions(FnExpr);
1227
Sebastian Redl0eb23302009-01-19 00:08:26 +00001228 Input.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001229 return Owned(new (Context)CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy,
Steve Naroff0a473932009-01-20 19:53:53 +00001230 OpLoc));
Douglas Gregor74253732008-11-19 15:42:04 +00001231 } else {
1232 // We matched a built-in operator. Convert the arguments, then
1233 // break out so that we will build the appropriate built-in
1234 // operator node.
1235 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1236 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001237 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001238
1239 break;
Sebastian Redl0eb23302009-01-19 00:08:26 +00001240 }
Douglas Gregor74253732008-11-19 15:42:04 +00001241 }
1242
1243 case OR_No_Viable_Function:
1244 // No viable function; fall through to handling this as a
1245 // built-in operator, which will produce an error message for us.
1246 break;
1247
1248 case OR_Ambiguous:
1249 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1250 << UnaryOperator::getOpcodeStr(Opc)
1251 << Arg->getSourceRange();
1252 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001253 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001254 }
1255
1256 // Either we found no viable overloaded operator or we matched a
1257 // built-in operator. In either case, fall through to trying to
1258 // build a built-in operation.
1259 }
1260
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00001261 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1262 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001263 if (result.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001264 return ExprError();
1265 Input.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001266 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001267}
1268
Sebastian Redl0eb23302009-01-19 00:08:26 +00001269Action::OwningExprResult
1270Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1271 ExprArg Idx, SourceLocation RLoc) {
1272 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1273 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner12d9ff62007-07-16 00:14:47 +00001274
Douglas Gregor337c6b92008-11-19 17:17:41 +00001275 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00001276 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00001277 LHSExp->getType()->isEnumeralType() ||
1278 RHSExp->getType()->isRecordType() ||
1279 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor337c6b92008-11-19 17:17:41 +00001280 // Add the appropriate overloaded operators (C++ [over.match.oper])
1281 // to the candidate set.
1282 OverloadCandidateSet CandidateSet;
1283 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregorf680a0f2009-02-04 16:44:47 +00001284 if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1285 SourceRange(LLoc, RLoc)))
1286 return ExprError();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001287
Douglas Gregor337c6b92008-11-19 17:17:41 +00001288 // Perform overload resolution.
1289 OverloadCandidateSet::iterator Best;
1290 switch (BestViableFunction(CandidateSet, Best)) {
1291 case OR_Success: {
1292 // We found a built-in operator or an overloaded operator.
1293 FunctionDecl *FnDecl = Best->Function;
1294
1295 if (FnDecl) {
1296 // We matched an overloaded operator. Build a call to that
1297 // operator.
1298
1299 // Convert the arguments.
1300 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1301 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1302 PerformCopyInitialization(RHSExp,
1303 FnDecl->getParamDecl(0)->getType(),
1304 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001305 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001306 } else {
1307 // Convert the arguments.
1308 if (PerformCopyInitialization(LHSExp,
1309 FnDecl->getParamDecl(0)->getType(),
1310 "passing") ||
1311 PerformCopyInitialization(RHSExp,
1312 FnDecl->getParamDecl(1)->getType(),
1313 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001314 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001315 }
1316
1317 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00001318 QualType ResultTy
Douglas Gregor337c6b92008-11-19 17:17:41 +00001319 = FnDecl->getType()->getAsFunctionType()->getResultType();
1320 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001321
Douglas Gregor337c6b92008-11-19 17:17:41 +00001322 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001323 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor337c6b92008-11-19 17:17:41 +00001324 SourceLocation());
1325 UsualUnaryConversions(FnExpr);
1326
Sebastian Redl0eb23302009-01-19 00:08:26 +00001327 Base.release();
1328 Idx.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001329 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, Args, 2,
1330 ResultTy, LLoc));
Douglas Gregor337c6b92008-11-19 17:17:41 +00001331 } else {
1332 // We matched a built-in operator. Convert the arguments, then
1333 // break out so that we will build the appropriate built-in
1334 // operator node.
1335 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1336 "passing") ||
1337 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1338 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001339 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001340
1341 break;
1342 }
1343 }
1344
1345 case OR_No_Viable_Function:
1346 // No viable function; fall through to handling this as a
1347 // built-in operator, which will produce an error message for us.
1348 break;
1349
1350 case OR_Ambiguous:
1351 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1352 << "[]"
1353 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1354 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001355 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001356 }
1357
1358 // Either we found no viable overloaded operator or we matched a
1359 // built-in operator. In either case, fall through to trying to
1360 // build a built-in operation.
1361 }
1362
Chris Lattner12d9ff62007-07-16 00:14:47 +00001363 // Perform default conversions.
1364 DefaultFunctionArrayConversion(LHSExp);
1365 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001366
Chris Lattner12d9ff62007-07-16 00:14:47 +00001367 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001368
Reid Spencer5f016e22007-07-11 17:01:13 +00001369 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001370 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +00001371 // in the subscript position. As a result, we need to derive the array base
1372 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001373 Expr *BaseExpr, *IndexExpr;
1374 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +00001375 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001376 BaseExpr = LHSExp;
1377 IndexExpr = RHSExp;
1378 // FIXME: need to deal with const...
1379 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +00001380 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001381 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001382 BaseExpr = RHSExp;
1383 IndexExpr = LHSExp;
1384 // FIXME: need to deal with const...
1385 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +00001386 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1387 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001388 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00001389
Chris Lattner12d9ff62007-07-16 00:14:47 +00001390 // FIXME: need to deal with const...
1391 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001392 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00001393 return ExprError(Diag(LHSExp->getLocStart(),
1394 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1395 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001396 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +00001397 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001398 return ExprError(Diag(IndexExpr->getLocStart(),
1399 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001400
Chris Lattner12d9ff62007-07-16 00:14:47 +00001401 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1402 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001403 // void (*)(int)) and pointers to incomplete types. Functions are not
1404 // objects in C99.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001405 if (!ResultType->isObjectType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001406 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001407 diag::err_typecheck_subscript_not_object)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001408 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner12d9ff62007-07-16 00:14:47 +00001409
Sebastian Redl0eb23302009-01-19 00:08:26 +00001410 Base.release();
1411 Idx.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001412 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1413 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001414}
1415
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001416QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001417CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001418 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +00001419 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +00001420
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001421 // The vector accessor can't exceed the number of elements.
1422 const char *compStr = CompName.getName();
Nate Begeman353417a2009-01-18 01:47:54 +00001423
1424 // This flag determines whether or not the component is one of the four
1425 // special names that indicate a subset of exactly half the elements are
1426 // to be selected.
1427 bool HalvingSwizzle = false;
1428
1429 // This flag determines whether or not CompName has an 's' char prefix,
1430 // indicating that it is a string of hex values to be used as vector indices.
1431 bool HexSwizzle = *compStr == 's';
Nate Begeman8a997642008-05-09 06:41:27 +00001432
1433 // Check that we've found one of the special components, or that the component
1434 // names must come from the same set.
1435 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00001436 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1437 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00001438 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001439 do
1440 compStr++;
1441 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00001442 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001443 do
1444 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001445 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00001446 }
Nate Begeman353417a2009-01-18 01:47:54 +00001447
1448 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001449 // We didn't get to the end of the string. This means the component names
1450 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001451 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1452 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001453 return QualType();
1454 }
Nate Begeman353417a2009-01-18 01:47:54 +00001455
1456 // Ensure no component accessor exceeds the width of the vector type it
1457 // operates on.
1458 if (!HalvingSwizzle) {
1459 compStr = CompName.getName();
1460
1461 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001462 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001463
1464 while (*compStr) {
1465 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1466 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1467 << baseType << SourceRange(CompLoc);
1468 return QualType();
1469 }
1470 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001471 }
Nate Begeman8a997642008-05-09 06:41:27 +00001472
Nate Begeman353417a2009-01-18 01:47:54 +00001473 // If this is a halving swizzle, verify that the base type has an even
1474 // number of elements.
1475 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001476 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00001477 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00001478 return QualType();
1479 }
1480
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001481 // The component accessor looks fine - now we need to compute the actual type.
1482 // The vector type is implied by the component accessor. For example,
1483 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00001484 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00001485 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman353417a2009-01-18 01:47:54 +00001486 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1487 : CompName.getLength();
1488 if (HexSwizzle)
1489 CompSize--;
1490
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001491 if (CompSize == 1)
1492 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +00001493
Nate Begeman213541a2008-04-18 23:10:10 +00001494 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroffbea0b342007-07-29 16:33:31 +00001495 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00001496 // diagostics look bad. We want extended vector types to appear built-in.
1497 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1498 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1499 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00001500 }
1501 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001502}
1503
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001504/// constructSetterName - Return the setter name for the given
1505/// identifier, i.e. "set" + Name where the initial character of Name
1506/// has been capitalized.
1507// FIXME: Merge with same routine in Parser. But where should this
1508// live?
1509static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1510 const IdentifierInfo *Name) {
1511 llvm::SmallString<100> SelectorName;
1512 SelectorName = "set";
1513 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1514 SelectorName[3] = toupper(SelectorName[3]);
1515 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1516}
1517
Sebastian Redl0eb23302009-01-19 00:08:26 +00001518Action::OwningExprResult
1519Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1520 tok::TokenKind OpKind, SourceLocation MemberLoc,
1521 IdentifierInfo &Member) {
1522 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001523 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +00001524
1525 // Perform default conversions.
1526 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001527
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001528 QualType BaseType = BaseExpr->getType();
1529 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00001530
Chris Lattner68a057b2008-07-21 04:36:39 +00001531 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1532 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +00001533 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +00001534 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001535 BaseType = PT->getPointeeType();
Douglas Gregor8ba10742008-11-20 16:27:02 +00001536 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001537 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1538 MemberLoc, Member));
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001539 else
Sebastian Redl0eb23302009-01-19 00:08:26 +00001540 return ExprError(Diag(MemberLoc,
1541 diag::err_typecheck_member_reference_arrow)
1542 << BaseType << BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001543 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001544
Chris Lattner68a057b2008-07-21 04:36:39 +00001545 // Handle field access to simple records. This also handles access to fields
1546 // of the ObjC 'id' struct.
Chris Lattnerc8629632007-07-31 19:29:30 +00001547 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001548 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00001549 if (DiagnoseIncompleteType(OpLoc, BaseType,
1550 diag::err_typecheck_incomplete_tag,
1551 BaseExpr->getSourceRange()))
1552 return ExprError();
1553
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001554 // The record definition is complete, now make sure the member is valid.
Douglas Gregor44b43212008-12-11 16:49:14 +00001555 // FIXME: Qualified name lookup for C++ is a bit more complicated
1556 // than this.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001557 LookupResult Result
Douglas Gregor7176fff2009-01-15 00:26:24 +00001558 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001559 LookupMemberName, false);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001560
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001561 NamedDecl *MemberDecl = 0;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001562 if (!Result)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001563 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1564 << &Member << BaseExpr->getSourceRange());
1565 else if (Result.isAmbiguous()) {
1566 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1567 MemberLoc, BaseExpr->getSourceRange());
1568 return ExprError();
1569 } else
Douglas Gregor7176fff2009-01-15 00:26:24 +00001570 MemberDecl = Result;
Douglas Gregor44b43212008-12-11 16:49:14 +00001571
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001572 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001573 // We may have found a field within an anonymous union or struct
1574 // (C++ [class.union]).
1575 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001576 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001577 BaseExpr, OpLoc);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001578
Douglas Gregor86f19402008-12-20 23:49:58 +00001579 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1580 // FIXME: Handle address space modifiers
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001581 QualType MemberType = FD->getType();
Douglas Gregor86f19402008-12-20 23:49:58 +00001582 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1583 MemberType = Ref->getPointeeType();
1584 else {
1585 unsigned combinedQualifiers =
1586 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001587 if (FD->isMutable())
Douglas Gregor86f19402008-12-20 23:49:58 +00001588 combinedQualifiers &= ~QualType::Const;
1589 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1590 }
Eli Friedman51019072008-02-06 22:48:16 +00001591
Steve Naroff6ece14c2009-01-21 00:14:39 +00001592 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1593 MemberLoc, MemberType));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001594 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001595 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001596 Var, MemberLoc,
1597 Var->getType().getNonReferenceType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001598 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001599 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1600 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00001601 else if (OverloadedFunctionDecl *Ovl
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001602 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001603 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001604 MemberLoc, Context.OverloadTy));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001605 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001606 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Enum,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001607 MemberLoc, Enum->getType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001608 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001609 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1610 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman51019072008-02-06 22:48:16 +00001611
Douglas Gregor86f19402008-12-20 23:49:58 +00001612 // We found a declaration kind that we didn't expect. This is a
1613 // generic error message that tells the user that she can't refer
1614 // to this member with '.' or '->'.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001615 return ExprError(Diag(MemberLoc,
1616 diag::err_typecheck_member_reference_unknown)
1617 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001618 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001619
Chris Lattnera38e6b12008-07-21 04:59:05 +00001620 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1621 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +00001622 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00001623 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Steve Naroff6ece14c2009-01-21 00:14:39 +00001624 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1625 MemberLoc, BaseExpr,
Fariborz Jahanianefc4c4b2008-12-18 17:29:46 +00001626 OpKind == tok::arrow);
1627 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001628 return Owned(MRef);
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00001629 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001630 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1631 << IFTy->getDecl()->getDeclName() << &Member
1632 << BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001633 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001634
Chris Lattnera38e6b12008-07-21 04:59:05 +00001635 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1636 // pointer to a (potentially qualified) interface type.
1637 const PointerType *PTy;
1638 const ObjCInterfaceType *IFTy;
1639 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1640 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1641 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001642
Daniel Dunbar2307d312008-09-03 01:05:41 +00001643 // Search for a declared property first.
Chris Lattnera38e6b12008-07-21 04:59:05 +00001644 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001645 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl0eb23302009-01-19 00:08:26 +00001646 MemberLoc, BaseExpr));
1647
Daniel Dunbar2307d312008-09-03 01:05:41 +00001648 // Check protocols on qualified interfaces.
Chris Lattner9baefc22008-07-21 05:20:01 +00001649 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1650 E = IFTy->qual_end(); I != E; ++I)
1651 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001652 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl0eb23302009-01-19 00:08:26 +00001653 MemberLoc, BaseExpr));
Daniel Dunbar2307d312008-09-03 01:05:41 +00001654
1655 // If that failed, look for an "implicit" property by seeing if the nullary
1656 // selector is implemented.
1657
1658 // FIXME: The logic for looking up nullary and unary selectors should be
1659 // shared with the code in ActOnInstanceMessage.
1660
1661 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1662 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001663
Daniel Dunbar2307d312008-09-03 01:05:41 +00001664 // If this reference is in an @implementation, check for 'private' methods.
1665 if (!Getter)
1666 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1667 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1668 if (ObjCImplementationDecl *ImpDecl =
1669 ObjCImplementations[ClassDecl->getIdentifier()])
1670 Getter = ImpDecl->getInstanceMethod(Sel);
1671
Steve Naroff7692ed62008-10-22 19:16:27 +00001672 // Look through local category implementations associated with the class.
1673 if (!Getter) {
1674 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1675 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1676 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1677 }
1678 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00001679 if (Getter) {
1680 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001681 // will look for the matching setter, in case it is needed.
1682 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1683 &Member);
1684 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1685 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1686 if (!Setter) {
1687 // If this reference is in an @implementation, also check for 'private'
1688 // methods.
1689 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1690 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1691 if (ObjCImplementationDecl *ImpDecl =
1692 ObjCImplementations[ClassDecl->getIdentifier()])
1693 Setter = ImpDecl->getInstanceMethod(SetterSel);
1694 }
1695 // Look through local category implementations associated with the class.
1696 if (!Setter) {
1697 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1698 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1699 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1700 }
1701 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001702
1703 // FIXME: we must check that the setter has property type.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001704 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
1705 Setter, MemberLoc, BaseExpr));
Daniel Dunbar2307d312008-09-03 01:05:41 +00001706 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001707
1708 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1709 << &Member << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00001710 }
Steve Naroff18bc1642008-10-20 22:53:06 +00001711 // Handle properties on qualified "id" protocols.
1712 const ObjCQualifiedIdType *QIdTy;
1713 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1714 // Check protocols on qualified interfaces.
1715 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001716 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroff18bc1642008-10-20 22:53:06 +00001717 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001718 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl0eb23302009-01-19 00:08:26 +00001719 MemberLoc, BaseExpr));
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001720 // Also must look for a getter name which uses property syntax.
1721 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1722 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Steve Naroff6ece14c2009-01-21 00:14:39 +00001723 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
1724 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001725 }
1726 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001727
1728 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1729 << &Member << BaseType);
1730 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001731 // Handle 'field access' to vectors, such as 'V.xx'.
1732 if (BaseType->isExtVectorType() && OpKind == tok::period) {
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001733 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1734 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001735 return ExprError();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001736 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
1737 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001738 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001739
1740 return ExprError(Diag(MemberLoc,
1741 diag::err_typecheck_member_reference_struct_union)
1742 << BaseType << BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001743}
1744
Douglas Gregor88a35142008-12-22 05:46:06 +00001745/// ConvertArgumentsForCall - Converts the arguments specified in
1746/// Args/NumArgs to the parameter types of the function FDecl with
1747/// function prototype Proto. Call is the call expression itself, and
1748/// Fn is the function expression. For a C++ member function, this
1749/// routine does not attempt to convert the object argument. Returns
1750/// true if the call is ill-formed.
1751bool
1752Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1753 FunctionDecl *FDecl,
1754 const FunctionTypeProto *Proto,
1755 Expr **Args, unsigned NumArgs,
1756 SourceLocation RParenLoc) {
1757 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1758 // assignment, to the types of the corresponding parameter, ...
1759 unsigned NumArgsInProto = Proto->getNumArgs();
1760 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor3fd56d72009-01-23 21:30:56 +00001761 bool Invalid = false;
1762
Douglas Gregor88a35142008-12-22 05:46:06 +00001763 // If too few arguments are available (and we don't have default
1764 // arguments for the remaining parameters), don't make the call.
1765 if (NumArgs < NumArgsInProto) {
1766 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1767 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1768 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1769 // Use default arguments for missing arguments
1770 NumArgsToCheck = NumArgsInProto;
1771 Call->setNumArgs(NumArgsInProto);
1772 }
1773
1774 // If too many are passed and not variadic, error on the extras and drop
1775 // them.
1776 if (NumArgs > NumArgsInProto) {
1777 if (!Proto->isVariadic()) {
1778 Diag(Args[NumArgsInProto]->getLocStart(),
1779 diag::err_typecheck_call_too_many_args)
1780 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1781 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1782 Args[NumArgs-1]->getLocEnd());
1783 // This deletes the extra arguments.
1784 Call->setNumArgs(NumArgsInProto);
Douglas Gregor3fd56d72009-01-23 21:30:56 +00001785 Invalid = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00001786 }
1787 NumArgsToCheck = NumArgsInProto;
1788 }
1789
1790 // Continue to check argument types (even if we have too few/many args).
1791 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1792 QualType ProtoArgType = Proto->getArgType(i);
1793
1794 Expr *Arg;
Douglas Gregor61366e92008-12-24 00:01:03 +00001795 if (i < NumArgs) {
Douglas Gregor88a35142008-12-22 05:46:06 +00001796 Arg = Args[i];
Douglas Gregor61366e92008-12-24 00:01:03 +00001797
1798 // Pass the argument.
1799 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1800 return true;
1801 } else
1802 // We already type-checked the argument, so we know it works.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001803 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor88a35142008-12-22 05:46:06 +00001804 QualType ArgType = Arg->getType();
Douglas Gregor61366e92008-12-24 00:01:03 +00001805
Douglas Gregor88a35142008-12-22 05:46:06 +00001806 Call->setArg(i, Arg);
1807 }
1808
1809 // If this is a variadic call, handle args passed through "...".
1810 if (Proto->isVariadic()) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +00001811 VariadicCallType CallType = VariadicFunction;
1812 if (Fn->getType()->isBlockPointerType())
1813 CallType = VariadicBlock; // Block
1814 else if (isa<MemberExpr>(Fn))
1815 CallType = VariadicMethod;
1816
Douglas Gregor88a35142008-12-22 05:46:06 +00001817 // Promote the arguments (C99 6.5.2.2p7).
1818 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1819 Expr *Arg = Args[i];
Anders Carlssondce5e2c2009-01-16 16:48:51 +00001820 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor88a35142008-12-22 05:46:06 +00001821 Call->setArg(i, Arg);
1822 }
1823 }
1824
Douglas Gregor3fd56d72009-01-23 21:30:56 +00001825 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00001826}
1827
Steve Narofff69936d2007-09-16 03:34:24 +00001828/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00001829/// This provides the location of the left/right parens and a list of comma
1830/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001831Action::OwningExprResult
1832Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1833 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00001834 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00001835 unsigned NumArgs = args.size();
1836 Expr *Fn = static_cast<Expr *>(fn.release());
1837 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00001838 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00001839 FunctionDecl *FDecl = NULL;
Douglas Gregor17330012009-02-04 15:01:18 +00001840 DeclarationName UnqualifiedName;
Douglas Gregor88a35142008-12-22 05:46:06 +00001841
Douglas Gregor88a35142008-12-22 05:46:06 +00001842 if (getLangOptions().CPlusPlus) {
Douglas Gregor17330012009-02-04 15:01:18 +00001843 // Determine whether this is a dependent call inside a C++ template,
1844 // in which case we won't do any semantic analysis now.
1845 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
1846 bool Dependent = false;
1847 if (Fn->isTypeDependent())
1848 Dependent = true;
1849 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1850 Dependent = true;
1851
1852 if (Dependent)
1853 return Owned(new (Context) CallExpr(Fn, Args, NumArgs,
1854 Context.DependentTy, RParenLoc));
1855
1856 // Determine whether this is a call to an object (C++ [over.call.object]).
1857 if (Fn->getType()->isRecordType())
1858 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1859 CommaLocs, RParenLoc));
1860
Douglas Gregorfa047642009-02-04 00:32:51 +00001861 // Determine whether this is a call to a member function.
Douglas Gregor88a35142008-12-22 05:46:06 +00001862 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1863 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1864 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001865 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1866 CommaLocs, RParenLoc));
Douglas Gregor88a35142008-12-22 05:46:06 +00001867 }
1868
Douglas Gregorfa047642009-02-04 00:32:51 +00001869 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor1a49af92009-01-06 05:10:23 +00001870 DeclRefExpr *DRExpr = NULL;
Douglas Gregorfa047642009-02-04 00:32:51 +00001871 Expr *FnExpr = Fn;
1872 bool ADL = true;
1873 while (true) {
1874 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
1875 FnExpr = IcExpr->getSubExpr();
1876 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Douglas Gregor17330012009-02-04 15:01:18 +00001877 // Parentheses around a function disable ADL
1878 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregorfa047642009-02-04 00:32:51 +00001879 ADL = false;
1880 FnExpr = PExpr->getSubExpr();
1881 } else if (isa<UnaryOperator>(FnExpr) &&
1882 cast<UnaryOperator>(FnExpr)->getOpcode()
1883 == UnaryOperator::AddrOf) {
1884 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
1885 } else {
Douglas Gregor17330012009-02-04 15:01:18 +00001886 if (isa<DeclRefExpr>(FnExpr)) {
1887 DRExpr = cast<DeclRefExpr>(FnExpr);
1888
1889 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
1890 ADL = ADL && !isa<QualifiedDeclRefExpr>(DRExpr);
1891 }
1892 else if (UnresolvedFunctionNameExpr *DepName
1893 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr))
1894 UnqualifiedName = DepName->getName();
1895 else {
1896 // Any kind of name that does not refer to a declaration (or
1897 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
1898 ADL = false;
1899 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001900 break;
1901 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001902 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001903
Douglas Gregor17330012009-02-04 15:01:18 +00001904 OverloadedFunctionDecl *Ovl = 0;
1905 if (DRExpr) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001906 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor17330012009-02-04 15:01:18 +00001907 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1908 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001909
Douglas Gregor17330012009-02-04 15:01:18 +00001910 if (getLangOptions().CPlusPlus && (FDecl || Ovl || UnqualifiedName)) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001911 // We don't perform ADL for builtins.
1912 if (FDecl && FDecl->getIdentifier() &&
1913 FDecl->getIdentifier()->getBuiltinID())
1914 ADL = false;
1915
Douglas Gregor17330012009-02-04 15:01:18 +00001916 if (Ovl || ADL) {
1917 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
1918 UnqualifiedName, LParenLoc, Args,
Douglas Gregorfa047642009-02-04 00:32:51 +00001919 NumArgs, CommaLocs, RParenLoc, ADL);
1920 if (!FDecl)
1921 return ExprError();
1922
1923 // Update Fn to refer to the actual function selected.
1924 Expr *NewFn = 0;
1925 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor17330012009-02-04 15:01:18 +00001926 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Douglas Gregorfa047642009-02-04 00:32:51 +00001927 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
1928 QDRExpr->getLocation(),
1929 false, false,
1930 QDRExpr->getSourceRange().getBegin());
1931 else
1932 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
1933 Fn->getSourceRange().getBegin());
1934 Fn->Destroy(Context);
1935 Fn = NewFn;
1936 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001937 }
Chris Lattner04421082008-04-08 04:40:51 +00001938
1939 // Promote the function operand.
1940 UsualUnaryConversions(Fn);
1941
Chris Lattner925e60d2007-12-28 05:29:59 +00001942 // Make the call expr early, before semantic checks. This guarantees cleanup
1943 // of arguments and function on error.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001944 // FIXME: Except that llvm::OwningPtr uses delete, when it really must be
1945 // Destroy(), or nothing gets cleaned up.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001946 llvm::OwningPtr<CallExpr> TheCall(new (Context) CallExpr(Fn, Args, NumArgs,
Chris Lattner925e60d2007-12-28 05:29:59 +00001947 Context.BoolTy, RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00001948
Steve Naroffdd972f22008-09-05 22:11:13 +00001949 const FunctionType *FuncT;
1950 if (!Fn->getType()->isBlockPointerType()) {
1951 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1952 // have type pointer to function".
1953 const PointerType *PT = Fn->getType()->getAsPointerType();
1954 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001955 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1956 << Fn->getType() << Fn->getSourceRange());
Steve Naroffdd972f22008-09-05 22:11:13 +00001957 FuncT = PT->getPointeeType()->getAsFunctionType();
1958 } else { // This is a block call.
1959 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1960 getAsFunctionType();
1961 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001962 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001963 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1964 << Fn->getType() << Fn->getSourceRange());
1965
Chris Lattner925e60d2007-12-28 05:29:59 +00001966 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001967 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001968
Chris Lattner925e60d2007-12-28 05:29:59 +00001969 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00001970 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
1971 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001972 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00001973 } else {
1974 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00001975
Steve Naroffb291ab62007-08-28 23:30:39 +00001976 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00001977 for (unsigned i = 0; i != NumArgs; i++) {
1978 Expr *Arg = Args[i];
1979 DefaultArgumentPromotion(Arg);
1980 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001981 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001982 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001983
Douglas Gregor88a35142008-12-22 05:46:06 +00001984 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
1985 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001986 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
1987 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00001988
Chris Lattner59907c42007-08-10 20:18:51 +00001989 // Do special checking on direct calls to functions.
Eli Friedmand38617c2008-05-14 19:38:39 +00001990 if (FDecl)
1991 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +00001992
Sebastian Redl0eb23302009-01-19 00:08:26 +00001993 return Owned(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00001994}
1995
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001996Action::OwningExprResult
1997Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
1998 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00001999 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +00002000 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00002001 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00002002 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002003 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00002004
Eli Friedman6223c222008-05-20 05:22:08 +00002005 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002006 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002007 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2008 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002009 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2010 diag::err_typecheck_decl_incomplete_type,
2011 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002012 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00002013
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002014 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002015 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002016 return ExprError();
Steve Naroffe9b12192008-01-14 18:19:28 +00002017
Chris Lattner371f2582008-12-04 23:50:19 +00002018 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00002019 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00002020 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002021 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002022 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002023 InitExpr.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00002024 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
2025 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00002026}
2027
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002028Action::OwningExprResult
2029Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2030 InitListDesignations &Designators,
2031 SourceLocation RBraceLoc) {
2032 unsigned NumInit = initlist.size();
2033 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00002034
Steve Naroff08d92e42007-09-15 18:49:24 +00002035 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +00002036 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002037
Steve Naroff6ece14c2009-01-21 00:14:39 +00002038 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00002039 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002040 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002041 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00002042}
2043
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002044/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar58d5ebb2008-08-20 03:55:42 +00002045bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002046 UsualUnaryConversions(castExpr);
2047
2048 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2049 // type needs to be scalar.
2050 if (castType->isVoidType()) {
2051 // Cast to void allows any expr type.
Douglas Gregor898574e2008-12-05 23:32:09 +00002052 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2053 // We can't check any more until template instantiation time.
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002054 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00002055 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2056 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2057 (castType->isStructureType() || castType->isUnionType())) {
2058 // GCC struct/union extension: allow cast to self.
2059 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2060 << castType << castExpr->getSourceRange();
2061 } else if (castType->isUnionType()) {
2062 // GCC cast to union extension
2063 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2064 RecordDecl::field_iterator Field, FieldEnd;
2065 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2066 Field != FieldEnd; ++Field) {
2067 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2068 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2069 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2070 << castExpr->getSourceRange();
2071 break;
2072 }
2073 }
2074 if (Field == FieldEnd)
2075 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2076 << castExpr->getType() << castExpr->getSourceRange();
2077 } else {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002078 // Reject any other conversions to non-scalar types.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002079 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00002080 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002081 }
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002082 } else if (!castExpr->getType()->isScalarType() &&
2083 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002084 return Diag(castExpr->getLocStart(),
2085 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00002086 << castExpr->getType() << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002087 } else if (castExpr->getType()->isVectorType()) {
2088 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2089 return true;
2090 } else if (castType->isVectorType()) {
2091 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2092 return true;
2093 }
2094 return false;
2095}
2096
Chris Lattnerfe23e212007-12-20 00:44:32 +00002097bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00002098 assert(VectorTy->isVectorType() && "Not a vector type!");
2099
2100 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00002101 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00002102 return Diag(R.getBegin(),
2103 Ty->isVectorType() ?
2104 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002105 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002106 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00002107 } else
2108 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002109 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00002110 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00002111
2112 return false;
2113}
2114
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002115Action::OwningExprResult
2116Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2117 SourceLocation RParenLoc, ExprArg Op) {
2118 assert((Ty != 0) && (Op.get() != 0) &&
2119 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00002120
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002121 Expr *castExpr = static_cast<Expr*>(Op.release());
Steve Naroff16beff82007-07-16 23:25:18 +00002122 QualType castType = QualType::getFromOpaquePtr(Ty);
2123
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002124 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002125 return ExprError();
Steve Naroff6ece14c2009-01-21 00:14:39 +00002126 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002127 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002128}
2129
Chris Lattnera21ddb32007-11-26 01:40:58 +00002130/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2131/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +00002132inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +00002133 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002134 UsualUnaryConversions(cond);
2135 UsualUnaryConversions(lex);
2136 UsualUnaryConversions(rex);
2137 QualType condT = cond->getType();
2138 QualType lexT = lex->getType();
2139 QualType rexT = rex->getType();
2140
Reid Spencer5f016e22007-07-11 17:01:13 +00002141 // first, check the condition.
Douglas Gregor898574e2008-12-05 23:32:09 +00002142 if (!cond->isTypeDependent()) {
2143 if (!condT->isScalarType()) { // C99 6.5.15p2
2144 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
2145 return QualType();
2146 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002147 }
Chris Lattner70d67a92008-01-06 22:42:25 +00002148
2149 // Now check the two expressions.
Douglas Gregor898574e2008-12-05 23:32:09 +00002150 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
2151 return Context.DependentTy;
2152
Chris Lattner70d67a92008-01-06 22:42:25 +00002153 // If both operands have arithmetic type, do the usual arithmetic conversions
2154 // to find a common type: C99 6.5.15p3,5.
2155 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Steve Naroffa4332e22007-07-17 00:58:39 +00002156 UsualArithmeticConversions(lex, rex);
2157 return lex->getType();
2158 }
Chris Lattner70d67a92008-01-06 22:42:25 +00002159
2160 // If both operands are the same structure or union type, the result is that
2161 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002162 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner70d67a92008-01-06 22:42:25 +00002163 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +00002164 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner70d67a92008-01-06 22:42:25 +00002165 // "If both the operands have structure or union type, the result has
2166 // that type." This implies that CV qualifiers are dropped.
2167 return lexT.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002168 }
Chris Lattner70d67a92008-01-06 22:42:25 +00002169
2170 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00002171 // The following || allows only one side to be void (a GCC-ism).
2172 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedman0e724012008-06-04 19:47:51 +00002173 if (!lexT->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002174 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2175 << rex->getSourceRange();
Steve Naroffe701c0a2008-05-12 21:44:38 +00002176 if (!rexT->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002177 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2178 << lex->getSourceRange();
Eli Friedman0e724012008-06-04 19:47:51 +00002179 ImpCastExprToType(lex, Context.VoidTy);
2180 ImpCastExprToType(rex, Context.VoidTy);
2181 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00002182 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00002183 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2184 // the type of the other operand."
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002185 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2186 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssond2652772008-12-01 06:28:23 +00002187 rex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002188 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00002189 return lexT;
2190 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002191 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2192 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssond2652772008-12-01 06:28:23 +00002193 lex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002194 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00002195 return rexT;
2196 }
Chris Lattnerbd57d362008-01-06 22:50:31 +00002197 // Handle the case where both operands are pointers before we handle null
2198 // pointer constants in case both operands are null pointer constants.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002199 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2200 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2201 // get the "pointed to" types
2202 QualType lhptee = LHSPT->getPointeeType();
2203 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002204
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002205 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2206 if (lhptee->isVoidType() &&
Chris Lattnerd805bec2008-04-02 06:59:01 +00002207 rhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00002208 // Figure out necessary qualifiers (C99 6.5.15p6)
2209 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00002210 QualType destType = Context.getPointerType(destPointee);
2211 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2212 ImpCastExprToType(rex, destType); // promote to void*
2213 return destType;
2214 }
Chris Lattnerd805bec2008-04-02 06:59:01 +00002215 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00002216 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00002217 QualType destType = Context.getPointerType(destPointee);
2218 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2219 ImpCastExprToType(rex, destType); // promote to void*
2220 return destType;
2221 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002222
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002223 QualType compositeType = lexT;
2224
2225 // If either type is an Objective-C object type then check
2226 // compatibility according to Objective-C.
2227 if (Context.isObjCObjectPointerType(lexT) ||
2228 Context.isObjCObjectPointerType(rexT)) {
2229 // If both operands are interfaces and either operand can be
2230 // assigned to the other, use that type as the composite
2231 // type. This allows
2232 // xxx ? (A*) a : (B*) b
2233 // where B is a subclass of A.
2234 //
2235 // Additionally, as for assignment, if either type is 'id'
2236 // allow silent coercion. Finally, if the types are
2237 // incompatible then make sure to use 'id' as the composite
2238 // type so the result is acceptable for sending messages to.
2239
2240 // FIXME: This code should not be localized to here. Also this
2241 // should use a compatible check instead of abusing the
2242 // canAssignObjCInterfaces code.
2243 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2244 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2245 if (LHSIface && RHSIface &&
2246 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2247 compositeType = lexT;
2248 } else if (LHSIface && RHSIface &&
Douglas Gregor7ffd0de2008-11-26 06:43:45 +00002249 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002250 compositeType = rexT;
2251 } else if (Context.isObjCIdType(lhptee) ||
2252 Context.isObjCIdType(rhptee)) {
2253 // FIXME: This code looks wrong, because isObjCIdType checks
2254 // the struct but getObjCIdType returns the pointer to
2255 // struct. This is horrible and should be fixed.
2256 compositeType = Context.getObjCIdType();
2257 } else {
2258 QualType incompatTy = Context.getObjCIdType();
2259 ImpCastExprToType(lex, incompatTy);
2260 ImpCastExprToType(rex, incompatTy);
2261 return incompatTy;
2262 }
2263 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2264 rhptee.getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002265 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00002266 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002267 // In this situation, we assume void* type. No especially good
2268 // reason, but this is what gcc does, and we do have to pick
2269 // to get a consistent AST.
2270 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbara56f7462008-08-26 00:41:39 +00002271 ImpCastExprToType(lex, incompatTy);
2272 ImpCastExprToType(rex, incompatTy);
2273 return incompatTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002274 }
2275 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002276 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2277 // differently qualified versions of compatible types, the result type is
2278 // a pointer to an appropriately qualified version of the *composite*
2279 // type.
Eli Friedman5835ea22008-05-16 20:37:07 +00002280 // FIXME: Need to calculate the composite type.
Eli Friedmana541d532008-02-10 22:59:36 +00002281 // FIXME: Need to add qualifiers
Eli Friedman5835ea22008-05-16 20:37:07 +00002282 ImpCastExprToType(lex, compositeType);
2283 ImpCastExprToType(rex, compositeType);
2284 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002285 }
2286 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002287 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2288 // evaluates to "struct objc_object *" (and is handled above when comparing
2289 // id with statically typed objects).
2290 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2291 // GCC allows qualified id and any Objective-C type to devolve to
2292 // id. Currently localizing to here until clear this should be
2293 // part of ObjCQualifiedIdTypesAreCompatible.
2294 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2295 (lexT->isObjCQualifiedIdType() &&
2296 Context.isObjCObjectPointerType(rexT)) ||
2297 (rexT->isObjCQualifiedIdType() &&
2298 Context.isObjCObjectPointerType(lexT))) {
2299 // FIXME: This is not the correct composite type. This only
2300 // happens to work because id can more or less be used anywhere,
2301 // however this may change the type of method sends.
2302 // FIXME: gcc adds some type-checking of the arguments and emits
2303 // (confusing) incompatible comparison warnings in some
2304 // cases. Investigate.
2305 QualType compositeType = Context.getObjCIdType();
2306 ImpCastExprToType(lex, compositeType);
2307 ImpCastExprToType(rex, compositeType);
2308 return compositeType;
2309 }
2310 }
2311
Steve Naroff61f40a22008-09-10 19:17:48 +00002312 // Selection between block pointer types is ok as long as they are the same.
2313 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2314 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2315 return lexT;
2316
Chris Lattner70d67a92008-01-06 22:42:25 +00002317 // Otherwise, the operands are not compatible.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002318 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattnerd1625842008-11-24 06:25:27 +00002319 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002320 return QualType();
2321}
2322
Steve Narofff69936d2007-09-16 03:34:24 +00002323/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00002324/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002325Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2326 SourceLocation ColonLoc,
2327 ExprArg Cond, ExprArg LHS,
2328 ExprArg RHS) {
2329 Expr *CondExpr = (Expr *) Cond.get();
2330 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00002331
2332 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2333 // was the condition.
2334 bool isLHSNull = LHSExpr == 0;
2335 if (isLHSNull)
2336 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002337
2338 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00002339 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002340 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002341 return ExprError();
2342
2343 Cond.release();
2344 LHS.release();
2345 RHS.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00002346 return Owned(new (Context) ConditionalOperator(CondExpr,
2347 isLHSNull ? 0 : LHSExpr,
2348 RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00002349}
2350
Reid Spencer5f016e22007-07-11 17:01:13 +00002351
2352// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2353// being closely modeled after the C99 spec:-). The odd characteristic of this
2354// routine is it effectively iqnores the qualifiers on the top level pointee.
2355// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2356// FIXME: add a couple examples in this comment.
Chris Lattner5cf216b2008-01-04 18:04:52 +00002357Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00002358Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2359 QualType lhptee, rhptee;
2360
2361 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002362 lhptee = lhsType->getAsPointerType()->getPointeeType();
2363 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002364
2365 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00002366 lhptee = Context.getCanonicalType(lhptee);
2367 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00002368
Chris Lattner5cf216b2008-01-04 18:04:52 +00002369 AssignConvertType ConvTy = Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00002370
2371 // C99 6.5.16.1p1: This following citation is common to constraints
2372 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2373 // qualifiers of the type *pointed to* by the right;
Chris Lattnerf46699c2008-02-20 20:55:12 +00002374 // FIXME: Handle ASQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00002375 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00002376 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00002377
2378 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2379 // incomplete type and the other is a pointer to a qualified or unqualified
2380 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002381 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00002382 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00002383 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002384
2385 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00002386 assert(rhptee->isFunctionType());
2387 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002388 }
2389
2390 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00002391 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00002392 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002393
2394 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00002395 assert(lhptee->isFunctionType());
2396 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002397 }
Eli Friedman3d815e72008-08-22 00:56:42 +00002398
2399 // Check for ObjC interfaces
2400 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2401 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2402 if (LHSIface && RHSIface &&
2403 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2404 return ConvTy;
2405
2406 // ID acts sort of like void* for ObjC interfaces
2407 if (LHSIface && Context.isObjCIdType(rhptee))
2408 return ConvTy;
2409 if (RHSIface && Context.isObjCIdType(lhptee))
2410 return ConvTy;
2411
Reid Spencer5f016e22007-07-11 17:01:13 +00002412 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2413 // unqualified versions of compatible types, ...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002414 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2415 rhptee.getUnqualifiedType()))
2416 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00002417 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002418}
2419
Steve Naroff1c7d0672008-09-04 15:10:53 +00002420/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2421/// block pointer types are compatible or whether a block and normal pointer
2422/// are compatible. It is more restrict than comparing two function pointer
2423// types.
2424Sema::AssignConvertType
2425Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2426 QualType rhsType) {
2427 QualType lhptee, rhptee;
2428
2429 // get the "pointed to" type (ignoring qualifiers at the top level)
2430 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2431 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2432
2433 // make sure we operate on the canonical type
2434 lhptee = Context.getCanonicalType(lhptee);
2435 rhptee = Context.getCanonicalType(rhptee);
2436
2437 AssignConvertType ConvTy = Compatible;
2438
2439 // For blocks we enforce that qualifiers are identical.
2440 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2441 ConvTy = CompatiblePointerDiscardsQualifiers;
2442
2443 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2444 return IncompatibleBlockPointer;
2445 return ConvTy;
2446}
2447
Reid Spencer5f016e22007-07-11 17:01:13 +00002448/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2449/// has code to accommodate several GCC extensions when type checking
2450/// pointers. Here are some objectionable examples that GCC considers warnings:
2451///
2452/// int a, *pint;
2453/// short *pshort;
2454/// struct foo *pfoo;
2455///
2456/// pint = pshort; // warning: assignment from incompatible pointer type
2457/// a = pint; // warning: assignment makes integer from pointer without a cast
2458/// pint = a; // warning: assignment makes pointer from integer without a cast
2459/// pint = pfoo; // warning: assignment from incompatible pointer type
2460///
2461/// As a result, the code for dealing with pointers is more complex than the
2462/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00002463///
Chris Lattner5cf216b2008-01-04 18:04:52 +00002464Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00002465Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00002466 // Get canonical types. We're not formatting these types, just comparing
2467 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002468 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2469 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002470
2471 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00002472 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00002473
Douglas Gregor9d293df2008-10-28 00:22:11 +00002474 // If the left-hand side is a reference type, then we are in a
2475 // (rare!) case where we've allowed the use of references in C,
2476 // e.g., as a parameter type in a built-in function. In this case,
2477 // just make sure that the type referenced is compatible with the
2478 // right-hand side type. The caller is responsible for adjusting
2479 // lhsType so that the resulting expression does not have reference
2480 // type.
2481 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2482 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00002483 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002484 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002485 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002486
Chris Lattnereca7be62008-04-07 05:30:13 +00002487 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2488 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002489 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00002490 // Relax integer conversions like we do for pointers below.
2491 if (rhsType->isIntegerType())
2492 return IntToPointer;
2493 if (lhsType->isIntegerType())
2494 return PointerToInt;
Steve Naroff39579072008-10-14 22:18:38 +00002495 return IncompatibleObjCQualifiedId;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002496 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00002497
Nate Begemanbe2341d2008-07-14 18:02:46 +00002498 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002499 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00002500 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2501 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00002502 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002503
Nate Begemanbe2341d2008-07-14 18:02:46 +00002504 // If we are allowing lax vector conversions, and LHS and RHS are both
2505 // vectors, the total size only needs to be the same. This is a bitcast;
2506 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00002507 if (getLangOptions().LaxVectorConversions &&
2508 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002509 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00002510 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00002511 }
2512 return Incompatible;
2513 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002514
Chris Lattnere8b3e962008-01-04 23:32:24 +00002515 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002516 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002517
Chris Lattner78eca282008-04-07 06:49:41 +00002518 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002519 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00002520 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002521
Chris Lattner78eca282008-04-07 06:49:41 +00002522 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002523 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00002524
Steve Naroffb4406862008-09-29 18:10:17 +00002525 if (rhsType->getAsBlockPointerType()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00002526 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002527 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00002528
2529 // Treat block pointers as objects.
2530 if (getLangOptions().ObjC1 &&
2531 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2532 return Compatible;
2533 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002534 return Incompatible;
2535 }
2536
2537 if (isa<BlockPointerType>(lhsType)) {
2538 if (rhsType->isIntegerType())
2539 return IntToPointer;
2540
Steve Naroffb4406862008-09-29 18:10:17 +00002541 // Treat block pointers as objects.
2542 if (getLangOptions().ObjC1 &&
2543 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2544 return Compatible;
2545
Steve Naroff1c7d0672008-09-04 15:10:53 +00002546 if (rhsType->isBlockPointerType())
2547 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2548
2549 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2550 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002551 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002552 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00002553 return Incompatible;
2554 }
2555
Chris Lattner78eca282008-04-07 06:49:41 +00002556 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002557 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002558 if (lhsType == Context.BoolTy)
2559 return Compatible;
2560
2561 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00002562 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00002563
Chris Lattner78eca282008-04-07 06:49:41 +00002564 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002565 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00002566
2567 if (isa<BlockPointerType>(lhsType) &&
2568 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002569 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002570 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002571 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002572
Chris Lattnerfc144e22008-01-04 23:18:45 +00002573 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00002574 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002575 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00002576 }
2577 return Incompatible;
2578}
2579
Chris Lattner5cf216b2008-01-04 18:04:52 +00002580Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002581Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002582 if (getLangOptions().CPlusPlus) {
2583 if (!lhsType->isRecordType()) {
2584 // C++ 5.17p3: If the left operand is not of class type, the
2585 // expression is implicitly converted (C++ 4) to the
2586 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00002587 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2588 "assigning"))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002589 return Incompatible;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002590 else
Douglas Gregor98cd5992008-10-21 23:43:52 +00002591 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002592 }
2593
2594 // FIXME: Currently, we fall through and treat C++ classes like C
2595 // structures.
2596 }
2597
Steve Naroff529a4ad2007-11-27 17:58:44 +00002598 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2599 // a null pointer constant.
Steve Naroff39218df2008-09-04 16:56:14 +00002600 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2601 lhsType->isBlockPointerType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00002602 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002603 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00002604 return Compatible;
2605 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002606
2607 // We don't allow conversion of non-null-pointer constants to integers.
2608 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2609 return IntToBlockPointer;
2610
Chris Lattner943140e2007-10-16 02:55:40 +00002611 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00002612 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00002613 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00002614 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00002615 //
Douglas Gregor9d293df2008-10-28 00:22:11 +00002616 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00002617 if (!lhsType->isReferenceType())
2618 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00002619
Chris Lattner5cf216b2008-01-04 18:04:52 +00002620 Sema::AssignConvertType result =
2621 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Narofff1120de2007-08-24 22:33:52 +00002622
2623 // C99 6.5.16.1p2: The value of the right operand is converted to the
2624 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00002625 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2626 // so that we can use references in built-in functions even in C.
2627 // The getNonReferenceType() call makes sure that the resulting expression
2628 // does not have reference type.
Steve Narofff1120de2007-08-24 22:33:52 +00002629 if (rExpr->getType() != lhsType)
Douglas Gregor9d293df2008-10-28 00:22:11 +00002630 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Narofff1120de2007-08-24 22:33:52 +00002631 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00002632}
2633
Chris Lattner5cf216b2008-01-04 18:04:52 +00002634Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002635Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2636 return CheckAssignmentConstraints(lhsType, rhsType);
2637}
2638
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002639QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002640 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00002641 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002642 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00002643 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002644}
2645
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002646inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00002647 Expr *&rex) {
Nate Begeman1330b0e2008-04-04 01:30:25 +00002648 // For conversion purposes, we ignore any qualifiers.
2649 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002650 QualType lhsType =
2651 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2652 QualType rhsType =
2653 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002654
Nate Begemanbe2341d2008-07-14 18:02:46 +00002655 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00002656 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00002657 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00002658
Nate Begemanbe2341d2008-07-14 18:02:46 +00002659 // Handle the case of a vector & extvector type of the same size and element
2660 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00002661 if (getLangOptions().LaxVectorConversions) {
2662 // FIXME: Should we warn here?
2663 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002664 if (const VectorType *RV = rhsType->getAsVectorType())
2665 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00002666 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002667 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00002668 }
2669 }
2670 }
2671
Nate Begemanbe2341d2008-07-14 18:02:46 +00002672 // If the lhs is an extended vector and the rhs is a scalar of the same type
2673 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00002674 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002675 QualType eltType = V->getElementType();
2676
2677 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2678 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2679 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002680 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00002681 return lhsType;
2682 }
2683 }
2684
Nate Begemanbe2341d2008-07-14 18:02:46 +00002685 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00002686 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00002687 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002688 QualType eltType = V->getElementType();
2689
2690 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2691 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2692 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002693 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00002694 return rhsType;
2695 }
2696 }
2697
Reid Spencer5f016e22007-07-11 17:01:13 +00002698 // You cannot convert between vector values of different size.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002699 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00002700 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002701 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002702 return QualType();
2703}
2704
2705inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002706 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002707{
Daniel Dunbar69d1d002009-01-05 22:42:10 +00002708 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002709 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00002710
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002711 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002712
Steve Naroffa4332e22007-07-17 00:58:39 +00002713 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002714 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002715 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002716}
2717
2718inline QualType Sema::CheckRemainderOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002719 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002720{
Daniel Dunbar523aa602009-01-05 22:55:36 +00002721 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2722 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2723 return CheckVectorOperands(Loc, lex, rex);
2724 return InvalidOperands(Loc, lex, rex);
2725 }
Steve Naroff90045e82007-07-13 23:32:42 +00002726
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002727 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002728
Steve Naroffa4332e22007-07-17 00:58:39 +00002729 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002730 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002731 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002732}
2733
2734inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002735 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002736{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002737 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002738 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00002739
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002740 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand72d16e2008-05-18 18:08:51 +00002741
Reid Spencer5f016e22007-07-11 17:01:13 +00002742 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00002743 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002744 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002745
Eli Friedmand72d16e2008-05-18 18:08:51 +00002746 // Put any potential pointer into PExp
2747 Expr* PExp = lex, *IExp = rex;
2748 if (IExp->getType()->isPointerType())
2749 std::swap(PExp, IExp);
2750
2751 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2752 if (IExp->getType()->isIntegerType()) {
2753 // Check for arithmetic on pointers to incomplete types
2754 if (!PTy->getPointeeType()->isObjectType()) {
2755 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00002756 if (getLangOptions().CPlusPlus) {
2757 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2758 << lex->getSourceRange() << rex->getSourceRange();
2759 return QualType();
2760 }
2761
2762 // GNU extension: arithmetic on pointer to void
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002763 Diag(Loc, diag::ext_gnu_void_ptr)
2764 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002765 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00002766 if (getLangOptions().CPlusPlus) {
2767 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2768 << lex->getType() << lex->getSourceRange();
2769 return QualType();
2770 }
2771
2772 // GNU extension: arithmetic on pointer to function
2773 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00002774 << lex->getType() << lex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002775 } else {
2776 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2777 diag::err_typecheck_arithmetic_incomplete_type,
2778 lex->getSourceRange(), SourceRange(),
2779 lex->getType());
2780 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00002781 }
2782 }
2783 return PExp->getType();
2784 }
2785 }
2786
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002787 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002788}
2789
Chris Lattnereca7be62008-04-07 05:30:13 +00002790// C99 6.5.6
2791QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002792 SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00002793 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002794 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002795
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002796 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002797
Chris Lattner6e4ab612007-12-09 21:53:25 +00002798 // Enforce type constraints: C99 6.5.6p3.
2799
2800 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00002801 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002802 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00002803
2804 // Either ptr - int or ptr - ptr.
2805 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00002806 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman8e54ad02008-02-08 01:19:44 +00002807
Chris Lattner6e4ab612007-12-09 21:53:25 +00002808 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff2565eef2008-01-29 18:58:14 +00002809 if (!lpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002810 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002811 if (lpointee->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002812 Diag(Loc, diag::ext_gnu_void_ptr)
2813 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorc983b862009-01-23 00:36:41 +00002814 } else if (lpointee->isFunctionType()) {
2815 if (getLangOptions().CPlusPlus) {
2816 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2817 << lex->getType() << lex->getSourceRange();
2818 return QualType();
2819 }
2820
2821 // GNU extension: arithmetic on pointer to function
2822 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2823 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002824 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002825 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00002826 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002827 return QualType();
2828 }
2829 }
2830
2831 // The result type of a pointer-int computation is the pointer type.
2832 if (rex->getType()->isIntegerType())
2833 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00002834
Chris Lattner6e4ab612007-12-09 21:53:25 +00002835 // Handle pointer-pointer subtractions.
2836 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00002837 QualType rpointee = RHSPTy->getPointeeType();
2838
Chris Lattner6e4ab612007-12-09 21:53:25 +00002839 // RHS must be an object type, unless void (GNU).
Steve Naroff2565eef2008-01-29 18:58:14 +00002840 if (!rpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002841 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002842 if (rpointee->isVoidType()) {
2843 if (!lpointee->isVoidType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002844 Diag(Loc, diag::ext_gnu_void_ptr)
2845 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor08048882009-01-23 19:03:35 +00002846 } else if (rpointee->isFunctionType()) {
2847 if (getLangOptions().CPlusPlus) {
2848 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2849 << rex->getType() << rex->getSourceRange();
2850 return QualType();
2851 }
2852
2853 // GNU extension: arithmetic on pointer to function
2854 if (!lpointee->isFunctionType())
2855 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2856 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002857 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002858 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00002859 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002860 return QualType();
2861 }
2862 }
2863
2864 // Pointee types must be compatible.
Eli Friedmanf1c7b482008-09-02 05:09:35 +00002865 if (!Context.typesAreCompatible(
2866 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2867 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002868 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattnerd1625842008-11-24 06:25:27 +00002869 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002870 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002871 return QualType();
2872 }
2873
2874 return Context.getPointerDiffType();
2875 }
2876 }
2877
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002878 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002879}
2880
Chris Lattnereca7be62008-04-07 05:30:13 +00002881// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002882QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00002883 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00002884 // C99 6.5.7p2: Each of the operands shall have integer type.
2885 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002886 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002887
Chris Lattnerca5eede2007-12-12 05:47:28 +00002888 // Shifts don't perform usual arithmetic conversions, they just do integer
2889 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00002890 if (!isCompAssign)
2891 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00002892 UsualUnaryConversions(rex);
2893
2894 // "The type of the result is that of the promoted left operand."
2895 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002896}
2897
Eli Friedman3d815e72008-08-22 00:56:42 +00002898static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2899 ASTContext& Context) {
2900 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2901 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2902 // ID acts sort of like void* for ObjC interfaces
2903 if (LHSIface && Context.isObjCIdType(RHS))
2904 return true;
2905 if (RHSIface && Context.isObjCIdType(LHS))
2906 return true;
2907 if (!LHSIface || !RHSIface)
2908 return false;
2909 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2910 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2911}
2912
Chris Lattnereca7be62008-04-07 05:30:13 +00002913// C99 6.5.8
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002914QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00002915 bool isRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002916 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002917 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002918
Chris Lattnera5937dd2007-08-26 01:18:55 +00002919 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00002920 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2921 UsualArithmeticConversions(lex, rex);
2922 else {
2923 UsualUnaryConversions(lex);
2924 UsualUnaryConversions(rex);
2925 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002926 QualType lType = lex->getType();
2927 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002928
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002929 // For non-floating point types, check for self-comparisons of the form
2930 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2931 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002932 if (!lType->isFloatingType()) {
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00002933 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2934 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002935 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002936 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002937 }
2938
Douglas Gregor447b69e2008-11-19 03:25:36 +00002939 // The result of comparisons is 'bool' in C++, 'int' in C.
2940 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2941
Chris Lattnera5937dd2007-08-26 01:18:55 +00002942 if (isRelational) {
2943 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00002944 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00002945 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002946 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002947 if (lType->isFloatingType()) {
2948 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002949 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00002950 }
2951
Chris Lattnera5937dd2007-08-26 01:18:55 +00002952 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00002953 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00002954 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002955
Chris Lattnerd28f8152007-08-26 01:10:14 +00002956 bool LHSIsNull = lex->isNullPointerConstant(Context);
2957 bool RHSIsNull = rex->isNullPointerConstant(Context);
2958
Chris Lattnera5937dd2007-08-26 01:18:55 +00002959 // All of the following pointer related warnings are GCC extensions, except
2960 // when handling null pointer constants. One day, we can consider making them
2961 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00002962 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002963 QualType LCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002964 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00002965 QualType RCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002966 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman8e54ad02008-02-08 01:19:44 +00002967
Steve Naroff66296cb2007-11-13 14:57:38 +00002968 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002969 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2970 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman3d815e72008-08-22 00:56:42 +00002971 RCanPointeeTy.getUnqualifiedType()) &&
2972 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002973 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00002974 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002975 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00002976 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002977 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002978 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002979 // Handle block pointer types.
2980 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2981 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2982 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2983
2984 if (!LHSIsNull && !RHSIsNull &&
2985 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002986 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00002987 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00002988 }
2989 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002990 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002991 }
Steve Naroff59f53942008-09-28 01:11:11 +00002992 // Allow block pointers to be compared with null pointer constants.
2993 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2994 (lType->isPointerType() && rType->isBlockPointerType())) {
2995 if (!LHSIsNull && !RHSIsNull) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002996 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00002997 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00002998 }
2999 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003000 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00003001 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00003002
Steve Naroff20373222008-06-03 14:04:54 +00003003 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00003004 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroffa8069f12008-11-17 19:49:16 +00003005 const PointerType *LPT = lType->getAsPointerType();
3006 const PointerType *RPT = rType->getAsPointerType();
3007 bool LPtrToVoid = LPT ?
3008 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
3009 bool RPtrToVoid = RPT ?
3010 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
3011
3012 if (!LPtrToVoid && !RPtrToVoid &&
3013 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003014 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00003015 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00003016 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00003017 return ResultTy;
Steve Naroffa5ad8632008-10-27 10:33:19 +00003018 }
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00003019 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00003020 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00003021 }
Steve Naroff20373222008-06-03 14:04:54 +00003022 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3023 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00003024 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00003025 } else {
3026 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003027 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003028 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00003029 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00003030 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00003031 }
Steve Naroff20373222008-06-03 14:04:54 +00003032 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00003033 }
Steve Naroff20373222008-06-03 14:04:54 +00003034 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
3035 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00003036 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003037 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003038 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00003039 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003040 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00003041 }
Steve Naroff20373222008-06-03 14:04:54 +00003042 if (lType->isIntegerType() &&
3043 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00003044 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003045 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003046 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00003047 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003048 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003049 }
Steve Naroff39218df2008-09-04 16:56:14 +00003050 // Handle block pointers.
3051 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3052 if (!RHSIsNull)
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(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003056 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00003057 }
3058 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3059 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003060 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003061 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00003062 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003063 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00003064 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003065 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003066}
3067
Nate Begemanbe2341d2008-07-14 18:02:46 +00003068/// CheckVectorCompareOperands - vector comparisons are a clang extension that
3069/// operates on extended vector types. Instead of producing an IntTy result,
3070/// like a scalar comparison, a vector comparison produces a vector of integer
3071/// types.
3072QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003073 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00003074 bool isRelational) {
3075 // Check to make sure we're operating on vectors of the same type and width,
3076 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003077 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00003078 if (vType.isNull())
3079 return vType;
3080
3081 QualType lType = lex->getType();
3082 QualType rType = rex->getType();
3083
3084 // For non-floating point types, check for self-comparisons of the form
3085 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3086 // often indicate logic errors in the program.
3087 if (!lType->isFloatingType()) {
3088 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3089 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3090 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003091 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00003092 }
3093
3094 // Check for comparisons of floating point operands using != and ==.
3095 if (!isRelational && lType->isFloatingType()) {
3096 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003097 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00003098 }
3099
3100 // Return the type for the comparison, which is the same as vector type for
3101 // integer vectors, or an integer type of identical size and number of
3102 // elements for floating point vectors.
3103 if (lType->isIntegerType())
3104 return lType;
3105
3106 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanbe2341d2008-07-14 18:02:46 +00003107 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00003108 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00003109 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begeman59b5da62009-01-18 03:20:47 +00003110 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3111 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3112
3113 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3114 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00003115 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3116}
3117
Reid Spencer5f016e22007-07-11 17:01:13 +00003118inline QualType Sema::CheckBitwiseOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003119 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00003120{
Steve Naroff3e5e5562007-07-16 22:23:01 +00003121 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003122 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00003123
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003124 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00003125
Steve Naroffa4332e22007-07-17 00:58:39 +00003126 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003127 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003128 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003129}
3130
3131inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003132 Expr *&lex, Expr *&rex, SourceLocation Loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00003133{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003134 UsualUnaryConversions(lex);
3135 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003136
Eli Friedman5773a6c2008-05-13 20:16:47 +00003137 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00003138 return Context.IntTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003139 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003140}
3141
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00003142/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3143/// is a read-only property; return true if so. A readonly property expression
3144/// depends on various declarations and thus must be treated specially.
3145///
3146static bool IsReadonlyProperty(Expr *E, Sema &S)
3147{
3148 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3149 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3150 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3151 QualType BaseType = PropExpr->getBase()->getType();
3152 if (const PointerType *PTy = BaseType->getAsPointerType())
3153 if (const ObjCInterfaceType *IFTy =
3154 PTy->getPointeeType()->getAsObjCInterfaceType())
3155 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3156 if (S.isPropertyReadonly(PDecl, IFace))
3157 return true;
3158 }
3159 }
3160 return false;
3161}
3162
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003163/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3164/// emit an error and return true. If so, return false.
3165static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00003166 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3167 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3168 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003169 if (IsLV == Expr::MLV_Valid)
3170 return false;
3171
3172 unsigned Diag = 0;
3173 bool NeedType = false;
3174 switch (IsLV) { // C99 6.5.16p2
3175 default: assert(0 && "Unknown result from isModifiableLvalue!");
3176 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003177 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003178 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3179 NeedType = true;
3180 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003181 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003182 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3183 NeedType = true;
3184 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00003185 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003186 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3187 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003188 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003189 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3190 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003191 case Expr::MLV_IncompleteType:
3192 case Expr::MLV_IncompleteVoidType:
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003193 return S.DiagnoseIncompleteType(Loc, E->getType(),
3194 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3195 E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00003196 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003197 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3198 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00003199 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003200 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3201 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00003202 case Expr::MLV_ReadonlyProperty:
3203 Diag = diag::error_readonly_property_assignment;
3204 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00003205 case Expr::MLV_NoSetterProperty:
3206 Diag = diag::error_nosetter_property_assignment;
3207 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003208 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00003209
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003210 if (NeedType)
Chris Lattnerd1625842008-11-24 06:25:27 +00003211 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003212 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003213 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003214 return true;
3215}
3216
3217
3218
3219// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003220QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3221 SourceLocation Loc,
3222 QualType CompoundType) {
3223 // Verify that LHS is a modifiable lvalue, and emit error if not.
3224 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003225 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003226
3227 QualType LHSType = LHS->getType();
3228 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003229
Chris Lattner5cf216b2008-01-04 18:04:52 +00003230 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003231 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00003232 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003233 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003234 // Special case of NSObject attributes on c-style pointer types.
3235 if (ConvTy == IncompatiblePointer &&
3236 ((Context.isObjCNSObjectType(LHSType) &&
3237 Context.isObjCObjectPointerType(RHSType)) ||
3238 (Context.isObjCNSObjectType(RHSType) &&
3239 Context.isObjCObjectPointerType(LHSType))))
3240 ConvTy = Compatible;
3241
Chris Lattner2c156472008-08-21 18:04:13 +00003242 // If the RHS is a unary plus or minus, check to see if they = and + are
3243 // right next to each other. If so, the user may have typo'd "x =+ 4"
3244 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003245 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00003246 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3247 RHSCheck = ICE->getSubExpr();
3248 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3249 if ((UO->getOpcode() == UnaryOperator::Plus ||
3250 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003251 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00003252 // Only if the two operators are exactly adjacent.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003253 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003254 Diag(Loc, diag::warn_not_compound_assign)
3255 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3256 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner2c156472008-08-21 18:04:13 +00003257 }
3258 } else {
3259 // Compound assignment "x += y"
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003260 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00003261 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00003262
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003263 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3264 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00003265 return QualType();
3266
Reid Spencer5f016e22007-07-11 17:01:13 +00003267 // C99 6.5.16p3: The type of an assignment expression is the type of the
3268 // left operand unless the left operand has qualified type, in which case
3269 // it is the unqualified version of the type of the left operand.
3270 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3271 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003272 // C++ 5.17p1: the type of the assignment expression is that of its left
3273 // oprdu.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003274 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003275}
3276
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003277// C99 6.5.17
3278QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3279 // FIXME: what is required for LHS?
Chris Lattner53fcaa92008-07-25 20:54:07 +00003280
3281 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003282 DefaultFunctionArrayConversion(RHS);
3283 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003284}
3285
Steve Naroff49b45262007-07-13 16:58:59 +00003286/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3287/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003288QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3289 bool isInc) {
Chris Lattner3528d352008-11-21 07:05:48 +00003290 QualType ResType = Op->getType();
3291 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00003292
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003293 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3294 // Decrement of bool is not allowed.
3295 if (!isInc) {
3296 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3297 return QualType();
3298 }
3299 // Increment of bool sets it to true, but is deprecated.
3300 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3301 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00003302 // OK!
3303 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3304 // C99 6.5.2.4p2, 6.5.6p2
3305 if (PT->getPointeeType()->isObjectType()) {
3306 // Pointer to object is ok!
3307 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00003308 if (getLangOptions().CPlusPlus) {
3309 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3310 << Op->getSourceRange();
3311 return QualType();
3312 }
3313
3314 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00003315 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003316 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00003317 if (getLangOptions().CPlusPlus) {
3318 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3319 << Op->getType() << Op->getSourceRange();
3320 return QualType();
3321 }
3322
3323 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00003324 << ResType << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003325 return QualType();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003326 } else {
3327 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3328 diag::err_typecheck_arithmetic_incomplete_type,
3329 Op->getSourceRange(), SourceRange(),
3330 ResType);
3331 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003332 }
Chris Lattner3528d352008-11-21 07:05:48 +00003333 } else if (ResType->isComplexType()) {
3334 // C99 does not support ++/-- on complex types, we allow as an extension.
3335 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00003336 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00003337 } else {
3338 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00003339 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00003340 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003341 }
Steve Naroffdd10e022007-08-23 21:37:33 +00003342 // At this point, we know we have a real, complex or pointer type.
3343 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00003344 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00003345 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00003346 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00003347}
3348
Anders Carlsson369dee42008-02-01 07:15:58 +00003349/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00003350/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003351/// where the declaration is needed for type checking. We only need to
3352/// handle cases when the expression references a function designator
3353/// or is an lvalue. Here are some examples:
3354/// - &(x) => x
3355/// - &*****f => f for f a function designator.
3356/// - &s.xx => s
3357/// - &s.zz[1].yy -> s, if zz is an array
3358/// - *(x + 1) -> x, if x is an array
3359/// - &"123"[2] -> 0
3360/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003361static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00003362 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003363 case Stmt::DeclRefExprClass:
Douglas Gregor1a49af92009-01-06 05:10:23 +00003364 case Stmt::QualifiedDeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00003365 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003366 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00003367 // Fields cannot be declared with a 'register' storage class.
3368 // &X->f is always ok, even if X is declared register.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003369 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00003370 return 0;
Chris Lattnerf0467b32008-04-02 04:24:33 +00003371 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00003372 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003373 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson369dee42008-02-01 07:15:58 +00003374
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003375 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar48d04ae2008-10-21 21:22:32 +00003376 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlssonf2a4b842008-02-01 16:01:31 +00003377 if (!VD || VD->getType()->isPointerType())
Anders Carlsson369dee42008-02-01 07:15:58 +00003378 return 0;
3379 else
3380 return VD;
3381 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003382 case Stmt::UnaryOperatorClass: {
3383 UnaryOperator *UO = cast<UnaryOperator>(E);
3384
3385 switch(UO->getOpcode()) {
3386 case UnaryOperator::Deref: {
3387 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003388 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3389 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3390 if (!VD || VD->getType()->isPointerType())
3391 return 0;
3392 return VD;
3393 }
3394 return 0;
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003395 }
3396 case UnaryOperator::Real:
3397 case UnaryOperator::Imag:
3398 case UnaryOperator::Extension:
3399 return getPrimaryDecl(UO->getSubExpr());
3400 default:
3401 return 0;
3402 }
3403 }
3404 case Stmt::BinaryOperatorClass: {
3405 BinaryOperator *BO = cast<BinaryOperator>(E);
3406
3407 // Handle cases involving pointer arithmetic. The result of an
3408 // Assign or AddAssign is not an lvalue so they can be ignored.
3409
3410 // (x + n) or (n + x) => x
3411 if (BO->getOpcode() == BinaryOperator::Add) {
3412 if (BO->getLHS()->getType()->isPointerType()) {
3413 return getPrimaryDecl(BO->getLHS());
3414 } else if (BO->getRHS()->getType()->isPointerType()) {
3415 return getPrimaryDecl(BO->getRHS());
3416 }
3417 }
3418
3419 return 0;
3420 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003421 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00003422 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00003423 case Stmt::ImplicitCastExprClass:
3424 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003425 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00003426 default:
3427 return 0;
3428 }
3429}
3430
3431/// CheckAddressOfOperand - The operand of & must be either a function
3432/// designator or an lvalue designating an object. If it is an lvalue, the
3433/// object cannot be declared with storage class register or be a bit field.
3434/// Note: The usual conversions are *not* applied to the operand of the &
3435/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor904eed32008-11-10 20:40:00 +00003436/// In C++, the operand might be an overloaded function name, in which case
3437/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00003438QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregor9103bb22008-12-17 22:52:20 +00003439 if (op->isTypeDependent())
3440 return Context.DependentTy;
3441
Steve Naroff08f19672008-01-13 17:10:08 +00003442 if (getLangOptions().C99) {
3443 // Implement C99-only parts of addressof rules.
3444 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3445 if (uOp->getOpcode() == UnaryOperator::Deref)
3446 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3447 // (assuming the deref expression is valid).
3448 return uOp->getSubExpr()->getType();
3449 }
3450 // Technically, there should be a check for array subscript
3451 // expressions here, but the result of one is always an lvalue anyway.
3452 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003453 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00003454 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00003455
Reid Spencer5f016e22007-07-11 17:01:13 +00003456 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00003457 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3458 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003459 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3460 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003461 return QualType();
3462 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00003463 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor86f19402008-12-20 23:49:58 +00003464 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3465 if (Field->isBitField()) {
3466 Diag(OpLoc, diag::err_typecheck_address_of)
3467 << "bit-field" << op->getSourceRange();
3468 return QualType();
3469 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00003470 }
3471 // Check for Apple extension for accessing vector components.
3472 } else if (isa<ArraySubscriptExpr>(op) &&
3473 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003474 Diag(OpLoc, diag::err_typecheck_address_of)
3475 << "vector" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00003476 return QualType();
3477 } else if (dcl) { // C99 6.5.3.2p1
Reid Spencer5f016e22007-07-11 17:01:13 +00003478 // We have an lvalue with a decl. Make sure the decl is not declared
3479 // with the register storage-class specifier.
3480 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3481 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003482 Diag(OpLoc, diag::err_typecheck_address_of)
3483 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003484 return QualType();
3485 }
Douglas Gregor29882052008-12-10 21:26:49 +00003486 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00003487 return Context.OverloadTy;
Douglas Gregor29882052008-12-10 21:26:49 +00003488 } else if (isa<FieldDecl>(dcl)) {
3489 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00003490 // Could be a pointer to member, though, if there is an explicit
3491 // scope qualifier for the class.
3492 if (isa<QualifiedDeclRefExpr>(op)) {
3493 DeclContext *Ctx = dcl->getDeclContext();
3494 if (Ctx && Ctx->isRecord())
3495 return Context.getMemberPointerType(op->getType(),
3496 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3497 }
Nuno Lopes6fea8d22008-12-16 22:58:26 +00003498 } else if (isa<FunctionDecl>(dcl)) {
3499 // Okay: we can take the address of a function.
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 }
Chris Lattnerc36d4052008-07-27 00:48:22 +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!");
3530 case tok::star: Opc = BinaryOperator::Mul; break;
3531 case tok::slash: Opc = BinaryOperator::Div; break;
3532 case tok::percent: Opc = BinaryOperator::Rem; break;
3533 case tok::plus: Opc = BinaryOperator::Add; break;
3534 case tok::minus: Opc = BinaryOperator::Sub; break;
3535 case tok::lessless: Opc = BinaryOperator::Shl; break;
3536 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3537 case tok::lessequal: Opc = BinaryOperator::LE; break;
3538 case tok::less: Opc = BinaryOperator::LT; break;
3539 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3540 case tok::greater: Opc = BinaryOperator::GT; break;
3541 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3542 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3543 case tok::amp: Opc = BinaryOperator::And; break;
3544 case tok::caret: Opc = BinaryOperator::Xor; break;
3545 case tok::pipe: Opc = BinaryOperator::Or; break;
3546 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3547 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3548 case tok::equal: Opc = BinaryOperator::Assign; break;
3549 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3550 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3551 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3552 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3553 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3554 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3555 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3556 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3557 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3558 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3559 case tok::comma: Opc = BinaryOperator::Comma; break;
3560 }
3561 return Opc;
3562}
3563
3564static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3565 tok::TokenKind Kind) {
3566 UnaryOperator::Opcode Opc;
3567 switch (Kind) {
3568 default: assert(0 && "Unknown unary op!");
3569 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3570 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3571 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3572 case tok::star: Opc = UnaryOperator::Deref; break;
3573 case tok::plus: Opc = UnaryOperator::Plus; break;
3574 case tok::minus: Opc = UnaryOperator::Minus; break;
3575 case tok::tilde: Opc = UnaryOperator::Not; break;
3576 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003577 case tok::kw___real: Opc = UnaryOperator::Real; break;
3578 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3579 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3580 }
3581 return Opc;
3582}
3583
Douglas Gregoreaebc752008-11-06 23:29:22 +00003584/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3585/// operator @p Opc at location @c TokLoc. This routine only supports
3586/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003587Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3588 unsigned Op,
3589 Expr *lhs, Expr *rhs) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00003590 QualType ResultTy; // Result type of the binary operator.
3591 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3592 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3593
3594 switch (Opc) {
3595 default:
3596 assert(0 && "Unknown binary expr!");
3597 case BinaryOperator::Assign:
3598 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3599 break;
3600 case BinaryOperator::Mul:
3601 case BinaryOperator::Div:
3602 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3603 break;
3604 case BinaryOperator::Rem:
3605 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3606 break;
3607 case BinaryOperator::Add:
3608 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3609 break;
3610 case BinaryOperator::Sub:
3611 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3612 break;
3613 case BinaryOperator::Shl:
3614 case BinaryOperator::Shr:
3615 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3616 break;
3617 case BinaryOperator::LE:
3618 case BinaryOperator::LT:
3619 case BinaryOperator::GE:
3620 case BinaryOperator::GT:
3621 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3622 break;
3623 case BinaryOperator::EQ:
3624 case BinaryOperator::NE:
3625 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3626 break;
3627 case BinaryOperator::And:
3628 case BinaryOperator::Xor:
3629 case BinaryOperator::Or:
3630 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3631 break;
3632 case BinaryOperator::LAnd:
3633 case BinaryOperator::LOr:
3634 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3635 break;
3636 case BinaryOperator::MulAssign:
3637 case BinaryOperator::DivAssign:
3638 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3639 if (!CompTy.isNull())
3640 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3641 break;
3642 case BinaryOperator::RemAssign:
3643 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3644 if (!CompTy.isNull())
3645 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3646 break;
3647 case BinaryOperator::AddAssign:
3648 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3649 if (!CompTy.isNull())
3650 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3651 break;
3652 case BinaryOperator::SubAssign:
3653 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3654 if (!CompTy.isNull())
3655 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3656 break;
3657 case BinaryOperator::ShlAssign:
3658 case BinaryOperator::ShrAssign:
3659 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3660 if (!CompTy.isNull())
3661 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3662 break;
3663 case BinaryOperator::AndAssign:
3664 case BinaryOperator::XorAssign:
3665 case BinaryOperator::OrAssign:
3666 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3667 if (!CompTy.isNull())
3668 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3669 break;
3670 case BinaryOperator::Comma:
3671 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3672 break;
3673 }
3674 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003675 return ExprError();
Steve Naroff6ece14c2009-01-21 00:14:39 +00003676 if (CompTy.isNull())
3677 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3678 else
3679 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Steve Naroff9e0b6002009-01-20 21:06:31 +00003680 CompTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00003681}
3682
Reid Spencer5f016e22007-07-11 17:01:13 +00003683// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003684Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3685 tok::TokenKind Kind,
3686 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003687 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003688 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Reid Spencer5f016e22007-07-11 17:01:13 +00003689
Steve Narofff69936d2007-09-16 03:34:24 +00003690 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3691 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00003692
Douglas Gregor898574e2008-12-05 23:32:09 +00003693 // If either expression is type-dependent, just build the AST.
3694 // FIXME: We'll need to perform some caching of the result of name
3695 // lookup for operator+.
3696 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff6ece14c2009-01-21 00:14:39 +00003697 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3698 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003699 Context.DependentTy,
3700 Context.DependentTy, TokLoc));
Steve Naroff6ece14c2009-01-21 00:14:39 +00003701 else
3702 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, Context.DependentTy,
3703 TokLoc));
Douglas Gregor898574e2008-12-05 23:32:09 +00003704 }
3705
Douglas Gregoreaebc752008-11-06 23:29:22 +00003706 if (getLangOptions().CPlusPlus &&
3707 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3708 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003709 // If this is one of the assignment operators, we only perform
3710 // overload resolution if the left-hand side is a class or
3711 // enumeration type (C++ [expr.ass]p3).
3712 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3713 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3714 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3715 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003716
Douglas Gregoreaebc752008-11-06 23:29:22 +00003717 // Determine which overloaded operator we're dealing with.
3718 static const OverloadedOperatorKind OverOps[] = {
3719 OO_Star, OO_Slash, OO_Percent,
3720 OO_Plus, OO_Minus,
3721 OO_LessLess, OO_GreaterGreater,
3722 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3723 OO_EqualEqual, OO_ExclaimEqual,
3724 OO_Amp,
3725 OO_Caret,
3726 OO_Pipe,
3727 OO_AmpAmp,
3728 OO_PipePipe,
3729 OO_Equal, OO_StarEqual,
3730 OO_SlashEqual, OO_PercentEqual,
3731 OO_PlusEqual, OO_MinusEqual,
3732 OO_LessLessEqual, OO_GreaterGreaterEqual,
3733 OO_AmpEqual, OO_CaretEqual,
3734 OO_PipeEqual,
3735 OO_Comma
3736 };
3737 OverloadedOperatorKind OverOp = OverOps[Opc];
3738
Douglas Gregor96176b32008-11-18 23:14:02 +00003739 // Add the appropriate overloaded operators (C++ [over.match.oper])
3740 // to the candidate set.
Douglas Gregor74253732008-11-19 15:42:04 +00003741 OverloadCandidateSet CandidateSet;
Douglas Gregoreaebc752008-11-06 23:29:22 +00003742 Expr *Args[2] = { lhs, rhs };
Douglas Gregorf680a0f2009-02-04 16:44:47 +00003743 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3744 return ExprError();
Douglas Gregoreaebc752008-11-06 23:29:22 +00003745
3746 // Perform overload resolution.
3747 OverloadCandidateSet::iterator Best;
3748 switch (BestViableFunction(CandidateSet, Best)) {
3749 case OR_Success: {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003750 // We found a built-in operator or an overloaded operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003751 FunctionDecl *FnDecl = Best->Function;
3752
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003753 if (FnDecl) {
3754 // We matched an overloaded operator. Build a call to that
3755 // operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003756
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003757 // Convert the arguments.
Douglas Gregor96176b32008-11-18 23:14:02 +00003758 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3759 if (PerformObjectArgumentInitialization(lhs, Method) ||
3760 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3761 "passing"))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003762 return ExprError();
Douglas Gregor96176b32008-11-18 23:14:02 +00003763 } else {
3764 // Convert the arguments.
3765 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3766 "passing") ||
3767 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3768 "passing"))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003769 return ExprError();
Douglas Gregor96176b32008-11-18 23:14:02 +00003770 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003771
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003772 // Determine the result type
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003773 QualType ResultTy
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003774 = FnDecl->getType()->getAsFunctionType()->getResultType();
3775 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003776
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003777 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00003778 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3779 SourceLocation());
Douglas Gregorb4609802008-11-14 16:09:21 +00003780 UsualUnaryConversions(FnExpr);
3781
Steve Naroff6ece14c2009-01-21 00:14:39 +00003782 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, Args, 2,
3783 ResultTy, TokLoc));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003784 } else {
3785 // We matched a built-in operator. Convert the arguments, then
3786 // break out so that we will build the appropriate built-in
3787 // operator node.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003788 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3789 Best->Conversions[0], "passing") ||
3790 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3791 Best->Conversions[1], "passing"))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003792 return ExprError();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003793
3794 break;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003795 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003796 }
3797
3798 case OR_No_Viable_Function:
3799 // No viable function; fall through to handling this as a
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003800 // built-in operator, which will produce an error message for us.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003801 break;
3802
3803 case OR_Ambiguous:
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003804 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3805 << BinaryOperator::getOpcodeStr(Opc)
3806 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregoreaebc752008-11-06 23:29:22 +00003807 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003808 return ExprError();
Douglas Gregoreaebc752008-11-06 23:29:22 +00003809 }
3810
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003811 // Either we found no viable overloaded operator or we matched a
3812 // built-in operator. In either case, fall through to trying to
3813 // build a built-in operation.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003814 }
3815
Douglas Gregoreaebc752008-11-06 23:29:22 +00003816 // Build a built-in binary operation.
3817 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00003818}
3819
3820// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003821Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3822 tok::TokenKind Op, ExprArg input) {
3823 // FIXME: Input is modified later, but smart pointer not reassigned.
3824 Expr *Input = (Expr*)input.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00003825 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor74253732008-11-19 15:42:04 +00003826
3827 if (getLangOptions().CPlusPlus &&
3828 (Input->getType()->isRecordType()
3829 || Input->getType()->isEnumeralType())) {
3830 // Determine which overloaded operator we're dealing with.
3831 static const OverloadedOperatorKind OverOps[] = {
3832 OO_None, OO_None,
3833 OO_PlusPlus, OO_MinusMinus,
3834 OO_Amp, OO_Star,
3835 OO_Plus, OO_Minus,
3836 OO_Tilde, OO_Exclaim,
3837 OO_None, OO_None,
3838 OO_None,
3839 OO_None
3840 };
3841 OverloadedOperatorKind OverOp = OverOps[Opc];
3842
3843 // Add the appropriate overloaded operators (C++ [over.match.oper])
3844 // to the candidate set.
3845 OverloadCandidateSet CandidateSet;
Douglas Gregorf680a0f2009-02-04 16:44:47 +00003846 if (OverOp != OO_None &&
3847 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
3848 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00003849
3850 // Perform overload resolution.
3851 OverloadCandidateSet::iterator Best;
3852 switch (BestViableFunction(CandidateSet, Best)) {
3853 case OR_Success: {
3854 // We found a built-in operator or an overloaded operator.
3855 FunctionDecl *FnDecl = Best->Function;
3856
3857 if (FnDecl) {
3858 // We matched an overloaded operator. Build a call to that
3859 // operator.
3860
3861 // Convert the arguments.
3862 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3863 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003864 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00003865 } else {
3866 // Convert the arguments.
3867 if (PerformCopyInitialization(Input,
3868 FnDecl->getParamDecl(0)->getType(),
3869 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003870 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00003871 }
3872
3873 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00003874 QualType ResultTy
Douglas Gregor74253732008-11-19 15:42:04 +00003875 = FnDecl->getType()->getAsFunctionType()->getResultType();
3876 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003877
Douglas Gregor74253732008-11-19 15:42:04 +00003878 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00003879 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3880 SourceLocation());
Douglas Gregor74253732008-11-19 15:42:04 +00003881 UsualUnaryConversions(FnExpr);
3882
Sebastian Redl0eb23302009-01-19 00:08:26 +00003883 input.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00003884 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, &Input, 1,
3885 ResultTy, OpLoc));
Douglas Gregor74253732008-11-19 15:42:04 +00003886 } else {
3887 // We matched a built-in operator. Convert the arguments, then
3888 // break out so that we will build the appropriate built-in
3889 // operator node.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003890 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3891 Best->Conversions[0], "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003892 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00003893
3894 break;
Sebastian Redl0eb23302009-01-19 00:08:26 +00003895 }
Douglas Gregor74253732008-11-19 15:42:04 +00003896 }
3897
3898 case OR_No_Viable_Function:
3899 // No viable function; fall through to handling this as a
3900 // built-in operator, which will produce an error message for us.
3901 break;
3902
3903 case OR_Ambiguous:
3904 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3905 << UnaryOperator::getOpcodeStr(Opc)
3906 << Input->getSourceRange();
3907 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003908 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00003909 }
3910
3911 // Either we found no viable overloaded operator or we matched a
3912 // built-in operator. In either case, fall through to trying to
Sebastian Redl0eb23302009-01-19 00:08:26 +00003913 // build a built-in operation.
Douglas Gregor74253732008-11-19 15:42:04 +00003914 }
3915
Reid Spencer5f016e22007-07-11 17:01:13 +00003916 QualType resultType;
3917 switch (Opc) {
3918 default:
3919 assert(0 && "Unimplemented unary expr!");
3920 case UnaryOperator::PreInc:
3921 case UnaryOperator::PreDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003922 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3923 Opc == UnaryOperator::PreInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00003924 break;
3925 case UnaryOperator::AddrOf:
3926 resultType = CheckAddressOfOperand(Input, OpLoc);
3927 break;
3928 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00003929 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003930 resultType = CheckIndirectionOperand(Input, OpLoc);
3931 break;
3932 case UnaryOperator::Plus:
3933 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003934 UsualUnaryConversions(Input);
3935 resultType = Input->getType();
Douglas Gregor74253732008-11-19 15:42:04 +00003936 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3937 break;
3938 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3939 resultType->isEnumeralType())
3940 break;
3941 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3942 Opc == UnaryOperator::Plus &&
3943 resultType->isPointerType())
3944 break;
3945
Sebastian Redl0eb23302009-01-19 00:08:26 +00003946 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3947 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003948 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003949 UsualUnaryConversions(Input);
3950 resultType = Input->getType();
Chris Lattner02a65142008-07-25 23:52:49 +00003951 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3952 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3953 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003954 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00003955 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00003956 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003957 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3958 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003959 break;
3960 case UnaryOperator::LNot: // logical negation
3961 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003962 DefaultFunctionArrayConversion(Input);
3963 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003964 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00003965 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3966 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003967 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003968 // In C++, it's bool. C++ 5.3.1p8
3969 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003970 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00003971 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00003972 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00003973 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00003974 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003975 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00003976 resultType = Input->getType();
3977 break;
3978 }
3979 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003980 return ExprError();
3981 input.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00003982 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003983}
3984
Steve Naroff1b273c42007-09-16 14:56:35 +00003985/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3986Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00003987 SourceLocation LabLoc,
3988 IdentifierInfo *LabelII) {
3989 // Look up the record for this label identifier.
3990 LabelStmt *&LabelDecl = LabelMap[LabelII];
3991
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00003992 // If we haven't seen this label yet, create a forward reference. It
3993 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Reid Spencer5f016e22007-07-11 17:01:13 +00003994 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00003995 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00003996
3997 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff6ece14c2009-01-21 00:14:39 +00003998 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3999 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00004000}
4001
Steve Naroff1b273c42007-09-16 14:56:35 +00004002Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004003 SourceLocation RPLoc) { // "({..})"
4004 Stmt *SubStmt = static_cast<Stmt*>(substmt);
4005 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4006 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4007
Eli Friedmandca2b732009-01-24 23:09:00 +00004008 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4009 if (isFileScope) {
4010 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4011 }
4012
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004013 // FIXME: there are a variety of strange constraints to enforce here, for
4014 // example, it is not possible to goto into a stmt expression apparently.
4015 // More semantic analysis is needed.
4016
4017 // FIXME: the last statement in the compount stmt has its value used. We
4018 // should not warn about it being unused.
4019
4020 // If there are sub stmts in the compound stmt, take the type of the last one
4021 // as the type of the stmtexpr.
4022 QualType Ty = Context.VoidTy;
4023
Chris Lattner611b2ec2008-07-26 19:51:01 +00004024 if (!Compound->body_empty()) {
4025 Stmt *LastStmt = Compound->body_back();
4026 // If LastStmt is a label, skip down through into the body.
4027 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4028 LastStmt = Label->getSubStmt();
4029
4030 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004031 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00004032 }
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004033
Steve Naroff6ece14c2009-01-21 00:14:39 +00004034 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00004035}
Steve Naroffd34e9152007-08-01 22:05:33 +00004036
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004037Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4038 SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004039 SourceLocation TypeLoc,
4040 TypeTy *argty,
4041 OffsetOfComponent *CompPtr,
4042 unsigned NumComponents,
4043 SourceLocation RPLoc) {
4044 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4045 assert(!ArgTy.isNull() && "Missing type argument!");
4046
4047 // We must have at least one component that refers to the type, and the first
4048 // one is known to be a field designator. Verify that the ArgTy represents
4049 // a struct/union/class.
4050 if (!ArgTy->isRecordType())
Chris Lattnerd1625842008-11-24 06:25:27 +00004051 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004052
4053 // Otherwise, create a compound literal expression as the base, and
4054 // iteratively process the offsetof designators.
Eli Friedman1d242592009-01-26 01:33:06 +00004055 InitListExpr *IList =
Douglas Gregor4c678342009-01-28 21:54:33 +00004056 new (Context) InitListExpr(SourceLocation(), 0, 0, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00004057 IList->setType(ArgTy);
4058 Expr *Res =
4059 new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, IList, false);
4060
Chris Lattner9e2b75c2007-08-31 21:49:13 +00004061 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4062 // GCC extension, diagnose them.
4063 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004064 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4065 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattner9e2b75c2007-08-31 21:49:13 +00004066
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004067 for (unsigned i = 0; i != NumComponents; ++i) {
4068 const OffsetOfComponent &OC = CompPtr[i];
4069 if (OC.isBrackets) {
4070 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004071 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004072 if (!AT) {
4073 delete Res;
Chris Lattnerd1625842008-11-24 06:25:27 +00004074 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004075 }
4076
Chris Lattner704fe352007-08-30 17:59:59 +00004077 // FIXME: C++: Verify that operator[] isn't overloaded.
4078
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004079 // C99 6.5.2.1p1
4080 Expr *Idx = static_cast<Expr*>(OC.U.E);
4081 if (!Idx->getType()->isIntegerType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004082 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4083 << Idx->getSourceRange();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004084
Steve Naroff6ece14c2009-01-21 00:14:39 +00004085 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4086 OC.LocEnd);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004087 continue;
4088 }
4089
4090 const RecordType *RC = Res->getType()->getAsRecordType();
4091 if (!RC) {
4092 delete Res;
Chris Lattnerd1625842008-11-24 06:25:27 +00004093 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004094 }
4095
4096 // Get the decl corresponding to this.
4097 RecordDecl *RD = RC->getDecl();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004098 FieldDecl *MemberDecl
Douglas Gregor4c921ae2009-01-30 01:04:22 +00004099 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4100 LookupMemberName)
4101 .getAsDecl());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004102 if (!MemberDecl)
Chris Lattner3c73c412008-11-19 08:23:25 +00004103 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4104 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner704fe352007-08-30 17:59:59 +00004105
4106 // FIXME: C++: Verify that MemberDecl isn't a static field.
4107 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman51019072008-02-06 22:48:16 +00004108 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4109 // matter here.
Steve Naroff6ece14c2009-01-21 00:14:39 +00004110 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4111 MemberDecl->getType().getNonReferenceType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004112 }
4113
Steve Naroff6ece14c2009-01-21 00:14:39 +00004114 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4115 Context.getSizeType(), BuiltinLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004116}
4117
4118
Steve Naroff1b273c42007-09-16 14:56:35 +00004119Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00004120 TypeTy *arg1, TypeTy *arg2,
4121 SourceLocation RPLoc) {
4122 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4123 QualType argT2 = QualType::getFromOpaquePtr(arg2);
4124
4125 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4126
Steve Naroff6ece14c2009-01-21 00:14:39 +00004127 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
4128 argT2, RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00004129}
4130
Steve Naroff1b273c42007-09-16 14:56:35 +00004131Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00004132 ExprTy *expr1, ExprTy *expr2,
4133 SourceLocation RPLoc) {
4134 Expr *CondExpr = static_cast<Expr*>(cond);
4135 Expr *LHSExpr = static_cast<Expr*>(expr1);
4136 Expr *RHSExpr = static_cast<Expr*>(expr2);
4137
4138 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4139
4140 // The conditional expression is required to be a constant expression.
4141 llvm::APSInt condEval(32);
4142 SourceLocation ExpLoc;
4143 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004144 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4145 << CondExpr->getSourceRange();
Steve Naroffd04fdd52007-08-03 21:21:27 +00004146
4147 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4148 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
4149 RHSExpr->getType();
Steve Naroff6ece14c2009-01-21 00:14:39 +00004150 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4151 resType, RPLoc);
Steve Naroffd04fdd52007-08-03 21:21:27 +00004152}
4153
Steve Naroff4eb206b2008-09-03 18:15:37 +00004154//===----------------------------------------------------------------------===//
4155// Clang Extensions.
4156//===----------------------------------------------------------------------===//
4157
4158/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00004159void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00004160 // Analyze block parameters.
4161 BlockSemaInfo *BSI = new BlockSemaInfo();
4162
4163 // Add BSI to CurBlock.
4164 BSI->PrevBlockInfo = CurBlock;
4165 CurBlock = BSI;
4166
4167 BSI->ReturnType = 0;
4168 BSI->TheScope = BlockScope;
4169
Steve Naroff090276f2008-10-10 01:28:17 +00004170 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00004171 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00004172}
4173
4174void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00004175 // Analyze arguments to block.
4176 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4177 "Not a function declarator!");
4178 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
4179
Steve Naroff090276f2008-10-10 01:28:17 +00004180 CurBlock->hasPrototype = FTI.hasPrototype;
4181 CurBlock->isVariadic = true;
Steve Naroff4eb206b2008-09-03 18:15:37 +00004182
4183 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4184 // no arguments, not a function that takes a single void argument.
4185 if (FTI.hasPrototype &&
4186 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4187 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4188 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4189 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00004190 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00004191 } else if (FTI.hasPrototype) {
4192 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff090276f2008-10-10 01:28:17 +00004193 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4194 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00004195 }
Steve Naroff090276f2008-10-10 01:28:17 +00004196 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4197
4198 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4199 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4200 // If this has an identifier, add it to the scope stack.
4201 if ((*AI)->getIdentifier())
4202 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004203}
4204
4205/// ActOnBlockError - If there is an error parsing a block, this callback
4206/// is invoked to pop the information about the block from the action impl.
4207void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4208 // Ensure that CurBlock is deleted.
4209 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4210
4211 // Pop off CurBlock, handle nested blocks.
4212 CurBlock = CurBlock->PrevBlockInfo;
4213
4214 // FIXME: Delete the ParmVarDecl objects as well???
4215
4216}
4217
4218/// ActOnBlockStmtExpr - This is called when the body of a block statement
4219/// literal was successfully completed. ^(int x){...}
4220Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4221 Scope *CurScope) {
4222 // Ensure that CurBlock is deleted.
4223 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
4224 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
4225
Steve Naroff090276f2008-10-10 01:28:17 +00004226 PopDeclContext();
4227
Steve Naroff4eb206b2008-09-03 18:15:37 +00004228 // Pop off CurBlock, handle nested blocks.
4229 CurBlock = CurBlock->PrevBlockInfo;
4230
4231 QualType RetTy = Context.VoidTy;
4232 if (BSI->ReturnType)
4233 RetTy = QualType(BSI->ReturnType, 0);
4234
4235 llvm::SmallVector<QualType, 8> ArgTypes;
4236 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4237 ArgTypes.push_back(BSI->Params[i]->getType());
4238
4239 QualType BlockTy;
4240 if (!BSI->hasPrototype)
4241 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4242 else
4243 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004244 BSI->isVariadic, 0);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004245
4246 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff56ee6892008-10-08 17:01:13 +00004247
Steve Naroff1c90bfc2008-10-08 18:44:00 +00004248 BSI->TheDecl->setBody(Body.take());
Steve Naroff6ece14c2009-01-21 00:14:39 +00004249 return new (Context) BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004250}
4251
Nate Begeman67295d02008-01-30 20:50:20 +00004252/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begemane2ce1d92008-01-17 17:46:27 +00004253/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begeman67295d02008-01-30 20:50:20 +00004254/// The number of arguments has already been validated to match the number of
4255/// arguments in FnType.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004256static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4257 ASTContext &Context) {
Nate Begemane2ce1d92008-01-17 17:46:27 +00004258 unsigned NumParams = FnType->getNumArgs();
Nate Begemand6595fa2008-04-18 23:35:14 +00004259 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00004260 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4261 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begemand6595fa2008-04-18 23:35:14 +00004262
4263 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begemane2ce1d92008-01-17 17:46:27 +00004264 return false;
Nate Begemand6595fa2008-04-18 23:35:14 +00004265 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00004266 return true;
4267}
4268
4269Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4270 SourceLocation *CommaLocs,
4271 SourceLocation BuiltinLoc,
4272 SourceLocation RParenLoc) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00004273 // __builtin_overload requires at least 2 arguments
4274 if (NumArgs < 2)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004275 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4276 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004277
Nate Begemane2ce1d92008-01-17 17:46:27 +00004278 // The first argument is required to be a constant expression. It tells us
4279 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begeman796ef3d2008-01-31 05:38:29 +00004280 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004281 Expr *NParamsExpr = Args[0];
4282 llvm::APSInt constEval(32);
4283 SourceLocation ExpLoc;
4284 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004285 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4286 << NParamsExpr->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004287
4288 // Verify that the number of parameters is > 0
4289 unsigned NumParams = constEval.getZExtValue();
4290 if (NumParams == 0)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004291 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4292 << NParamsExpr->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004293 // Verify that we have at least 1 + NumParams arguments to the builtin.
4294 if ((NumParams + 1) > NumArgs)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004295 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4296 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004297
4298 // Figure out the return type, by matching the args to one of the functions
Nate Begeman67295d02008-01-30 20:50:20 +00004299 // listed after the parameters.
Nate Begeman796ef3d2008-01-31 05:38:29 +00004300 OverloadExpr *OE = 0;
Nate Begemane2ce1d92008-01-17 17:46:27 +00004301 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4302 // UsualUnaryConversions will convert the function DeclRefExpr into a
4303 // pointer to function.
4304 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerb77792e2008-07-26 22:17:49 +00004305 const FunctionTypeProto *FnType = 0;
4306 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4307 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004308
4309 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4310 // parameters, and the number of parameters must match the value passed to
4311 // the builtin.
4312 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004313 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4314 << Fn->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004315
4316 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begeman67295d02008-01-30 20:50:20 +00004317 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begemane2ce1d92008-01-17 17:46:27 +00004318 // If they match, return a new OverloadExpr.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004319 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00004320 if (OE)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004321 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4322 << OE->getFn()->getSourceRange();
Nate Begeman796ef3d2008-01-31 05:38:29 +00004323 // Remember our match, and continue processing the remaining arguments
4324 // to catch any errors.
Steve Naroff6ece14c2009-01-21 00:14:39 +00004325 OE = new (Context) OverloadExpr(Args, NumArgs, i,
Douglas Gregor9d293df2008-10-28 00:22:11 +00004326 FnType->getResultType().getNonReferenceType(),
Nate Begeman796ef3d2008-01-31 05:38:29 +00004327 BuiltinLoc, RParenLoc);
4328 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00004329 }
Nate Begeman796ef3d2008-01-31 05:38:29 +00004330 // Return the newly created OverloadExpr node, if we succeded in matching
4331 // exactly one of the candidate functions.
4332 if (OE)
4333 return OE;
Nate Begemane2ce1d92008-01-17 17:46:27 +00004334
4335 // If we didn't find a matching function Expr in the __builtin_overload list
4336 // the return an error.
4337 std::string typeNames;
Nate Begeman67295d02008-01-30 20:50:20 +00004338 for (unsigned i = 0; i != NumParams; ++i) {
4339 if (i != 0) typeNames += ", ";
4340 typeNames += Args[i+1]->getType().getAsString();
4341 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00004342
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004343 return Diag(BuiltinLoc, diag::err_overload_no_match)
4344 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004345}
4346
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004347Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4348 ExprTy *expr, TypeTy *type,
Chris Lattner5cf216b2008-01-04 18:04:52 +00004349 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004350 Expr *E = static_cast<Expr*>(expr);
4351 QualType T = QualType::getFromOpaquePtr(type);
4352
4353 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00004354
4355 // Get the va_list type
4356 QualType VaListType = Context.getBuiltinVaListType();
4357 // Deal with implicit array decay; for example, on x86-64,
4358 // va_list is an array, but it's supposed to decay to
4359 // a pointer for va_arg.
4360 if (VaListType->isArrayType())
4361 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmanefbe85c2008-08-20 22:17:17 +00004362 // Make sure the input expression also decays appropriately.
4363 UsualUnaryConversions(E);
Eli Friedmanc34bcde2008-08-09 23:32:40 +00004364
4365 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004366 return Diag(E->getLocStart(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004367 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerd1625842008-11-24 06:25:27 +00004368 << E->getType() << E->getSourceRange();
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004369
4370 // FIXME: Warn if a non-POD type is passed in.
4371
Steve Naroff6ece14c2009-01-21 00:14:39 +00004372 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004373}
4374
Douglas Gregor2d8b2732008-11-29 04:51:27 +00004375Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4376 // The type of __null will be int or long, depending on the size of
4377 // pointers on the target.
4378 QualType Ty;
4379 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4380 Ty = Context.IntTy;
4381 else
4382 Ty = Context.LongTy;
4383
Steve Naroff6ece14c2009-01-21 00:14:39 +00004384 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregor2d8b2732008-11-29 04:51:27 +00004385}
4386
Chris Lattner5cf216b2008-01-04 18:04:52 +00004387bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4388 SourceLocation Loc,
4389 QualType DstType, QualType SrcType,
4390 Expr *SrcExpr, const char *Flavor) {
4391 // Decode the result (notice that AST's are still created for extensions).
4392 bool isInvalid = false;
4393 unsigned DiagKind;
4394 switch (ConvTy) {
4395 default: assert(0 && "Unknown conversion type");
4396 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00004397 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00004398 DiagKind = diag::ext_typecheck_convert_pointer_int;
4399 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00004400 case IntToPointer:
4401 DiagKind = diag::ext_typecheck_convert_int_pointer;
4402 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004403 case IncompatiblePointer:
4404 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4405 break;
4406 case FunctionVoidPointer:
4407 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4408 break;
4409 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00004410 // If the qualifiers lost were because we were applying the
4411 // (deprecated) C++ conversion from a string literal to a char*
4412 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4413 // Ideally, this check would be performed in
4414 // CheckPointerTypesForAssignment. However, that would require a
4415 // bit of refactoring (so that the second argument is an
4416 // expression, rather than a type), which should be done as part
4417 // of a larger effort to fix CheckPointerTypesForAssignment for
4418 // C++ semantics.
4419 if (getLangOptions().CPlusPlus &&
4420 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4421 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004422 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4423 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004424 case IntToBlockPointer:
4425 DiagKind = diag::err_int_to_block_pointer;
4426 break;
4427 case IncompatibleBlockPointer:
Steve Naroffba80c9a2008-09-24 23:31:10 +00004428 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004429 break;
Steve Naroff39579072008-10-14 22:18:38 +00004430 case IncompatibleObjCQualifiedId:
4431 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4432 // it can give a more specific diagnostic.
4433 DiagKind = diag::warn_incompatible_qualified_id;
4434 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004435 case IncompatibleVectors:
4436 DiagKind = diag::warn_incompatible_vectors;
4437 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004438 case Incompatible:
4439 DiagKind = diag::err_typecheck_convert_incompatible;
4440 isInvalid = true;
4441 break;
4442 }
4443
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004444 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4445 << SrcExpr->getSourceRange();
Chris Lattner5cf216b2008-01-04 18:04:52 +00004446 return isInvalid;
4447}
Anders Carlssone21555e2008-11-30 19:50:32 +00004448
4449bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4450{
4451 Expr::EvalResult EvalResult;
4452
4453 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4454 EvalResult.HasSideEffects) {
4455 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4456
4457 if (EvalResult.Diag) {
4458 // We only show the note if it's not the usual "invalid subexpression"
4459 // or if it's actually in a subexpression.
4460 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4461 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4462 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4463 }
4464
4465 return true;
4466 }
4467
4468 if (EvalResult.Diag) {
4469 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4470 E->getSourceRange();
4471
4472 // Print the reason it's not a constant.
4473 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4474 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4475 }
4476
4477 if (Result)
4478 *Result = EvalResult.Val.getInt();
4479 return false;
4480}