blob: 129967a14b624e907fba52c074f28d8088e93490 [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,
366 const CXXScopeSpec *SS) {
Douglas Gregor10c42622008-11-18 15:03:34 +0000367 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS);
368}
369
Douglas Gregor1a49af92009-01-06 05:10:23 +0000370/// BuildDeclRefExpr - Build either a DeclRefExpr or a
371/// QualifiedDeclRefExpr based on whether or not SS is a
372/// nested-name-specifier.
373DeclRefExpr *Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
374 bool TypeDependent, bool ValueDependent,
375 const CXXScopeSpec *SS) {
Steve Naroff6ece14c2009-01-21 00:14:39 +0000376 if (SS && !SS->isEmpty())
377 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Steve Naroff0a473932009-01-20 19:53:53 +0000378 ValueDependent, SS->getRange().getBegin());
Steve Naroff6ece14c2009-01-21 00:14:39 +0000379 else
380 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor1a49af92009-01-06 05:10:23 +0000381}
382
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000383/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
384/// variable corresponding to the anonymous union or struct whose type
385/// is Record.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000386static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000387 assert(Record->isAnonymousStructOrUnion() &&
388 "Record must be an anonymous struct or union!");
389
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000390 // FIXME: Once Decls are directly linked together, this will
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000391 // be an O(1) operation rather than a slow walk through DeclContext's
392 // vector (which itself will be eliminated). DeclGroups might make
393 // this even better.
394 DeclContext *Ctx = Record->getDeclContext();
395 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
396 DEnd = Ctx->decls_end();
397 D != DEnd; ++D) {
398 if (*D == Record) {
399 // The object for the anonymous struct/union directly
400 // follows its type in the list of declarations.
401 ++D;
402 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000403 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000404 return *D;
405 }
406 }
407
408 assert(false && "Missing object for anonymous record");
409 return 0;
410}
411
Sebastian Redlcd965b92009-01-18 18:53:16 +0000412Sema::OwningExprResult
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000413Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
414 FieldDecl *Field,
415 Expr *BaseObjectExpr,
416 SourceLocation OpLoc) {
417 assert(Field->getDeclContext()->isRecord() &&
418 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
419 && "Field must be stored inside an anonymous struct or union");
420
421 // Construct the sequence of field member references
422 // we'll have to perform to get to the field in the anonymous
423 // union/struct. The list of members is built from the field
424 // outward, so traverse it backwards to go from an object in
425 // the current context to the field we found.
426 llvm::SmallVector<FieldDecl *, 4> AnonFields;
427 AnonFields.push_back(Field);
428 VarDecl *BaseObject = 0;
429 DeclContext *Ctx = Field->getDeclContext();
430 do {
431 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000432 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000433 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
434 AnonFields.push_back(AnonField);
435 else {
436 BaseObject = cast<VarDecl>(AnonObject);
437 break;
438 }
439 Ctx = Ctx->getParent();
440 } while (Ctx->isRecord() &&
441 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
442
443 // Build the expression that refers to the base object, from
444 // which we will build a sequence of member references to each
445 // of the anonymous union objects and, eventually, the field we
446 // found via name lookup.
447 bool BaseObjectIsPointer = false;
448 unsigned ExtraQuals = 0;
449 if (BaseObject) {
450 // BaseObject is an anonymous struct/union variable (and is,
451 // therefore, not part of another non-anonymous record).
452 delete BaseObjectExpr;
453
Steve Naroff6ece14c2009-01-21 00:14:39 +0000454 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000455 SourceLocation());
456 ExtraQuals
457 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
458 } else if (BaseObjectExpr) {
459 // The caller provided the base object expression. Determine
460 // whether its a pointer and whether it adds any qualifiers to the
461 // anonymous struct/union fields we're looking into.
462 QualType ObjectType = BaseObjectExpr->getType();
463 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
464 BaseObjectIsPointer = true;
465 ObjectType = ObjectPtr->getPointeeType();
466 }
467 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
468 } else {
469 // We've found a member of an anonymous struct/union that is
470 // inside a non-anonymous struct/union, so in a well-formed
471 // program our base object expression is "this".
472 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
473 if (!MD->isStatic()) {
474 QualType AnonFieldType
475 = Context.getTagDeclType(
476 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
477 QualType ThisType = Context.getTagDeclType(MD->getParent());
478 if ((Context.getCanonicalType(AnonFieldType)
479 == Context.getCanonicalType(ThisType)) ||
480 IsDerivedFrom(ThisType, AnonFieldType)) {
481 // Our base object expression is "this".
Steve Naroff6ece14c2009-01-21 00:14:39 +0000482 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000483 MD->getThisType(Context));
484 BaseObjectIsPointer = true;
485 }
486 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000487 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
488 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000489 }
490 ExtraQuals = MD->getTypeQualifiers();
491 }
492
493 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000494 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
495 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000496 }
497
498 // Build the implicit member references to the field of the
499 // anonymous struct/union.
500 Expr *Result = BaseObjectExpr;
501 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
502 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
503 FI != FIEnd; ++FI) {
504 QualType MemberType = (*FI)->getType();
505 if (!(*FI)->isMutable()) {
506 unsigned combinedQualifiers
507 = MemberType.getCVRQualifiers() | ExtraQuals;
508 MemberType = MemberType.getQualifiedType(combinedQualifiers);
509 }
Steve Naroff6ece14c2009-01-21 00:14:39 +0000510 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
511 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000512 BaseObjectIsPointer = false;
513 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
514 OpLoc = SourceLocation();
515 }
516
Sebastian Redlcd965b92009-01-18 18:53:16 +0000517 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000518}
519
Douglas Gregor10c42622008-11-18 15:03:34 +0000520/// ActOnDeclarationNameExpr - The parser has read some kind of name
521/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
522/// performs lookup on that name and returns an expression that refers
523/// to that name. This routine isn't directly called from the parser,
524/// because the parser doesn't know about DeclarationName. Rather,
525/// this routine is called by ActOnIdentifierExpr,
526/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
527/// which form the DeclarationName from the corresponding syntactic
528/// forms.
529///
530/// HasTrailingLParen indicates whether this identifier is used in a
531/// function call context. LookupCtx is only used for a C++
532/// qualified-id (foo::bar) to indicate the class or namespace that
533/// the identifier must be a member of.
Douglas Gregor5c37de72008-12-06 00:22:45 +0000534///
535/// If ForceResolution is true, then we will attempt to resolve the
536/// name even if it looks like a dependent name. This option is off by
537/// default.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000538Sema::OwningExprResult
539Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
540 DeclarationName Name, bool HasTrailingLParen,
541 const CXXScopeSpec *SS, bool ForceResolution) {
Douglas Gregor5c37de72008-12-06 00:22:45 +0000542 if (S->getTemplateParamParent() && Name.getAsIdentifierInfo() &&
543 HasTrailingLParen && !SS && !ForceResolution) {
544 // We've seen something of the form
545 // identifier(
546 // and we are in a template, so it is likely that 's' is a
547 // dependent name. However, we won't know until we've parsed all
548 // of the call arguments. So, build a CXXDependentNameExpr node
549 // to represent this name. Then, if it turns out that none of the
550 // arguments are type-dependent, we'll force the resolution of the
551 // dependent name at that point.
Steve Naroff6ece14c2009-01-21 00:14:39 +0000552 return Owned(new (Context) CXXDependentNameExpr(Name.getAsIdentifierInfo(),
553 Context.DependentTy, Loc));
Douglas Gregor5c37de72008-12-06 00:22:45 +0000554 }
555
Chris Lattner8a934232008-03-31 00:36:02 +0000556 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor7176fff2009-01-15 00:26:24 +0000557 Decl *D = 0;
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000558 if (SS && SS->isInvalid())
559 return ExprError();
560 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000561
Sebastian Redlcd965b92009-01-18 18:53:16 +0000562 if (Lookup.isAmbiguous()) {
563 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
564 SS && SS->isSet() ? SS->getRange()
565 : SourceRange());
566 return ExprError();
567 } else
Douglas Gregor7176fff2009-01-15 00:26:24 +0000568 D = Lookup.getAsDecl();
Douglas Gregor5c37de72008-12-06 00:22:45 +0000569
Chris Lattner8a934232008-03-31 00:36:02 +0000570 // If this reference is in an Objective-C method, then ivar lookup happens as
571 // well.
Douglas Gregor10c42622008-11-18 15:03:34 +0000572 IdentifierInfo *II = Name.getAsIdentifierInfo();
573 if (II && getCurMethodDecl()) {
Chris Lattner8a934232008-03-31 00:36:02 +0000574 // There are two cases to handle here. 1) scoped lookup could have failed,
575 // in which case we should look for an ivar. 2) scoped lookup could have
576 // found a decl, but that decl is outside the current method (i.e. a global
577 // variable). In these two cases, we do a lookup for an ivar with this
578 // name, if the lookup suceeds, we replace it our current decl.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000579 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000580 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregor10c42622008-11-18 15:03:34 +0000581 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattner8a934232008-03-31 00:36:02 +0000582 // FIXME: This should use a new expr for a direct reference, don't turn
583 // this into Self->ivar, just return a BareIVarExpr or something.
584 IdentifierInfo &II = Context.Idents.get("self");
Sebastian Redlcd965b92009-01-18 18:53:16 +0000585 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000586 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
587 Loc, static_cast<Expr*>(SelfExpr.release()),
Sebastian Redlcd965b92009-01-18 18:53:16 +0000588 true, true);
Fariborz Jahanianefc4c4b2008-12-18 17:29:46 +0000589 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000590 return Owned(MRef);
Chris Lattner8a934232008-03-31 00:36:02 +0000591 }
592 }
Steve Naroff76de9d72008-08-10 19:10:41 +0000593 // Needed to implement property "super.method" notation.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000594 if (D == 0 && II->isStr("super")) {
Steve Naroffe3e9add2008-06-02 23:03:37 +0000595 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000596 getCurMethodDecl()->getClassInterface()));
Steve Naroff6ece14c2009-01-21 00:14:39 +0000597 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroffe3e9add2008-06-02 23:03:37 +0000598 }
Chris Lattner8a934232008-03-31 00:36:02 +0000599 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000600 if (D == 0) {
601 // Otherwise, this could be an implicitly declared function reference (legal
602 // in C90, extension in C99).
Douglas Gregor10c42622008-11-18 15:03:34 +0000603 if (HasTrailingLParen && II &&
Chris Lattner8a934232008-03-31 00:36:02 +0000604 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregor10c42622008-11-18 15:03:34 +0000605 D = ImplicitlyDefineFunction(Loc, *II, S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000606 else {
607 // If this name wasn't predeclared and if this is not a function call,
608 // diagnose the problem.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000609 if (SS && !SS->isEmpty())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000610 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
611 << Name << SS->getRange());
Douglas Gregor10c42622008-11-18 15:03:34 +0000612 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
613 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000614 return ExprError(Diag(Loc, diag::err_undeclared_use)
615 << Name.getAsString());
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000616 else
Sebastian Redlcd965b92009-01-18 18:53:16 +0000617 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000618 }
619 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000620
621 // We may have found a field within an anonymous union or struct
622 // (C++ [class.union]).
623 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
624 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
625 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000626
Douglas Gregor88a35142008-12-22 05:46:06 +0000627 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
628 if (!MD->isStatic()) {
629 // C++ [class.mfct.nonstatic]p2:
630 // [...] if name lookup (3.4.1) resolves the name in the
631 // id-expression to a nonstatic nontype member of class X or of
632 // a base class of X, the id-expression is transformed into a
633 // class member access expression (5.2.5) using (*this) (9.3.2)
634 // as the postfix-expression to the left of the '.' operator.
635 DeclContext *Ctx = 0;
636 QualType MemberType;
637 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
638 Ctx = FD->getDeclContext();
639 MemberType = FD->getType();
640
641 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
642 MemberType = RefType->getPointeeType();
643 else if (!FD->isMutable()) {
644 unsigned combinedQualifiers
645 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
646 MemberType = MemberType.getQualifiedType(combinedQualifiers);
647 }
648 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
649 if (!Method->isStatic()) {
650 Ctx = Method->getParent();
651 MemberType = Method->getType();
652 }
653 } else if (OverloadedFunctionDecl *Ovl
654 = dyn_cast<OverloadedFunctionDecl>(D)) {
655 for (OverloadedFunctionDecl::function_iterator
656 Func = Ovl->function_begin(),
657 FuncEnd = Ovl->function_end();
658 Func != FuncEnd; ++Func) {
659 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
660 if (!DMethod->isStatic()) {
661 Ctx = Ovl->getDeclContext();
662 MemberType = Context.OverloadTy;
663 break;
664 }
665 }
666 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000667
668 if (Ctx && Ctx->isRecord()) {
Douglas Gregor88a35142008-12-22 05:46:06 +0000669 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
670 QualType ThisType = Context.getTagDeclType(MD->getParent());
671 if ((Context.getCanonicalType(CtxType)
672 == Context.getCanonicalType(ThisType)) ||
673 IsDerivedFrom(ThisType, CtxType)) {
674 // Build the implicit member access expression.
Steve Naroff6ece14c2009-01-21 00:14:39 +0000675 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor88a35142008-12-22 05:46:06 +0000676 MD->getThisType(Context));
Steve Naroff6ece14c2009-01-21 00:14:39 +0000677 return Owned(new (Context) MemberExpr(This, true, cast<NamedDecl>(D),
Sebastian Redlcd965b92009-01-18 18:53:16 +0000678 SourceLocation(), MemberType));
Douglas Gregor88a35142008-12-22 05:46:06 +0000679 }
680 }
681 }
682 }
683
Douglas Gregor44b43212008-12-11 16:49:14 +0000684 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000685 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
686 if (MD->isStatic())
687 // "invalid use of member 'x' in static member function"
Sebastian Redlcd965b92009-01-18 18:53:16 +0000688 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
689 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000690 }
691
Douglas Gregor88a35142008-12-22 05:46:06 +0000692 // Any other ways we could have found the field in a well-formed
693 // program would have been turned into implicit member expressions
694 // above.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000695 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
696 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000697 }
Douglas Gregor88a35142008-12-22 05:46:06 +0000698
Reid Spencer5f016e22007-07-11 17:01:13 +0000699 if (isa<TypedefDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000700 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000701 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000702 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000703 if (isa<NamespaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000704 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000705
Steve Naroffdd972f22008-09-05 22:11:13 +0000706 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000707 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +0000708 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
709 false, false, SS));
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000710
Steve Naroffdd972f22008-09-05 22:11:13 +0000711 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000712
Steve Naroffdd972f22008-09-05 22:11:13 +0000713 // check if referencing an identifier with __attribute__((deprecated)).
714 if (VD->getAttr<DeprecatedAttr>())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000715 ExprError(Diag(Loc, diag::warn_deprecated) << VD->getDeclName());
716
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000717 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
718 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
719 Scope *CheckS = S;
720 while (CheckS) {
721 if (CheckS->isWithinElse() &&
722 CheckS->getControlParent()->isDeclScope(Var)) {
723 if (Var->getType()->isBooleanType())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000724 ExprError(Diag(Loc, diag::warn_value_always_false)
725 << Var->getDeclName());
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000726 else
Sebastian Redlcd965b92009-01-18 18:53:16 +0000727 ExprError(Diag(Loc, diag::warn_value_always_zero)
728 << Var->getDeclName());
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000729 break;
730 }
731
732 // Move up one more control parent to check again.
733 CheckS = CheckS->getControlParent();
734 if (CheckS)
735 CheckS = CheckS->getParent();
736 }
737 }
738 }
Steve Naroffdd972f22008-09-05 22:11:13 +0000739
740 // Only create DeclRefExpr's for valid Decl's.
741 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000742 return ExprError();
743
Chris Lattner639e2d32008-10-20 05:16:36 +0000744 // If the identifier reference is inside a block, and it refers to a value
745 // that is outside the block, create a BlockDeclRefExpr instead of a
746 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
747 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +0000748 //
Chris Lattner639e2d32008-10-20 05:16:36 +0000749 // We do not do this for things like enum constants, global variables, etc,
750 // as they do not get snapshotted.
751 //
752 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff090276f2008-10-10 01:28:17 +0000753 // The BlocksAttr indicates the variable is bound by-reference.
754 if (VD->getAttr<BlocksAttr>())
Steve Naroff6ece14c2009-01-21 00:14:39 +0000755 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroff0a473932009-01-20 19:53:53 +0000756 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd965b92009-01-18 18:53:16 +0000757
Steve Naroff090276f2008-10-10 01:28:17 +0000758 // Variable will be bound by-copy, make it const within the closure.
759 VD->getType().addConst();
Steve Naroff6ece14c2009-01-21 00:14:39 +0000760 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroff0a473932009-01-20 19:53:53 +0000761 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff090276f2008-10-10 01:28:17 +0000762 }
763 // If this reference is not in a block or if the referenced variable is
764 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +0000765
Douglas Gregor898574e2008-12-05 23:32:09 +0000766 bool TypeDependent = false;
Douglas Gregor83f96f62008-12-10 20:57:37 +0000767 bool ValueDependent = false;
768 if (getLangOptions().CPlusPlus) {
769 // C++ [temp.dep.expr]p3:
770 // An id-expression is type-dependent if it contains:
771 // - an identifier that was declared with a dependent type,
772 if (VD->getType()->isDependentType())
773 TypeDependent = true;
774 // - FIXME: a template-id that is dependent,
775 // - a conversion-function-id that specifies a dependent type,
776 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
777 Name.getCXXNameType()->isDependentType())
778 TypeDependent = true;
779 // - a nested-name-specifier that contains a class-name that
780 // names a dependent type.
781 else if (SS && !SS->isEmpty()) {
782 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
783 DC; DC = DC->getParent()) {
784 // FIXME: could stop early at namespace scope.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000785 if (DC->isRecord()) {
Douglas Gregor83f96f62008-12-10 20:57:37 +0000786 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
787 if (Context.getTypeDeclType(Record)->isDependentType()) {
788 TypeDependent = true;
789 break;
790 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000791 }
792 }
793 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000794
Douglas Gregor83f96f62008-12-10 20:57:37 +0000795 // C++ [temp.dep.constexpr]p2:
796 //
797 // An identifier is value-dependent if it is:
798 // - a name declared with a dependent type,
799 if (TypeDependent)
800 ValueDependent = true;
801 // - the name of a non-type template parameter,
802 else if (isa<NonTypeTemplateParmDecl>(VD))
803 ValueDependent = true;
804 // - a constant with integral or enumeration type and is
805 // initialized with an expression that is value-dependent
806 // (FIXME!).
807 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000808
Sebastian Redlcd965b92009-01-18 18:53:16 +0000809 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
810 TypeDependent, ValueDependent, SS));
Reid Spencer5f016e22007-07-11 17:01:13 +0000811}
812
Sebastian Redlcd965b92009-01-18 18:53:16 +0000813Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
814 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +0000815 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +0000816
Reid Spencer5f016e22007-07-11 17:01:13 +0000817 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +0000818 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +0000819 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
820 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
821 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000822 }
Chris Lattner1423ea42008-01-12 18:39:25 +0000823
Chris Lattnerfa28b302008-01-12 08:14:25 +0000824 // Pre-defined identifiers are of type char[x], where x is the length of the
825 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +0000826 unsigned Length;
Chris Lattner371f2582008-12-04 23:50:19 +0000827 if (FunctionDecl *FD = getCurFunctionDecl())
828 Length = FD->getIdentifier()->getLength();
Chris Lattnerb0da9232008-12-12 05:05:20 +0000829 else if (ObjCMethodDecl *MD = getCurMethodDecl())
830 Length = MD->getSynthesizedMethodSize();
831 else {
832 Diag(Loc, diag::ext_predef_outside_function);
833 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
834 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
835 }
Sebastian Redlcd965b92009-01-18 18:53:16 +0000836
837
Chris Lattner8f978d52008-01-12 19:32:28 +0000838 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +0000839 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +0000840 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000841 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +0000842}
843
Sebastian Redlcd965b92009-01-18 18:53:16 +0000844Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000845 llvm::SmallString<16> CharBuffer;
846 CharBuffer.resize(Tok.getLength());
847 const char *ThisTokBegin = &CharBuffer[0];
848 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000849
Reid Spencer5f016e22007-07-11 17:01:13 +0000850 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
851 Tok.getLocation(), PP);
852 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000853 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +0000854
855 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
856
Sebastian Redle91b3bc2009-01-20 22:23:13 +0000857 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
858 Literal.isWide(),
859 type, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000860}
861
Sebastian Redlcd965b92009-01-18 18:53:16 +0000862Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
863 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +0000864 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
865 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +0000866 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +0000867 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +0000868 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +0000869 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000870 }
Ted Kremenek28396602009-01-13 23:19:12 +0000871
Reid Spencer5f016e22007-07-11 17:01:13 +0000872 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +0000873 // Add padding so that NumericLiteralParser can overread by one character.
874 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000875 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +0000876
Reid Spencer5f016e22007-07-11 17:01:13 +0000877 // Get the spelling of the token, which eliminates trigraphs, etc.
878 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000879
Reid Spencer5f016e22007-07-11 17:01:13 +0000880 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
881 Tok.getLocation(), PP);
882 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000883 return ExprError();
884
Chris Lattner5d661452007-08-26 03:42:43 +0000885 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +0000886
Chris Lattner5d661452007-08-26 03:42:43 +0000887 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000888 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000889 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +0000890 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000891 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +0000892 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000893 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000894 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000895
896 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
897
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000898 // isExact will be set by GetFloatValue().
899 bool isExact = false;
Sebastian Redle91b3bc2009-01-20 22:23:13 +0000900 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
901 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +0000902
Chris Lattner5d661452007-08-26 03:42:43 +0000903 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000904 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +0000905 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000906 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +0000907
Neil Boothb9449512007-08-29 22:00:19 +0000908 // long long is a C99 feature.
909 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000910 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000911 Diag(Tok.getLocation(), diag::ext_longlong);
912
Reid Spencer5f016e22007-07-11 17:01:13 +0000913 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +0000914 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000915
Reid Spencer5f016e22007-07-11 17:01:13 +0000916 if (Literal.GetIntegerValue(ResultVal)) {
917 // If this value didn't fit into uintmax_t, warn and force to ull.
918 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000919 Ty = Context.UnsignedLongLongTy;
920 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +0000921 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000922 } else {
923 // If this value fits into a ULL, try to figure out what else it fits into
924 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000925
Reid Spencer5f016e22007-07-11 17:01:13 +0000926 // Octal, Hexadecimal, and integers with a U suffix are allowed to
927 // be an unsigned int.
928 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
929
930 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000931 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +0000932 if (!Literal.isLong && !Literal.isLongLong) {
933 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000934 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000935
Reid Spencer5f016e22007-07-11 17:01:13 +0000936 // Does it fit in a unsigned int?
937 if (ResultVal.isIntN(IntSize)) {
938 // Does it fit in a signed int?
939 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000940 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000941 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000942 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000943 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000944 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000945 }
Sebastian Redlcd965b92009-01-18 18:53:16 +0000946
Reid Spencer5f016e22007-07-11 17:01:13 +0000947 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +0000948 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000949 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000950
Reid Spencer5f016e22007-07-11 17:01:13 +0000951 // Does it fit in a unsigned long?
952 if (ResultVal.isIntN(LongSize)) {
953 // Does it fit in a signed long?
954 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000955 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000956 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000957 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000958 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000959 }
Sebastian Redlcd965b92009-01-18 18:53:16 +0000960 }
961
Reid Spencer5f016e22007-07-11 17:01:13 +0000962 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000963 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000964 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000965
Reid Spencer5f016e22007-07-11 17:01:13 +0000966 // Does it fit in a unsigned long long?
967 if (ResultVal.isIntN(LongLongSize)) {
968 // Does it fit in a signed long long?
969 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000970 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000971 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000972 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000973 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000974 }
975 }
Sebastian Redlcd965b92009-01-18 18:53:16 +0000976
Reid Spencer5f016e22007-07-11 17:01:13 +0000977 // If we still couldn't decide a type, we probably have something that
978 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000979 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000980 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000981 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000982 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000983 }
Sebastian Redlcd965b92009-01-18 18:53:16 +0000984
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000985 if (ResultVal.getBitWidth() != Width)
986 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +0000987 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +0000988 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000989 }
Sebastian Redlcd965b92009-01-18 18:53:16 +0000990
Chris Lattner5d661452007-08-26 03:42:43 +0000991 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
992 if (Literal.isImaginary)
Steve Naroff6ece14c2009-01-21 00:14:39 +0000993 Res = new (Context) ImaginaryLiteral(Res,
994 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +0000995
996 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +0000997}
998
Sebastian Redlcd965b92009-01-18 18:53:16 +0000999Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1000 SourceLocation R, ExprArg Val) {
1001 Expr *E = (Expr *)Val.release();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001002 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001003 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001004}
1005
1006/// The UsualUnaryConversions() function is *not* called by this routine.
1007/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl05189992008-11-11 17:56:53 +00001008bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1009 SourceLocation OpLoc,
1010 const SourceRange &ExprRange,
1011 bool isSizeof) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001012 // C99 6.5.3.4p1:
Chris Lattner01072922009-01-24 19:46:37 +00001013 if (isa<FunctionType>(exprType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001014 // alignof(function) is allowed.
Chris Lattner01072922009-01-24 19:46:37 +00001015 if (isSizeof)
1016 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1017 return false;
1018 }
1019
1020 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001021 Diag(OpLoc, diag::ext_sizeof_void_type)
1022 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001023 return false;
1024 }
Sebastian Redl05189992008-11-11 17:56:53 +00001025
Chris Lattner01072922009-01-24 19:46:37 +00001026 return DiagnoseIncompleteType(OpLoc, exprType,
1027 isSizeof ? diag::err_sizeof_incomplete_type :
1028 diag::err_alignof_incomplete_type,
1029 ExprRange);
Reid Spencer5f016e22007-07-11 17:01:13 +00001030}
1031
Chris Lattner31e21e02009-01-24 20:17:12 +00001032bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1033 const SourceRange &ExprRange) {
1034 E = E->IgnoreParens();
1035
1036 // alignof decl is always ok.
1037 if (isa<DeclRefExpr>(E))
1038 return false;
1039
1040 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1041 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1042 if (FD->isBitField()) {
Chris Lattnerda027472009-01-24 21:29:22 +00001043 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner31e21e02009-01-24 20:17:12 +00001044 return true;
1045 }
1046 // Other fields are ok.
1047 return false;
1048 }
1049 }
1050 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1051}
1052
Sebastian Redl05189992008-11-11 17:56:53 +00001053/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1054/// the same for @c alignof and @c __alignof
1055/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001056Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001057Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1058 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001059 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001060 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001061
Sebastian Redl05189992008-11-11 17:56:53 +00001062 QualType ArgTy;
1063 SourceRange Range;
1064 if (isType) {
1065 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1066 Range = ArgRange;
Chris Lattner694b1e42009-01-24 19:49:13 +00001067
1068 // Verify that the operand is valid.
1069 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1070 return ExprError();
Sebastian Redl05189992008-11-11 17:56:53 +00001071 } else {
1072 // Get the end location.
1073 Expr *ArgEx = (Expr *)TyOrEx;
1074 Range = ArgEx->getSourceRange();
1075 ArgTy = ArgEx->getType();
Chris Lattner694b1e42009-01-24 19:49:13 +00001076
1077 // Verify that the operand is valid.
Chris Lattner31e21e02009-01-24 20:17:12 +00001078 bool isInvalid;
Chris Lattnerda027472009-01-24 21:29:22 +00001079 if (!isSizeof) {
Chris Lattner31e21e02009-01-24 20:17:12 +00001080 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattnerda027472009-01-24 21:29:22 +00001081 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1082 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1083 isInvalid = true;
1084 } else {
1085 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1086 }
Chris Lattner31e21e02009-01-24 20:17:12 +00001087
1088 if (isInvalid) {
Chris Lattner694b1e42009-01-24 19:49:13 +00001089 DeleteExpr(ArgEx);
1090 return ExprError();
1091 }
Sebastian Redl05189992008-11-11 17:56:53 +00001092 }
1093
Sebastian Redl05189992008-11-11 17:56:53 +00001094 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001095 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner01072922009-01-24 19:46:37 +00001096 Context.getSizeType(), OpLoc,
1097 Range.getEnd()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001098}
1099
Chris Lattner5d794252007-08-24 21:41:10 +00001100QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +00001101 DefaultFunctionArrayConversion(V);
1102
Chris Lattnercc26ed72007-08-26 05:39:26 +00001103 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +00001104 if (const ComplexType *CT = V->getType()->getAsComplexType())
1105 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +00001106
1107 // Otherwise they pass through real integer and floating point types here.
1108 if (V->getType()->isArithmeticType())
1109 return V->getType();
1110
1111 // Reject anything else.
Chris Lattnerd1625842008-11-24 06:25:27 +00001112 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnercc26ed72007-08-26 05:39:26 +00001113 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001114}
1115
1116
Reid Spencer5f016e22007-07-11 17:01:13 +00001117
Sebastian Redl0eb23302009-01-19 00:08:26 +00001118Action::OwningExprResult
1119Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1120 tok::TokenKind Kind, ExprArg Input) {
1121 Expr *Arg = (Expr *)Input.get();
Douglas Gregor74253732008-11-19 15:42:04 +00001122
Reid Spencer5f016e22007-07-11 17:01:13 +00001123 UnaryOperator::Opcode Opc;
1124 switch (Kind) {
1125 default: assert(0 && "Unknown unary op!");
1126 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1127 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1128 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001129
Douglas Gregor74253732008-11-19 15:42:04 +00001130 if (getLangOptions().CPlusPlus &&
1131 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1132 // Which overloaded operator?
Sebastian Redl0eb23302009-01-19 00:08:26 +00001133 OverloadedOperatorKind OverOp =
Douglas Gregor74253732008-11-19 15:42:04 +00001134 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1135
1136 // C++ [over.inc]p1:
1137 //
1138 // [...] If the function is a member function with one
1139 // parameter (which shall be of type int) or a non-member
1140 // function with two parameters (the second of which shall be
1141 // of type int), it defines the postfix increment operator ++
1142 // for objects of that type. When the postfix increment is
1143 // called as a result of using the ++ operator, the int
1144 // argument will have value zero.
1145 Expr *Args[2] = {
1146 Arg,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001147 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1148 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor74253732008-11-19 15:42:04 +00001149 };
1150
1151 // Build the candidate set for overloading
1152 OverloadCandidateSet CandidateSet;
1153 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
1154
1155 // Perform overload resolution.
1156 OverloadCandidateSet::iterator Best;
1157 switch (BestViableFunction(CandidateSet, Best)) {
1158 case OR_Success: {
1159 // We found a built-in operator or an overloaded operator.
1160 FunctionDecl *FnDecl = Best->Function;
1161
1162 if (FnDecl) {
1163 // We matched an overloaded operator. Build a call to that
1164 // operator.
1165
1166 // Convert the arguments.
1167 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1168 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001169 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001170 } else {
1171 // Convert the arguments.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001172 if (PerformCopyInitialization(Arg,
Douglas Gregor74253732008-11-19 15:42:04 +00001173 FnDecl->getParamDecl(0)->getType(),
1174 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001175 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001176 }
1177
1178 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00001179 QualType ResultTy
Douglas Gregor74253732008-11-19 15:42:04 +00001180 = FnDecl->getType()->getAsFunctionType()->getResultType();
1181 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001182
Douglas Gregor74253732008-11-19 15:42:04 +00001183 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001184 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor74253732008-11-19 15:42:04 +00001185 SourceLocation());
1186 UsualUnaryConversions(FnExpr);
1187
Sebastian Redl0eb23302009-01-19 00:08:26 +00001188 Input.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001189 return Owned(new (Context)CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy,
Steve Naroff0a473932009-01-20 19:53:53 +00001190 OpLoc));
Douglas Gregor74253732008-11-19 15:42:04 +00001191 } else {
1192 // We matched a built-in operator. Convert the arguments, then
1193 // break out so that we will build the appropriate built-in
1194 // operator node.
1195 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1196 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001197 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001198
1199 break;
Sebastian Redl0eb23302009-01-19 00:08:26 +00001200 }
Douglas Gregor74253732008-11-19 15:42:04 +00001201 }
1202
1203 case OR_No_Viable_Function:
1204 // No viable function; fall through to handling this as a
1205 // built-in operator, which will produce an error message for us.
1206 break;
1207
1208 case OR_Ambiguous:
1209 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1210 << UnaryOperator::getOpcodeStr(Opc)
1211 << Arg->getSourceRange();
1212 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001213 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001214 }
1215
1216 // Either we found no viable overloaded operator or we matched a
1217 // built-in operator. In either case, fall through to trying to
1218 // build a built-in operation.
1219 }
1220
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00001221 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1222 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001223 if (result.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001224 return ExprError();
1225 Input.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001226 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001227}
1228
Sebastian Redl0eb23302009-01-19 00:08:26 +00001229Action::OwningExprResult
1230Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1231 ExprArg Idx, SourceLocation RLoc) {
1232 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1233 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner12d9ff62007-07-16 00:14:47 +00001234
Douglas Gregor337c6b92008-11-19 17:17:41 +00001235 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00001236 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00001237 LHSExp->getType()->isEnumeralType() ||
1238 RHSExp->getType()->isRecordType() ||
1239 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor337c6b92008-11-19 17:17:41 +00001240 // Add the appropriate overloaded operators (C++ [over.match.oper])
1241 // to the candidate set.
1242 OverloadCandidateSet CandidateSet;
1243 Expr *Args[2] = { LHSExp, RHSExp };
1244 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001245
Douglas Gregor337c6b92008-11-19 17:17:41 +00001246 // Perform overload resolution.
1247 OverloadCandidateSet::iterator Best;
1248 switch (BestViableFunction(CandidateSet, Best)) {
1249 case OR_Success: {
1250 // We found a built-in operator or an overloaded operator.
1251 FunctionDecl *FnDecl = Best->Function;
1252
1253 if (FnDecl) {
1254 // We matched an overloaded operator. Build a call to that
1255 // operator.
1256
1257 // Convert the arguments.
1258 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1259 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1260 PerformCopyInitialization(RHSExp,
1261 FnDecl->getParamDecl(0)->getType(),
1262 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001263 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001264 } else {
1265 // Convert the arguments.
1266 if (PerformCopyInitialization(LHSExp,
1267 FnDecl->getParamDecl(0)->getType(),
1268 "passing") ||
1269 PerformCopyInitialization(RHSExp,
1270 FnDecl->getParamDecl(1)->getType(),
1271 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001272 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001273 }
1274
1275 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00001276 QualType ResultTy
Douglas Gregor337c6b92008-11-19 17:17:41 +00001277 = FnDecl->getType()->getAsFunctionType()->getResultType();
1278 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001279
Douglas Gregor337c6b92008-11-19 17:17:41 +00001280 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001281 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor337c6b92008-11-19 17:17:41 +00001282 SourceLocation());
1283 UsualUnaryConversions(FnExpr);
1284
Sebastian Redl0eb23302009-01-19 00:08:26 +00001285 Base.release();
1286 Idx.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001287 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, Args, 2,
1288 ResultTy, LLoc));
Douglas Gregor337c6b92008-11-19 17:17:41 +00001289 } else {
1290 // We matched a built-in operator. Convert the arguments, then
1291 // break out so that we will build the appropriate built-in
1292 // operator node.
1293 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1294 "passing") ||
1295 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1296 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001297 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001298
1299 break;
1300 }
1301 }
1302
1303 case OR_No_Viable_Function:
1304 // No viable function; fall through to handling this as a
1305 // built-in operator, which will produce an error message for us.
1306 break;
1307
1308 case OR_Ambiguous:
1309 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1310 << "[]"
1311 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1312 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001313 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001314 }
1315
1316 // Either we found no viable overloaded operator or we matched a
1317 // built-in operator. In either case, fall through to trying to
1318 // build a built-in operation.
1319 }
1320
Chris Lattner12d9ff62007-07-16 00:14:47 +00001321 // Perform default conversions.
1322 DefaultFunctionArrayConversion(LHSExp);
1323 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001324
Chris Lattner12d9ff62007-07-16 00:14:47 +00001325 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001326
Reid Spencer5f016e22007-07-11 17:01:13 +00001327 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001328 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +00001329 // in the subscript position. As a result, we need to derive the array base
1330 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001331 Expr *BaseExpr, *IndexExpr;
1332 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +00001333 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001334 BaseExpr = LHSExp;
1335 IndexExpr = RHSExp;
1336 // FIXME: need to deal with const...
1337 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +00001338 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001339 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001340 BaseExpr = RHSExp;
1341 IndexExpr = LHSExp;
1342 // FIXME: need to deal with const...
1343 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +00001344 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1345 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001346 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00001347
Chris Lattner12d9ff62007-07-16 00:14:47 +00001348 // FIXME: need to deal with const...
1349 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001350 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00001351 return ExprError(Diag(LHSExp->getLocStart(),
1352 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1353 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001354 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +00001355 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001356 return ExprError(Diag(IndexExpr->getLocStart(),
1357 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001358
Chris Lattner12d9ff62007-07-16 00:14:47 +00001359 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1360 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001361 // void (*)(int)) and pointers to incomplete types. Functions are not
1362 // objects in C99.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001363 if (!ResultType->isObjectType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001364 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001365 diag::err_typecheck_subscript_not_object)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001366 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner12d9ff62007-07-16 00:14:47 +00001367
Sebastian Redl0eb23302009-01-19 00:08:26 +00001368 Base.release();
1369 Idx.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001370 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1371 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001372}
1373
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001374QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001375CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001376 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +00001377 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +00001378
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001379 // The vector accessor can't exceed the number of elements.
1380 const char *compStr = CompName.getName();
Nate Begeman353417a2009-01-18 01:47:54 +00001381
1382 // This flag determines whether or not the component is one of the four
1383 // special names that indicate a subset of exactly half the elements are
1384 // to be selected.
1385 bool HalvingSwizzle = false;
1386
1387 // This flag determines whether or not CompName has an 's' char prefix,
1388 // indicating that it is a string of hex values to be used as vector indices.
1389 bool HexSwizzle = *compStr == 's';
Nate Begeman8a997642008-05-09 06:41:27 +00001390
1391 // Check that we've found one of the special components, or that the component
1392 // names must come from the same set.
1393 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00001394 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1395 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00001396 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001397 do
1398 compStr++;
1399 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00001400 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001401 do
1402 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001403 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00001404 }
Nate Begeman353417a2009-01-18 01:47:54 +00001405
1406 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001407 // We didn't get to the end of the string. This means the component names
1408 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001409 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1410 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001411 return QualType();
1412 }
Nate Begeman353417a2009-01-18 01:47:54 +00001413
1414 // Ensure no component accessor exceeds the width of the vector type it
1415 // operates on.
1416 if (!HalvingSwizzle) {
1417 compStr = CompName.getName();
1418
1419 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001420 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001421
1422 while (*compStr) {
1423 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1424 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1425 << baseType << SourceRange(CompLoc);
1426 return QualType();
1427 }
1428 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001429 }
Nate Begeman8a997642008-05-09 06:41:27 +00001430
Nate Begeman353417a2009-01-18 01:47:54 +00001431 // If this is a halving swizzle, verify that the base type has an even
1432 // number of elements.
1433 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001434 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00001435 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00001436 return QualType();
1437 }
1438
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001439 // The component accessor looks fine - now we need to compute the actual type.
1440 // The vector type is implied by the component accessor. For example,
1441 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00001442 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00001443 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman353417a2009-01-18 01:47:54 +00001444 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1445 : CompName.getLength();
1446 if (HexSwizzle)
1447 CompSize--;
1448
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001449 if (CompSize == 1)
1450 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +00001451
Nate Begeman213541a2008-04-18 23:10:10 +00001452 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroffbea0b342007-07-29 16:33:31 +00001453 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00001454 // diagostics look bad. We want extended vector types to appear built-in.
1455 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1456 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1457 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00001458 }
1459 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001460}
1461
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001462/// constructSetterName - Return the setter name for the given
1463/// identifier, i.e. "set" + Name where the initial character of Name
1464/// has been capitalized.
1465// FIXME: Merge with same routine in Parser. But where should this
1466// live?
1467static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1468 const IdentifierInfo *Name) {
1469 llvm::SmallString<100> SelectorName;
1470 SelectorName = "set";
1471 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1472 SelectorName[3] = toupper(SelectorName[3]);
1473 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1474}
1475
Sebastian Redl0eb23302009-01-19 00:08:26 +00001476Action::OwningExprResult
1477Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1478 tok::TokenKind OpKind, SourceLocation MemberLoc,
1479 IdentifierInfo &Member) {
1480 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001481 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +00001482
1483 // Perform default conversions.
1484 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001485
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001486 QualType BaseType = BaseExpr->getType();
1487 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00001488
Chris Lattner68a057b2008-07-21 04:36:39 +00001489 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1490 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +00001491 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +00001492 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001493 BaseType = PT->getPointeeType();
Douglas Gregor8ba10742008-11-20 16:27:02 +00001494 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001495 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1496 MemberLoc, Member));
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001497 else
Sebastian Redl0eb23302009-01-19 00:08:26 +00001498 return ExprError(Diag(MemberLoc,
1499 diag::err_typecheck_member_reference_arrow)
1500 << BaseType << BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001501 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001502
Chris Lattner68a057b2008-07-21 04:36:39 +00001503 // Handle field access to simple records. This also handles access to fields
1504 // of the ObjC 'id' struct.
Chris Lattnerc8629632007-07-31 19:29:30 +00001505 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001506 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00001507 if (DiagnoseIncompleteType(OpLoc, BaseType,
1508 diag::err_typecheck_incomplete_tag,
1509 BaseExpr->getSourceRange()))
1510 return ExprError();
1511
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001512 // The record definition is complete, now make sure the member is valid.
Douglas Gregor44b43212008-12-11 16:49:14 +00001513 // FIXME: Qualified name lookup for C++ is a bit more complicated
1514 // than this.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001515 LookupResult Result
Douglas Gregor7176fff2009-01-15 00:26:24 +00001516 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001517 LookupMemberName, false);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001518
1519 Decl *MemberDecl = 0;
1520 if (!Result)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001521 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1522 << &Member << BaseExpr->getSourceRange());
1523 else if (Result.isAmbiguous()) {
1524 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1525 MemberLoc, BaseExpr->getSourceRange());
1526 return ExprError();
1527 } else
Douglas Gregor7176fff2009-01-15 00:26:24 +00001528 MemberDecl = Result;
Douglas Gregor44b43212008-12-11 16:49:14 +00001529
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001530 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001531 // We may have found a field within an anonymous union or struct
1532 // (C++ [class.union]).
1533 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001534 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001535 BaseExpr, OpLoc);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001536
Douglas Gregor86f19402008-12-20 23:49:58 +00001537 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1538 // FIXME: Handle address space modifiers
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001539 QualType MemberType = FD->getType();
Douglas Gregor86f19402008-12-20 23:49:58 +00001540 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1541 MemberType = Ref->getPointeeType();
1542 else {
1543 unsigned combinedQualifiers =
1544 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001545 if (FD->isMutable())
Douglas Gregor86f19402008-12-20 23:49:58 +00001546 combinedQualifiers &= ~QualType::Const;
1547 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1548 }
Eli Friedman51019072008-02-06 22:48:16 +00001549
Steve Naroff6ece14c2009-01-21 00:14:39 +00001550 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1551 MemberLoc, MemberType));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001552 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001553 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001554 Var, MemberLoc,
1555 Var->getType().getNonReferenceType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001556 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001557 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1558 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00001559 else if (OverloadedFunctionDecl *Ovl
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001560 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001561 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001562 MemberLoc, Context.OverloadTy));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001563 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001564 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Enum,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001565 MemberLoc, Enum->getType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001566 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001567 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1568 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman51019072008-02-06 22:48:16 +00001569
Douglas Gregor86f19402008-12-20 23:49:58 +00001570 // We found a declaration kind that we didn't expect. This is a
1571 // generic error message that tells the user that she can't refer
1572 // to this member with '.' or '->'.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001573 return ExprError(Diag(MemberLoc,
1574 diag::err_typecheck_member_reference_unknown)
1575 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001576 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001577
Chris Lattnera38e6b12008-07-21 04:59:05 +00001578 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1579 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +00001580 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00001581 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Steve Naroff6ece14c2009-01-21 00:14:39 +00001582 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1583 MemberLoc, BaseExpr,
Fariborz Jahanianefc4c4b2008-12-18 17:29:46 +00001584 OpKind == tok::arrow);
1585 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001586 return Owned(MRef);
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00001587 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001588 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1589 << IFTy->getDecl()->getDeclName() << &Member
1590 << BaseExpr->getSourceRange());
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001591 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001592
Chris Lattnera38e6b12008-07-21 04:59:05 +00001593 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1594 // pointer to a (potentially qualified) interface type.
1595 const PointerType *PTy;
1596 const ObjCInterfaceType *IFTy;
1597 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1598 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1599 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001600
Daniel Dunbar2307d312008-09-03 01:05:41 +00001601 // Search for a declared property first.
Chris Lattnera38e6b12008-07-21 04:59:05 +00001602 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001603 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl0eb23302009-01-19 00:08:26 +00001604 MemberLoc, BaseExpr));
1605
Daniel Dunbar2307d312008-09-03 01:05:41 +00001606 // Check protocols on qualified interfaces.
Chris Lattner9baefc22008-07-21 05:20:01 +00001607 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1608 E = IFTy->qual_end(); I != E; ++I)
1609 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001610 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl0eb23302009-01-19 00:08:26 +00001611 MemberLoc, BaseExpr));
Daniel Dunbar2307d312008-09-03 01:05:41 +00001612
1613 // If that failed, look for an "implicit" property by seeing if the nullary
1614 // selector is implemented.
1615
1616 // FIXME: The logic for looking up nullary and unary selectors should be
1617 // shared with the code in ActOnInstanceMessage.
1618
1619 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1620 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001621
Daniel Dunbar2307d312008-09-03 01:05:41 +00001622 // If this reference is in an @implementation, check for 'private' methods.
1623 if (!Getter)
1624 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1625 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1626 if (ObjCImplementationDecl *ImpDecl =
1627 ObjCImplementations[ClassDecl->getIdentifier()])
1628 Getter = ImpDecl->getInstanceMethod(Sel);
1629
Steve Naroff7692ed62008-10-22 19:16:27 +00001630 // Look through local category implementations associated with the class.
1631 if (!Getter) {
1632 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1633 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1634 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1635 }
1636 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00001637 if (Getter) {
1638 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001639 // will look for the matching setter, in case it is needed.
1640 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1641 &Member);
1642 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1643 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1644 if (!Setter) {
1645 // If this reference is in an @implementation, also check for 'private'
1646 // methods.
1647 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1648 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1649 if (ObjCImplementationDecl *ImpDecl =
1650 ObjCImplementations[ClassDecl->getIdentifier()])
1651 Setter = ImpDecl->getInstanceMethod(SetterSel);
1652 }
1653 // Look through local category implementations associated with the class.
1654 if (!Setter) {
1655 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1656 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1657 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1658 }
1659 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001660
1661 // FIXME: we must check that the setter has property type.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001662 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
1663 Setter, MemberLoc, BaseExpr));
Daniel Dunbar2307d312008-09-03 01:05:41 +00001664 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001665
1666 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1667 << &Member << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00001668 }
Steve Naroff18bc1642008-10-20 22:53:06 +00001669 // Handle properties on qualified "id" protocols.
1670 const ObjCQualifiedIdType *QIdTy;
1671 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1672 // Check protocols on qualified interfaces.
1673 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001674 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroff18bc1642008-10-20 22:53:06 +00001675 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001676 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl0eb23302009-01-19 00:08:26 +00001677 MemberLoc, BaseExpr));
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001678 // Also must look for a getter name which uses property syntax.
1679 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1680 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Steve Naroff6ece14c2009-01-21 00:14:39 +00001681 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
1682 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001683 }
1684 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001685
1686 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1687 << &Member << BaseType);
1688 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001689 // Handle 'field access' to vectors, such as 'V.xx'.
1690 if (BaseType->isExtVectorType() && OpKind == tok::period) {
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001691 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1692 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001693 return ExprError();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001694 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
1695 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001696 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001697
1698 return ExprError(Diag(MemberLoc,
1699 diag::err_typecheck_member_reference_struct_union)
1700 << BaseType << BaseExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001701}
1702
Douglas Gregor88a35142008-12-22 05:46:06 +00001703/// ConvertArgumentsForCall - Converts the arguments specified in
1704/// Args/NumArgs to the parameter types of the function FDecl with
1705/// function prototype Proto. Call is the call expression itself, and
1706/// Fn is the function expression. For a C++ member function, this
1707/// routine does not attempt to convert the object argument. Returns
1708/// true if the call is ill-formed.
1709bool
1710Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1711 FunctionDecl *FDecl,
1712 const FunctionTypeProto *Proto,
1713 Expr **Args, unsigned NumArgs,
1714 SourceLocation RParenLoc) {
1715 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1716 // assignment, to the types of the corresponding parameter, ...
1717 unsigned NumArgsInProto = Proto->getNumArgs();
1718 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor3fd56d72009-01-23 21:30:56 +00001719 bool Invalid = false;
1720
Douglas Gregor88a35142008-12-22 05:46:06 +00001721 // If too few arguments are available (and we don't have default
1722 // arguments for the remaining parameters), don't make the call.
1723 if (NumArgs < NumArgsInProto) {
1724 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1725 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1726 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1727 // Use default arguments for missing arguments
1728 NumArgsToCheck = NumArgsInProto;
1729 Call->setNumArgs(NumArgsInProto);
1730 }
1731
1732 // If too many are passed and not variadic, error on the extras and drop
1733 // them.
1734 if (NumArgs > NumArgsInProto) {
1735 if (!Proto->isVariadic()) {
1736 Diag(Args[NumArgsInProto]->getLocStart(),
1737 diag::err_typecheck_call_too_many_args)
1738 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1739 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1740 Args[NumArgs-1]->getLocEnd());
1741 // This deletes the extra arguments.
1742 Call->setNumArgs(NumArgsInProto);
Douglas Gregor3fd56d72009-01-23 21:30:56 +00001743 Invalid = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00001744 }
1745 NumArgsToCheck = NumArgsInProto;
1746 }
1747
1748 // Continue to check argument types (even if we have too few/many args).
1749 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1750 QualType ProtoArgType = Proto->getArgType(i);
1751
1752 Expr *Arg;
Douglas Gregor61366e92008-12-24 00:01:03 +00001753 if (i < NumArgs) {
Douglas Gregor88a35142008-12-22 05:46:06 +00001754 Arg = Args[i];
Douglas Gregor61366e92008-12-24 00:01:03 +00001755
1756 // Pass the argument.
1757 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1758 return true;
1759 } else
1760 // We already type-checked the argument, so we know it works.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001761 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor88a35142008-12-22 05:46:06 +00001762 QualType ArgType = Arg->getType();
Douglas Gregor61366e92008-12-24 00:01:03 +00001763
Douglas Gregor88a35142008-12-22 05:46:06 +00001764 Call->setArg(i, Arg);
1765 }
1766
1767 // If this is a variadic call, handle args passed through "...".
1768 if (Proto->isVariadic()) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +00001769 VariadicCallType CallType = VariadicFunction;
1770 if (Fn->getType()->isBlockPointerType())
1771 CallType = VariadicBlock; // Block
1772 else if (isa<MemberExpr>(Fn))
1773 CallType = VariadicMethod;
1774
Douglas Gregor88a35142008-12-22 05:46:06 +00001775 // Promote the arguments (C99 6.5.2.2p7).
1776 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1777 Expr *Arg = Args[i];
Anders Carlssondce5e2c2009-01-16 16:48:51 +00001778 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor88a35142008-12-22 05:46:06 +00001779 Call->setArg(i, Arg);
1780 }
1781 }
1782
Douglas Gregor3fd56d72009-01-23 21:30:56 +00001783 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00001784}
1785
Steve Narofff69936d2007-09-16 03:34:24 +00001786/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00001787/// This provides the location of the left/right parens and a list of comma
1788/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001789Action::OwningExprResult
1790Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1791 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00001792 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00001793 unsigned NumArgs = args.size();
1794 Expr *Fn = static_cast<Expr *>(fn.release());
1795 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00001796 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00001797 FunctionDecl *FDecl = NULL;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001798 OverloadedFunctionDecl *Ovl = NULL;
1799
Douglas Gregor5c37de72008-12-06 00:22:45 +00001800 // Determine whether this is a dependent call inside a C++ template,
1801 // in which case we won't do any semantic analysis now.
1802 bool Dependent = false;
1803 if (Fn->isTypeDependent()) {
1804 if (CXXDependentNameExpr *FnName = dyn_cast<CXXDependentNameExpr>(Fn)) {
1805 if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1806 Dependent = true;
1807 else {
1808 // Resolve the CXXDependentNameExpr to an actual identifier;
1809 // it wasn't really a dependent name after all.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001810 OwningExprResult Resolved
1811 = ActOnDeclarationNameExpr(S, FnName->getLocation(),
1812 FnName->getName(),
Douglas Gregor5c37de72008-12-06 00:22:45 +00001813 /*HasTrailingLParen=*/true,
1814 /*SS=*/0,
1815 /*ForceResolution=*/true);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001816 if (Resolved.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001817 return ExprError();
Douglas Gregor5c37de72008-12-06 00:22:45 +00001818 else {
1819 delete Fn;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001820 Fn = (Expr *)Resolved.release();
Douglas Gregor5c37de72008-12-06 00:22:45 +00001821 }
1822 }
1823 } else
1824 Dependent = true;
1825 } else
1826 Dependent = Expr::hasAnyTypeDependentArguments(Args, NumArgs);
1827
Douglas Gregor898574e2008-12-05 23:32:09 +00001828 // FIXME: Will need to cache the results of name lookup (including
1829 // ADL) in Fn.
Douglas Gregor5c37de72008-12-06 00:22:45 +00001830 if (Dependent)
Steve Naroff6ece14c2009-01-21 00:14:39 +00001831 return Owned(new (Context) CallExpr(Fn, Args, NumArgs,
1832 Context.DependentTy, RParenLoc));
Douglas Gregor898574e2008-12-05 23:32:09 +00001833
Douglas Gregor88a35142008-12-22 05:46:06 +00001834 // Determine whether this is a call to an object (C++ [over.call.object]).
1835 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001836 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1837 CommaLocs, RParenLoc));
Douglas Gregor88a35142008-12-22 05:46:06 +00001838
1839 // Determine whether this is a call to a member function.
1840 if (getLangOptions().CPlusPlus) {
1841 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1842 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1843 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001844 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1845 CommaLocs, RParenLoc));
Douglas Gregor88a35142008-12-22 05:46:06 +00001846 }
1847
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001848 // If we're directly calling a function or a set of overloaded
1849 // functions, get the appropriate declaration.
Douglas Gregor1a49af92009-01-06 05:10:23 +00001850 DeclRefExpr *DRExpr = NULL;
1851 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1852 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1853 else
1854 DRExpr = dyn_cast<DeclRefExpr>(Fn);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001855
Douglas Gregor1a49af92009-01-06 05:10:23 +00001856 if (DRExpr) {
1857 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1858 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001859 }
1860
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001861 if (Ovl) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00001862 FDecl = ResolveOverloadedCallFn(Fn, Ovl, LParenLoc, Args, NumArgs,
1863 CommaLocs, RParenLoc);
Douglas Gregor0a396682008-11-26 06:01:48 +00001864 if (!FDecl)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001865 return ExprError();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001866
Douglas Gregor0a396682008-11-26 06:01:48 +00001867 // Update Fn to refer to the actual function selected.
Douglas Gregor1a49af92009-01-06 05:10:23 +00001868 Expr *NewFn = 0;
1869 if (QualifiedDeclRefExpr *QDRExpr = dyn_cast<QualifiedDeclRefExpr>(DRExpr))
Steve Naroff6ece14c2009-01-21 00:14:39 +00001870 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregor1a49af92009-01-06 05:10:23 +00001871 QDRExpr->getLocation(), false, false,
1872 QDRExpr->getSourceRange().getBegin());
1873 else
Steve Naroff6ece14c2009-01-21 00:14:39 +00001874 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
1875 Fn->getSourceRange().getBegin());
Douglas Gregor0a396682008-11-26 06:01:48 +00001876 Fn->Destroy(Context);
1877 Fn = NewFn;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001878 }
Chris Lattner04421082008-04-08 04:40:51 +00001879
1880 // Promote the function operand.
1881 UsualUnaryConversions(Fn);
1882
Chris Lattner925e60d2007-12-28 05:29:59 +00001883 // Make the call expr early, before semantic checks. This guarantees cleanup
1884 // of arguments and function on error.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001885 // FIXME: Except that llvm::OwningPtr uses delete, when it really must be
1886 // Destroy(), or nothing gets cleaned up.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001887 llvm::OwningPtr<CallExpr> TheCall(new (Context) CallExpr(Fn, Args, NumArgs,
Chris Lattner925e60d2007-12-28 05:29:59 +00001888 Context.BoolTy, RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00001889
Steve Naroffdd972f22008-09-05 22:11:13 +00001890 const FunctionType *FuncT;
1891 if (!Fn->getType()->isBlockPointerType()) {
1892 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1893 // have type pointer to function".
1894 const PointerType *PT = Fn->getType()->getAsPointerType();
1895 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001896 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1897 << Fn->getType() << Fn->getSourceRange());
Steve Naroffdd972f22008-09-05 22:11:13 +00001898 FuncT = PT->getPointeeType()->getAsFunctionType();
1899 } else { // This is a block call.
1900 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1901 getAsFunctionType();
1902 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001903 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001904 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1905 << Fn->getType() << Fn->getSourceRange());
1906
Chris Lattner925e60d2007-12-28 05:29:59 +00001907 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001908 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001909
Chris Lattner925e60d2007-12-28 05:29:59 +00001910 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00001911 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
1912 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001913 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00001914 } else {
1915 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00001916
Steve Naroffb291ab62007-08-28 23:30:39 +00001917 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00001918 for (unsigned i = 0; i != NumArgs; i++) {
1919 Expr *Arg = Args[i];
1920 DefaultArgumentPromotion(Arg);
1921 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001922 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001923 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001924
Douglas Gregor88a35142008-12-22 05:46:06 +00001925 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
1926 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00001927 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
1928 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00001929
Chris Lattner59907c42007-08-10 20:18:51 +00001930 // Do special checking on direct calls to functions.
Eli Friedmand38617c2008-05-14 19:38:39 +00001931 if (FDecl)
1932 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +00001933
Sebastian Redl0eb23302009-01-19 00:08:26 +00001934 return Owned(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00001935}
1936
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001937Action::OwningExprResult
1938Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
1939 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00001940 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +00001941 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00001942 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00001943 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001944 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00001945
Eli Friedman6223c222008-05-20 05:22:08 +00001946 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001947 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001948 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
1949 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor4ec339f2009-01-19 19:26:10 +00001950 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
1951 diag::err_typecheck_decl_incomplete_type,
1952 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001953 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00001954
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001955 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001956 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001957 return ExprError();
Steve Naroffe9b12192008-01-14 18:19:28 +00001958
Chris Lattner371f2582008-12-04 23:50:19 +00001959 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00001960 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00001961 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001962 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001963 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001964 InitExpr.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001965 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
1966 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00001967}
1968
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001969Action::OwningExprResult
1970Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
1971 InitListDesignations &Designators,
1972 SourceLocation RBraceLoc) {
1973 unsigned NumInit = initlist.size();
1974 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001975
Steve Naroff08d92e42007-09-15 18:49:24 +00001976 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +00001977 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001978
Steve Naroff6ece14c2009-01-21 00:14:39 +00001979 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00001980 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001981 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00001982 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00001983}
1984
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001985/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar58d5ebb2008-08-20 03:55:42 +00001986bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001987 UsualUnaryConversions(castExpr);
1988
1989 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1990 // type needs to be scalar.
1991 if (castType->isVoidType()) {
1992 // Cast to void allows any expr type.
Douglas Gregor898574e2008-12-05 23:32:09 +00001993 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
1994 // We can't check any more until template instantiation time.
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001995 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00001996 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
1997 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
1998 (castType->isStructureType() || castType->isUnionType())) {
1999 // GCC struct/union extension: allow cast to self.
2000 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2001 << castType << castExpr->getSourceRange();
2002 } else if (castType->isUnionType()) {
2003 // GCC cast to union extension
2004 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2005 RecordDecl::field_iterator Field, FieldEnd;
2006 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2007 Field != FieldEnd; ++Field) {
2008 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2009 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2010 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2011 << castExpr->getSourceRange();
2012 break;
2013 }
2014 }
2015 if (Field == FieldEnd)
2016 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2017 << castExpr->getType() << castExpr->getSourceRange();
2018 } else {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002019 // Reject any other conversions to non-scalar types.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002020 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00002021 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002022 }
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002023 } else if (!castExpr->getType()->isScalarType() &&
2024 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002025 return Diag(castExpr->getLocStart(),
2026 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00002027 << castExpr->getType() << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002028 } else if (castExpr->getType()->isVectorType()) {
2029 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2030 return true;
2031 } else if (castType->isVectorType()) {
2032 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2033 return true;
2034 }
2035 return false;
2036}
2037
Chris Lattnerfe23e212007-12-20 00:44:32 +00002038bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00002039 assert(VectorTy->isVectorType() && "Not a vector type!");
2040
2041 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00002042 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00002043 return Diag(R.getBegin(),
2044 Ty->isVectorType() ?
2045 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002046 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002047 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00002048 } else
2049 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002050 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00002051 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00002052
2053 return false;
2054}
2055
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002056Action::OwningExprResult
2057Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2058 SourceLocation RParenLoc, ExprArg Op) {
2059 assert((Ty != 0) && (Op.get() != 0) &&
2060 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00002061
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002062 Expr *castExpr = static_cast<Expr*>(Op.release());
Steve Naroff16beff82007-07-16 23:25:18 +00002063 QualType castType = QualType::getFromOpaquePtr(Ty);
2064
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002065 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002066 return ExprError();
Steve Naroff6ece14c2009-01-21 00:14:39 +00002067 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002068 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002069}
2070
Chris Lattnera21ddb32007-11-26 01:40:58 +00002071/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2072/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +00002073inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +00002074 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002075 UsualUnaryConversions(cond);
2076 UsualUnaryConversions(lex);
2077 UsualUnaryConversions(rex);
2078 QualType condT = cond->getType();
2079 QualType lexT = lex->getType();
2080 QualType rexT = rex->getType();
2081
Reid Spencer5f016e22007-07-11 17:01:13 +00002082 // first, check the condition.
Douglas Gregor898574e2008-12-05 23:32:09 +00002083 if (!cond->isTypeDependent()) {
2084 if (!condT->isScalarType()) { // C99 6.5.15p2
2085 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
2086 return QualType();
2087 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002088 }
Chris Lattner70d67a92008-01-06 22:42:25 +00002089
2090 // Now check the two expressions.
Douglas Gregor898574e2008-12-05 23:32:09 +00002091 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
2092 return Context.DependentTy;
2093
Chris Lattner70d67a92008-01-06 22:42:25 +00002094 // If both operands have arithmetic type, do the usual arithmetic conversions
2095 // to find a common type: C99 6.5.15p3,5.
2096 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Steve Naroffa4332e22007-07-17 00:58:39 +00002097 UsualArithmeticConversions(lex, rex);
2098 return lex->getType();
2099 }
Chris Lattner70d67a92008-01-06 22:42:25 +00002100
2101 // If both operands are the same structure or union type, the result is that
2102 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002103 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner70d67a92008-01-06 22:42:25 +00002104 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +00002105 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner70d67a92008-01-06 22:42:25 +00002106 // "If both the operands have structure or union type, the result has
2107 // that type." This implies that CV qualifiers are dropped.
2108 return lexT.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002109 }
Chris Lattner70d67a92008-01-06 22:42:25 +00002110
2111 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00002112 // The following || allows only one side to be void (a GCC-ism).
2113 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedman0e724012008-06-04 19:47:51 +00002114 if (!lexT->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002115 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2116 << rex->getSourceRange();
Steve Naroffe701c0a2008-05-12 21:44:38 +00002117 if (!rexT->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002118 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2119 << lex->getSourceRange();
Eli Friedman0e724012008-06-04 19:47:51 +00002120 ImpCastExprToType(lex, Context.VoidTy);
2121 ImpCastExprToType(rex, Context.VoidTy);
2122 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00002123 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00002124 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2125 // the type of the other operand."
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002126 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2127 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssond2652772008-12-01 06:28:23 +00002128 rex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002129 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00002130 return lexT;
2131 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002132 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2133 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssond2652772008-12-01 06:28:23 +00002134 lex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002135 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00002136 return rexT;
2137 }
Chris Lattnerbd57d362008-01-06 22:50:31 +00002138 // Handle the case where both operands are pointers before we handle null
2139 // pointer constants in case both operands are null pointer constants.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002140 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2141 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2142 // get the "pointed to" types
2143 QualType lhptee = LHSPT->getPointeeType();
2144 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002145
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002146 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2147 if (lhptee->isVoidType() &&
Chris Lattnerd805bec2008-04-02 06:59:01 +00002148 rhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00002149 // Figure out necessary qualifiers (C99 6.5.15p6)
2150 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00002151 QualType destType = Context.getPointerType(destPointee);
2152 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2153 ImpCastExprToType(rex, destType); // promote to void*
2154 return destType;
2155 }
Chris Lattnerd805bec2008-04-02 06:59:01 +00002156 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00002157 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00002158 QualType destType = Context.getPointerType(destPointee);
2159 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2160 ImpCastExprToType(rex, destType); // promote to void*
2161 return destType;
2162 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002163
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002164 QualType compositeType = lexT;
2165
2166 // If either type is an Objective-C object type then check
2167 // compatibility according to Objective-C.
2168 if (Context.isObjCObjectPointerType(lexT) ||
2169 Context.isObjCObjectPointerType(rexT)) {
2170 // If both operands are interfaces and either operand can be
2171 // assigned to the other, use that type as the composite
2172 // type. This allows
2173 // xxx ? (A*) a : (B*) b
2174 // where B is a subclass of A.
2175 //
2176 // Additionally, as for assignment, if either type is 'id'
2177 // allow silent coercion. Finally, if the types are
2178 // incompatible then make sure to use 'id' as the composite
2179 // type so the result is acceptable for sending messages to.
2180
2181 // FIXME: This code should not be localized to here. Also this
2182 // should use a compatible check instead of abusing the
2183 // canAssignObjCInterfaces code.
2184 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2185 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2186 if (LHSIface && RHSIface &&
2187 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2188 compositeType = lexT;
2189 } else if (LHSIface && RHSIface &&
Douglas Gregor7ffd0de2008-11-26 06:43:45 +00002190 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002191 compositeType = rexT;
2192 } else if (Context.isObjCIdType(lhptee) ||
2193 Context.isObjCIdType(rhptee)) {
2194 // FIXME: This code looks wrong, because isObjCIdType checks
2195 // the struct but getObjCIdType returns the pointer to
2196 // struct. This is horrible and should be fixed.
2197 compositeType = Context.getObjCIdType();
2198 } else {
2199 QualType incompatTy = Context.getObjCIdType();
2200 ImpCastExprToType(lex, incompatTy);
2201 ImpCastExprToType(rex, incompatTy);
2202 return incompatTy;
2203 }
2204 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2205 rhptee.getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002206 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00002207 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002208 // In this situation, we assume void* type. No especially good
2209 // reason, but this is what gcc does, and we do have to pick
2210 // to get a consistent AST.
2211 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbara56f7462008-08-26 00:41:39 +00002212 ImpCastExprToType(lex, incompatTy);
2213 ImpCastExprToType(rex, incompatTy);
2214 return incompatTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002215 }
2216 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002217 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2218 // differently qualified versions of compatible types, the result type is
2219 // a pointer to an appropriately qualified version of the *composite*
2220 // type.
Eli Friedman5835ea22008-05-16 20:37:07 +00002221 // FIXME: Need to calculate the composite type.
Eli Friedmana541d532008-02-10 22:59:36 +00002222 // FIXME: Need to add qualifiers
Eli Friedman5835ea22008-05-16 20:37:07 +00002223 ImpCastExprToType(lex, compositeType);
2224 ImpCastExprToType(rex, compositeType);
2225 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002226 }
2227 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002228 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2229 // evaluates to "struct objc_object *" (and is handled above when comparing
2230 // id with statically typed objects).
2231 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2232 // GCC allows qualified id and any Objective-C type to devolve to
2233 // id. Currently localizing to here until clear this should be
2234 // part of ObjCQualifiedIdTypesAreCompatible.
2235 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2236 (lexT->isObjCQualifiedIdType() &&
2237 Context.isObjCObjectPointerType(rexT)) ||
2238 (rexT->isObjCQualifiedIdType() &&
2239 Context.isObjCObjectPointerType(lexT))) {
2240 // FIXME: This is not the correct composite type. This only
2241 // happens to work because id can more or less be used anywhere,
2242 // however this may change the type of method sends.
2243 // FIXME: gcc adds some type-checking of the arguments and emits
2244 // (confusing) incompatible comparison warnings in some
2245 // cases. Investigate.
2246 QualType compositeType = Context.getObjCIdType();
2247 ImpCastExprToType(lex, compositeType);
2248 ImpCastExprToType(rex, compositeType);
2249 return compositeType;
2250 }
2251 }
2252
Steve Naroff61f40a22008-09-10 19:17:48 +00002253 // Selection between block pointer types is ok as long as they are the same.
2254 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2255 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2256 return lexT;
2257
Chris Lattner70d67a92008-01-06 22:42:25 +00002258 // Otherwise, the operands are not compatible.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002259 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattnerd1625842008-11-24 06:25:27 +00002260 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002261 return QualType();
2262}
2263
Steve Narofff69936d2007-09-16 03:34:24 +00002264/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00002265/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002266Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2267 SourceLocation ColonLoc,
2268 ExprArg Cond, ExprArg LHS,
2269 ExprArg RHS) {
2270 Expr *CondExpr = (Expr *) Cond.get();
2271 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00002272
2273 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2274 // was the condition.
2275 bool isLHSNull = LHSExpr == 0;
2276 if (isLHSNull)
2277 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002278
2279 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00002280 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002281 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002282 return ExprError();
2283
2284 Cond.release();
2285 LHS.release();
2286 RHS.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00002287 return Owned(new (Context) ConditionalOperator(CondExpr,
2288 isLHSNull ? 0 : LHSExpr,
2289 RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00002290}
2291
Reid Spencer5f016e22007-07-11 17:01:13 +00002292
2293// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2294// being closely modeled after the C99 spec:-). The odd characteristic of this
2295// routine is it effectively iqnores the qualifiers on the top level pointee.
2296// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2297// FIXME: add a couple examples in this comment.
Chris Lattner5cf216b2008-01-04 18:04:52 +00002298Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00002299Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2300 QualType lhptee, rhptee;
2301
2302 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002303 lhptee = lhsType->getAsPointerType()->getPointeeType();
2304 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002305
2306 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00002307 lhptee = Context.getCanonicalType(lhptee);
2308 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00002309
Chris Lattner5cf216b2008-01-04 18:04:52 +00002310 AssignConvertType ConvTy = Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00002311
2312 // C99 6.5.16.1p1: This following citation is common to constraints
2313 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2314 // qualifiers of the type *pointed to* by the right;
Chris Lattnerf46699c2008-02-20 20:55:12 +00002315 // FIXME: Handle ASQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00002316 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00002317 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00002318
2319 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2320 // incomplete type and the other is a pointer to a qualified or unqualified
2321 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002322 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00002323 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00002324 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002325
2326 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00002327 assert(rhptee->isFunctionType());
2328 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002329 }
2330
2331 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00002332 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00002333 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002334
2335 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00002336 assert(lhptee->isFunctionType());
2337 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002338 }
Eli Friedman3d815e72008-08-22 00:56:42 +00002339
2340 // Check for ObjC interfaces
2341 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2342 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2343 if (LHSIface && RHSIface &&
2344 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2345 return ConvTy;
2346
2347 // ID acts sort of like void* for ObjC interfaces
2348 if (LHSIface && Context.isObjCIdType(rhptee))
2349 return ConvTy;
2350 if (RHSIface && Context.isObjCIdType(lhptee))
2351 return ConvTy;
2352
Reid Spencer5f016e22007-07-11 17:01:13 +00002353 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2354 // unqualified versions of compatible types, ...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002355 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2356 rhptee.getUnqualifiedType()))
2357 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00002358 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002359}
2360
Steve Naroff1c7d0672008-09-04 15:10:53 +00002361/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2362/// block pointer types are compatible or whether a block and normal pointer
2363/// are compatible. It is more restrict than comparing two function pointer
2364// types.
2365Sema::AssignConvertType
2366Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2367 QualType rhsType) {
2368 QualType lhptee, rhptee;
2369
2370 // get the "pointed to" type (ignoring qualifiers at the top level)
2371 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2372 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2373
2374 // make sure we operate on the canonical type
2375 lhptee = Context.getCanonicalType(lhptee);
2376 rhptee = Context.getCanonicalType(rhptee);
2377
2378 AssignConvertType ConvTy = Compatible;
2379
2380 // For blocks we enforce that qualifiers are identical.
2381 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2382 ConvTy = CompatiblePointerDiscardsQualifiers;
2383
2384 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2385 return IncompatibleBlockPointer;
2386 return ConvTy;
2387}
2388
Reid Spencer5f016e22007-07-11 17:01:13 +00002389/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2390/// has code to accommodate several GCC extensions when type checking
2391/// pointers. Here are some objectionable examples that GCC considers warnings:
2392///
2393/// int a, *pint;
2394/// short *pshort;
2395/// struct foo *pfoo;
2396///
2397/// pint = pshort; // warning: assignment from incompatible pointer type
2398/// a = pint; // warning: assignment makes integer from pointer without a cast
2399/// pint = a; // warning: assignment makes pointer from integer without a cast
2400/// pint = pfoo; // warning: assignment from incompatible pointer type
2401///
2402/// As a result, the code for dealing with pointers is more complex than the
2403/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00002404///
Chris Lattner5cf216b2008-01-04 18:04:52 +00002405Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00002406Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00002407 // Get canonical types. We're not formatting these types, just comparing
2408 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002409 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2410 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002411
2412 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00002413 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00002414
Douglas Gregor9d293df2008-10-28 00:22:11 +00002415 // If the left-hand side is a reference type, then we are in a
2416 // (rare!) case where we've allowed the use of references in C,
2417 // e.g., as a parameter type in a built-in function. In this case,
2418 // just make sure that the type referenced is compatible with the
2419 // right-hand side type. The caller is responsible for adjusting
2420 // lhsType so that the resulting expression does not have reference
2421 // type.
2422 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2423 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00002424 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002425 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002426 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002427
Chris Lattnereca7be62008-04-07 05:30:13 +00002428 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2429 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002430 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00002431 // Relax integer conversions like we do for pointers below.
2432 if (rhsType->isIntegerType())
2433 return IntToPointer;
2434 if (lhsType->isIntegerType())
2435 return PointerToInt;
Steve Naroff39579072008-10-14 22:18:38 +00002436 return IncompatibleObjCQualifiedId;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002437 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00002438
Nate Begemanbe2341d2008-07-14 18:02:46 +00002439 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002440 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00002441 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2442 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00002443 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002444
Nate Begemanbe2341d2008-07-14 18:02:46 +00002445 // If we are allowing lax vector conversions, and LHS and RHS are both
2446 // vectors, the total size only needs to be the same. This is a bitcast;
2447 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00002448 if (getLangOptions().LaxVectorConversions &&
2449 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002450 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2451 return Compatible;
Chris Lattnere8b3e962008-01-04 23:32:24 +00002452 }
2453 return Incompatible;
2454 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002455
Chris Lattnere8b3e962008-01-04 23:32:24 +00002456 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002457 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002458
Chris Lattner78eca282008-04-07 06:49:41 +00002459 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002460 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00002461 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002462
Chris Lattner78eca282008-04-07 06:49:41 +00002463 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002464 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00002465
Steve Naroffb4406862008-09-29 18:10:17 +00002466 if (rhsType->getAsBlockPointerType()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00002467 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002468 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00002469
2470 // Treat block pointers as objects.
2471 if (getLangOptions().ObjC1 &&
2472 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2473 return Compatible;
2474 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002475 return Incompatible;
2476 }
2477
2478 if (isa<BlockPointerType>(lhsType)) {
2479 if (rhsType->isIntegerType())
2480 return IntToPointer;
2481
Steve Naroffb4406862008-09-29 18:10:17 +00002482 // Treat block pointers as objects.
2483 if (getLangOptions().ObjC1 &&
2484 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2485 return Compatible;
2486
Steve Naroff1c7d0672008-09-04 15:10:53 +00002487 if (rhsType->isBlockPointerType())
2488 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2489
2490 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2491 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002492 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002493 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00002494 return Incompatible;
2495 }
2496
Chris Lattner78eca282008-04-07 06:49:41 +00002497 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002498 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002499 if (lhsType == Context.BoolTy)
2500 return Compatible;
2501
2502 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00002503 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00002504
Chris Lattner78eca282008-04-07 06:49:41 +00002505 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002506 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00002507
2508 if (isa<BlockPointerType>(lhsType) &&
2509 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002510 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002511 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002512 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002513
Chris Lattnerfc144e22008-01-04 23:18:45 +00002514 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00002515 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002516 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00002517 }
2518 return Incompatible;
2519}
2520
Chris Lattner5cf216b2008-01-04 18:04:52 +00002521Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002522Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002523 if (getLangOptions().CPlusPlus) {
2524 if (!lhsType->isRecordType()) {
2525 // C++ 5.17p3: If the left operand is not of class type, the
2526 // expression is implicitly converted (C++ 4) to the
2527 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00002528 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2529 "assigning"))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002530 return Incompatible;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002531 else
Douglas Gregor98cd5992008-10-21 23:43:52 +00002532 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002533 }
2534
2535 // FIXME: Currently, we fall through and treat C++ classes like C
2536 // structures.
2537 }
2538
Steve Naroff529a4ad2007-11-27 17:58:44 +00002539 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2540 // a null pointer constant.
Steve Naroff39218df2008-09-04 16:56:14 +00002541 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2542 lhsType->isBlockPointerType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00002543 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002544 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00002545 return Compatible;
2546 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002547
2548 // We don't allow conversion of non-null-pointer constants to integers.
2549 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2550 return IntToBlockPointer;
2551
Chris Lattner943140e2007-10-16 02:55:40 +00002552 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00002553 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00002554 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00002555 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00002556 //
Douglas Gregor9d293df2008-10-28 00:22:11 +00002557 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00002558 if (!lhsType->isReferenceType())
2559 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00002560
Chris Lattner5cf216b2008-01-04 18:04:52 +00002561 Sema::AssignConvertType result =
2562 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Narofff1120de2007-08-24 22:33:52 +00002563
2564 // C99 6.5.16.1p2: The value of the right operand is converted to the
2565 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00002566 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2567 // so that we can use references in built-in functions even in C.
2568 // The getNonReferenceType() call makes sure that the resulting expression
2569 // does not have reference type.
Steve Narofff1120de2007-08-24 22:33:52 +00002570 if (rExpr->getType() != lhsType)
Douglas Gregor9d293df2008-10-28 00:22:11 +00002571 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Narofff1120de2007-08-24 22:33:52 +00002572 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00002573}
2574
Chris Lattner5cf216b2008-01-04 18:04:52 +00002575Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002576Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2577 return CheckAssignmentConstraints(lhsType, rhsType);
2578}
2579
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002580QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002581 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00002582 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002583 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00002584 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002585}
2586
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002587inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00002588 Expr *&rex) {
Nate Begeman1330b0e2008-04-04 01:30:25 +00002589 // For conversion purposes, we ignore any qualifiers.
2590 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002591 QualType lhsType =
2592 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2593 QualType rhsType =
2594 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002595
Nate Begemanbe2341d2008-07-14 18:02:46 +00002596 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00002597 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00002598 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00002599
Nate Begemanbe2341d2008-07-14 18:02:46 +00002600 // Handle the case of a vector & extvector type of the same size and element
2601 // type. It would be nice if we only had one vector type someday.
2602 if (getLangOptions().LaxVectorConversions)
2603 if (const VectorType *LV = lhsType->getAsVectorType())
2604 if (const VectorType *RV = rhsType->getAsVectorType())
2605 if (LV->getElementType() == RV->getElementType() &&
2606 LV->getNumElements() == RV->getNumElements())
2607 return lhsType->isExtVectorType() ? lhsType : rhsType;
2608
2609 // If the lhs is an extended vector and the rhs is a scalar of the same type
2610 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00002611 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002612 QualType eltType = V->getElementType();
2613
2614 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2615 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2616 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002617 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00002618 return lhsType;
2619 }
2620 }
2621
Nate Begemanbe2341d2008-07-14 18:02:46 +00002622 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00002623 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00002624 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002625 QualType eltType = V->getElementType();
2626
2627 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2628 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2629 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002630 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00002631 return rhsType;
2632 }
2633 }
2634
Reid Spencer5f016e22007-07-11 17:01:13 +00002635 // You cannot convert between vector values of different size.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002636 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00002637 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002638 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002639 return QualType();
2640}
2641
2642inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002643 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002644{
Daniel Dunbar69d1d002009-01-05 22:42:10 +00002645 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002646 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00002647
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002648 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002649
Steve Naroffa4332e22007-07-17 00:58:39 +00002650 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002651 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002652 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002653}
2654
2655inline QualType Sema::CheckRemainderOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002656 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002657{
Daniel Dunbar523aa602009-01-05 22:55:36 +00002658 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2659 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2660 return CheckVectorOperands(Loc, lex, rex);
2661 return InvalidOperands(Loc, lex, rex);
2662 }
Steve Naroff90045e82007-07-13 23:32:42 +00002663
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002664 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002665
Steve Naroffa4332e22007-07-17 00:58:39 +00002666 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002667 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002668 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002669}
2670
2671inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002672 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002673{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002674 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002675 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00002676
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002677 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand72d16e2008-05-18 18:08:51 +00002678
Reid Spencer5f016e22007-07-11 17:01:13 +00002679 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00002680 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002681 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002682
Eli Friedmand72d16e2008-05-18 18:08:51 +00002683 // Put any potential pointer into PExp
2684 Expr* PExp = lex, *IExp = rex;
2685 if (IExp->getType()->isPointerType())
2686 std::swap(PExp, IExp);
2687
2688 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2689 if (IExp->getType()->isIntegerType()) {
2690 // Check for arithmetic on pointers to incomplete types
2691 if (!PTy->getPointeeType()->isObjectType()) {
2692 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00002693 if (getLangOptions().CPlusPlus) {
2694 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2695 << lex->getSourceRange() << rex->getSourceRange();
2696 return QualType();
2697 }
2698
2699 // GNU extension: arithmetic on pointer to void
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002700 Diag(Loc, diag::ext_gnu_void_ptr)
2701 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002702 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00002703 if (getLangOptions().CPlusPlus) {
2704 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2705 << lex->getType() << lex->getSourceRange();
2706 return QualType();
2707 }
2708
2709 // GNU extension: arithmetic on pointer to function
2710 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00002711 << lex->getType() << lex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002712 } else {
2713 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2714 diag::err_typecheck_arithmetic_incomplete_type,
2715 lex->getSourceRange(), SourceRange(),
2716 lex->getType());
2717 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00002718 }
2719 }
2720 return PExp->getType();
2721 }
2722 }
2723
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002724 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002725}
2726
Chris Lattnereca7be62008-04-07 05:30:13 +00002727// C99 6.5.6
2728QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002729 SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00002730 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002731 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002732
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002733 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002734
Chris Lattner6e4ab612007-12-09 21:53:25 +00002735 // Enforce type constraints: C99 6.5.6p3.
2736
2737 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00002738 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002739 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00002740
2741 // Either ptr - int or ptr - ptr.
2742 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00002743 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman8e54ad02008-02-08 01:19:44 +00002744
Chris Lattner6e4ab612007-12-09 21:53:25 +00002745 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff2565eef2008-01-29 18:58:14 +00002746 if (!lpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002747 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002748 if (lpointee->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002749 Diag(Loc, diag::ext_gnu_void_ptr)
2750 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorc983b862009-01-23 00:36:41 +00002751 } else if (lpointee->isFunctionType()) {
2752 if (getLangOptions().CPlusPlus) {
2753 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2754 << lex->getType() << lex->getSourceRange();
2755 return QualType();
2756 }
2757
2758 // GNU extension: arithmetic on pointer to function
2759 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2760 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002761 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002762 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00002763 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002764 return QualType();
2765 }
2766 }
2767
2768 // The result type of a pointer-int computation is the pointer type.
2769 if (rex->getType()->isIntegerType())
2770 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00002771
Chris Lattner6e4ab612007-12-09 21:53:25 +00002772 // Handle pointer-pointer subtractions.
2773 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00002774 QualType rpointee = RHSPTy->getPointeeType();
2775
Chris Lattner6e4ab612007-12-09 21:53:25 +00002776 // RHS must be an object type, unless void (GNU).
Steve Naroff2565eef2008-01-29 18:58:14 +00002777 if (!rpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002778 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002779 if (rpointee->isVoidType()) {
2780 if (!lpointee->isVoidType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002781 Diag(Loc, diag::ext_gnu_void_ptr)
2782 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor08048882009-01-23 19:03:35 +00002783 } else if (rpointee->isFunctionType()) {
2784 if (getLangOptions().CPlusPlus) {
2785 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2786 << rex->getType() << rex->getSourceRange();
2787 return QualType();
2788 }
2789
2790 // GNU extension: arithmetic on pointer to function
2791 if (!lpointee->isFunctionType())
2792 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2793 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002794 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002795 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00002796 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002797 return QualType();
2798 }
2799 }
2800
2801 // Pointee types must be compatible.
Eli Friedmanf1c7b482008-09-02 05:09:35 +00002802 if (!Context.typesAreCompatible(
2803 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2804 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002805 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattnerd1625842008-11-24 06:25:27 +00002806 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002807 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002808 return QualType();
2809 }
2810
2811 return Context.getPointerDiffType();
2812 }
2813 }
2814
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002815 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002816}
2817
Chris Lattnereca7be62008-04-07 05:30:13 +00002818// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002819QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00002820 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00002821 // C99 6.5.7p2: Each of the operands shall have integer type.
2822 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002823 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002824
Chris Lattnerca5eede2007-12-12 05:47:28 +00002825 // Shifts don't perform usual arithmetic conversions, they just do integer
2826 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00002827 if (!isCompAssign)
2828 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00002829 UsualUnaryConversions(rex);
2830
2831 // "The type of the result is that of the promoted left operand."
2832 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002833}
2834
Eli Friedman3d815e72008-08-22 00:56:42 +00002835static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2836 ASTContext& Context) {
2837 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2838 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2839 // ID acts sort of like void* for ObjC interfaces
2840 if (LHSIface && Context.isObjCIdType(RHS))
2841 return true;
2842 if (RHSIface && Context.isObjCIdType(LHS))
2843 return true;
2844 if (!LHSIface || !RHSIface)
2845 return false;
2846 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2847 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2848}
2849
Chris Lattnereca7be62008-04-07 05:30:13 +00002850// C99 6.5.8
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002851QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00002852 bool isRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002853 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002854 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002855
Chris Lattnera5937dd2007-08-26 01:18:55 +00002856 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00002857 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2858 UsualArithmeticConversions(lex, rex);
2859 else {
2860 UsualUnaryConversions(lex);
2861 UsualUnaryConversions(rex);
2862 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002863 QualType lType = lex->getType();
2864 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002865
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002866 // For non-floating point types, check for self-comparisons of the form
2867 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2868 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002869 if (!lType->isFloatingType()) {
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00002870 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2871 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002872 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002873 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002874 }
2875
Douglas Gregor447b69e2008-11-19 03:25:36 +00002876 // The result of comparisons is 'bool' in C++, 'int' in C.
2877 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2878
Chris Lattnera5937dd2007-08-26 01:18:55 +00002879 if (isRelational) {
2880 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00002881 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00002882 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002883 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002884 if (lType->isFloatingType()) {
2885 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002886 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00002887 }
2888
Chris Lattnera5937dd2007-08-26 01:18:55 +00002889 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00002890 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00002891 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002892
Chris Lattnerd28f8152007-08-26 01:10:14 +00002893 bool LHSIsNull = lex->isNullPointerConstant(Context);
2894 bool RHSIsNull = rex->isNullPointerConstant(Context);
2895
Chris Lattnera5937dd2007-08-26 01:18:55 +00002896 // All of the following pointer related warnings are GCC extensions, except
2897 // when handling null pointer constants. One day, we can consider making them
2898 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00002899 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002900 QualType LCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002901 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00002902 QualType RCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002903 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman8e54ad02008-02-08 01:19:44 +00002904
Steve Naroff66296cb2007-11-13 14:57:38 +00002905 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002906 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2907 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman3d815e72008-08-22 00:56:42 +00002908 RCanPointeeTy.getUnqualifiedType()) &&
2909 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002910 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00002911 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002912 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00002913 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002914 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002915 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002916 // Handle block pointer types.
2917 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2918 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2919 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2920
2921 if (!LHSIsNull && !RHSIsNull &&
2922 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002923 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00002924 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00002925 }
2926 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002927 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002928 }
Steve Naroff59f53942008-09-28 01:11:11 +00002929 // Allow block pointers to be compared with null pointer constants.
2930 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2931 (lType->isPointerType() && rType->isBlockPointerType())) {
2932 if (!LHSIsNull && !RHSIsNull) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002933 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00002934 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00002935 }
2936 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002937 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00002938 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002939
Steve Naroff20373222008-06-03 14:04:54 +00002940 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00002941 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroffa8069f12008-11-17 19:49:16 +00002942 const PointerType *LPT = lType->getAsPointerType();
2943 const PointerType *RPT = rType->getAsPointerType();
2944 bool LPtrToVoid = LPT ?
2945 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2946 bool RPtrToVoid = RPT ?
2947 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2948
2949 if (!LPtrToVoid && !RPtrToVoid &&
2950 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002951 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00002952 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00002953 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002954 return ResultTy;
Steve Naroffa5ad8632008-10-27 10:33:19 +00002955 }
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002956 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002957 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00002958 }
Steve Naroff20373222008-06-03 14:04:54 +00002959 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2960 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002961 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00002962 } else {
2963 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002964 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002965 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002966 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002967 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00002968 }
Steve Naroff20373222008-06-03 14:04:54 +00002969 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00002970 }
Steve Naroff20373222008-06-03 14:04:54 +00002971 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2972 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002973 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002974 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002975 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00002976 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002977 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002978 }
Steve Naroff20373222008-06-03 14:04:54 +00002979 if (lType->isIntegerType() &&
2980 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002981 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002982 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002983 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00002984 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002985 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002986 }
Steve Naroff39218df2008-09-04 16:56:14 +00002987 // Handle block pointers.
2988 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2989 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002990 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002991 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00002992 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002993 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00002994 }
2995 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2996 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002997 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002998 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00002999 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00003000 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00003001 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003002 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003003}
3004
Nate Begemanbe2341d2008-07-14 18:02:46 +00003005/// CheckVectorCompareOperands - vector comparisons are a clang extension that
3006/// operates on extended vector types. Instead of producing an IntTy result,
3007/// like a scalar comparison, a vector comparison produces a vector of integer
3008/// types.
3009QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003010 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00003011 bool isRelational) {
3012 // Check to make sure we're operating on vectors of the same type and width,
3013 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003014 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00003015 if (vType.isNull())
3016 return vType;
3017
3018 QualType lType = lex->getType();
3019 QualType rType = rex->getType();
3020
3021 // For non-floating point types, check for self-comparisons of the form
3022 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3023 // often indicate logic errors in the program.
3024 if (!lType->isFloatingType()) {
3025 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3026 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3027 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003028 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00003029 }
3030
3031 // Check for comparisons of floating point operands using != and ==.
3032 if (!isRelational && lType->isFloatingType()) {
3033 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003034 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00003035 }
3036
3037 // Return the type for the comparison, which is the same as vector type for
3038 // integer vectors, or an integer type of identical size and number of
3039 // elements for floating point vectors.
3040 if (lType->isIntegerType())
3041 return lType;
3042
3043 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanbe2341d2008-07-14 18:02:46 +00003044 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00003045 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00003046 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begeman59b5da62009-01-18 03:20:47 +00003047 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3048 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3049
3050 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3051 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00003052 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3053}
3054
Reid Spencer5f016e22007-07-11 17:01:13 +00003055inline QualType Sema::CheckBitwiseOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003056 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00003057{
Steve Naroff3e5e5562007-07-16 22:23:01 +00003058 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003059 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00003060
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003061 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00003062
Steve Naroffa4332e22007-07-17 00:58:39 +00003063 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003064 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003065 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003066}
3067
3068inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003069 Expr *&lex, Expr *&rex, SourceLocation Loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00003070{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003071 UsualUnaryConversions(lex);
3072 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003073
Eli Friedman5773a6c2008-05-13 20:16:47 +00003074 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00003075 return Context.IntTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003076 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003077}
3078
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00003079/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3080/// is a read-only property; return true if so. A readonly property expression
3081/// depends on various declarations and thus must be treated specially.
3082///
3083static bool IsReadonlyProperty(Expr *E, Sema &S)
3084{
3085 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3086 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3087 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3088 QualType BaseType = PropExpr->getBase()->getType();
3089 if (const PointerType *PTy = BaseType->getAsPointerType())
3090 if (const ObjCInterfaceType *IFTy =
3091 PTy->getPointeeType()->getAsObjCInterfaceType())
3092 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3093 if (S.isPropertyReadonly(PDecl, IFace))
3094 return true;
3095 }
3096 }
3097 return false;
3098}
3099
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003100/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3101/// emit an error and return true. If so, return false.
3102static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00003103 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3104 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3105 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003106 if (IsLV == Expr::MLV_Valid)
3107 return false;
3108
3109 unsigned Diag = 0;
3110 bool NeedType = false;
3111 switch (IsLV) { // C99 6.5.16p2
3112 default: assert(0 && "Unknown result from isModifiableLvalue!");
3113 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003114 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003115 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3116 NeedType = true;
3117 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003118 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003119 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3120 NeedType = true;
3121 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00003122 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003123 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3124 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003125 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003126 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3127 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00003128 case Expr::MLV_IncompleteType:
3129 case Expr::MLV_IncompleteVoidType:
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003130 return S.DiagnoseIncompleteType(Loc, E->getType(),
3131 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3132 E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00003133 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003134 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3135 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00003136 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003137 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3138 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00003139 case Expr::MLV_ReadonlyProperty:
3140 Diag = diag::error_readonly_property_assignment;
3141 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00003142 case Expr::MLV_NoSetterProperty:
3143 Diag = diag::error_nosetter_property_assignment;
3144 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003145 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00003146
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003147 if (NeedType)
Chris Lattnerd1625842008-11-24 06:25:27 +00003148 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003149 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003150 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003151 return true;
3152}
3153
3154
3155
3156// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003157QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3158 SourceLocation Loc,
3159 QualType CompoundType) {
3160 // Verify that LHS is a modifiable lvalue, and emit error if not.
3161 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003162 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003163
3164 QualType LHSType = LHS->getType();
3165 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003166
Chris Lattner5cf216b2008-01-04 18:04:52 +00003167 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003168 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00003169 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003170 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003171 // Special case of NSObject attributes on c-style pointer types.
3172 if (ConvTy == IncompatiblePointer &&
3173 ((Context.isObjCNSObjectType(LHSType) &&
3174 Context.isObjCObjectPointerType(RHSType)) ||
3175 (Context.isObjCNSObjectType(RHSType) &&
3176 Context.isObjCObjectPointerType(LHSType))))
3177 ConvTy = Compatible;
3178
Chris Lattner2c156472008-08-21 18:04:13 +00003179 // If the RHS is a unary plus or minus, check to see if they = and + are
3180 // right next to each other. If so, the user may have typo'd "x =+ 4"
3181 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003182 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00003183 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3184 RHSCheck = ICE->getSubExpr();
3185 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3186 if ((UO->getOpcode() == UnaryOperator::Plus ||
3187 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003188 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00003189 // Only if the two operators are exactly adjacent.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003190 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003191 Diag(Loc, diag::warn_not_compound_assign)
3192 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3193 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner2c156472008-08-21 18:04:13 +00003194 }
3195 } else {
3196 // Compound assignment "x += y"
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003197 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00003198 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00003199
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003200 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3201 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00003202 return QualType();
3203
Reid Spencer5f016e22007-07-11 17:01:13 +00003204 // C99 6.5.16p3: The type of an assignment expression is the type of the
3205 // left operand unless the left operand has qualified type, in which case
3206 // it is the unqualified version of the type of the left operand.
3207 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3208 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003209 // C++ 5.17p1: the type of the assignment expression is that of its left
3210 // oprdu.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003211 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003212}
3213
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003214// C99 6.5.17
3215QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3216 // FIXME: what is required for LHS?
Chris Lattner53fcaa92008-07-25 20:54:07 +00003217
3218 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003219 DefaultFunctionArrayConversion(RHS);
3220 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003221}
3222
Steve Naroff49b45262007-07-13 16:58:59 +00003223/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3224/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003225QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3226 bool isInc) {
Chris Lattner3528d352008-11-21 07:05:48 +00003227 QualType ResType = Op->getType();
3228 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00003229
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003230 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3231 // Decrement of bool is not allowed.
3232 if (!isInc) {
3233 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3234 return QualType();
3235 }
3236 // Increment of bool sets it to true, but is deprecated.
3237 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3238 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00003239 // OK!
3240 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3241 // C99 6.5.2.4p2, 6.5.6p2
3242 if (PT->getPointeeType()->isObjectType()) {
3243 // Pointer to object is ok!
3244 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00003245 if (getLangOptions().CPlusPlus) {
3246 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3247 << Op->getSourceRange();
3248 return QualType();
3249 }
3250
3251 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00003252 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003253 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00003254 if (getLangOptions().CPlusPlus) {
3255 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3256 << Op->getType() << Op->getSourceRange();
3257 return QualType();
3258 }
3259
3260 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00003261 << ResType << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003262 return QualType();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003263 } else {
3264 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3265 diag::err_typecheck_arithmetic_incomplete_type,
3266 Op->getSourceRange(), SourceRange(),
3267 ResType);
3268 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003269 }
Chris Lattner3528d352008-11-21 07:05:48 +00003270 } else if (ResType->isComplexType()) {
3271 // C99 does not support ++/-- on complex types, we allow as an extension.
3272 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00003273 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00003274 } else {
3275 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00003276 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00003277 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003278 }
Steve Naroffdd10e022007-08-23 21:37:33 +00003279 // At this point, we know we have a real, complex or pointer type.
3280 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00003281 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00003282 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00003283 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00003284}
3285
Anders Carlsson369dee42008-02-01 07:15:58 +00003286/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00003287/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003288/// where the declaration is needed for type checking. We only need to
3289/// handle cases when the expression references a function designator
3290/// or is an lvalue. Here are some examples:
3291/// - &(x) => x
3292/// - &*****f => f for f a function designator.
3293/// - &s.xx => s
3294/// - &s.zz[1].yy -> s, if zz is an array
3295/// - *(x + 1) -> x, if x is an array
3296/// - &"123"[2] -> 0
3297/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003298static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00003299 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003300 case Stmt::DeclRefExprClass:
Douglas Gregor1a49af92009-01-06 05:10:23 +00003301 case Stmt::QualifiedDeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00003302 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003303 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00003304 // Fields cannot be declared with a 'register' storage class.
3305 // &X->f is always ok, even if X is declared register.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003306 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00003307 return 0;
Chris Lattnerf0467b32008-04-02 04:24:33 +00003308 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00003309 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003310 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson369dee42008-02-01 07:15:58 +00003311
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003312 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar48d04ae2008-10-21 21:22:32 +00003313 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlssonf2a4b842008-02-01 16:01:31 +00003314 if (!VD || VD->getType()->isPointerType())
Anders Carlsson369dee42008-02-01 07:15:58 +00003315 return 0;
3316 else
3317 return VD;
3318 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003319 case Stmt::UnaryOperatorClass: {
3320 UnaryOperator *UO = cast<UnaryOperator>(E);
3321
3322 switch(UO->getOpcode()) {
3323 case UnaryOperator::Deref: {
3324 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003325 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3326 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3327 if (!VD || VD->getType()->isPointerType())
3328 return 0;
3329 return VD;
3330 }
3331 return 0;
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003332 }
3333 case UnaryOperator::Real:
3334 case UnaryOperator::Imag:
3335 case UnaryOperator::Extension:
3336 return getPrimaryDecl(UO->getSubExpr());
3337 default:
3338 return 0;
3339 }
3340 }
3341 case Stmt::BinaryOperatorClass: {
3342 BinaryOperator *BO = cast<BinaryOperator>(E);
3343
3344 // Handle cases involving pointer arithmetic. The result of an
3345 // Assign or AddAssign is not an lvalue so they can be ignored.
3346
3347 // (x + n) or (n + x) => x
3348 if (BO->getOpcode() == BinaryOperator::Add) {
3349 if (BO->getLHS()->getType()->isPointerType()) {
3350 return getPrimaryDecl(BO->getLHS());
3351 } else if (BO->getRHS()->getType()->isPointerType()) {
3352 return getPrimaryDecl(BO->getRHS());
3353 }
3354 }
3355
3356 return 0;
3357 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003358 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00003359 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00003360 case Stmt::ImplicitCastExprClass:
3361 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003362 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00003363 default:
3364 return 0;
3365 }
3366}
3367
3368/// CheckAddressOfOperand - The operand of & must be either a function
3369/// designator or an lvalue designating an object. If it is an lvalue, the
3370/// object cannot be declared with storage class register or be a bit field.
3371/// Note: The usual conversions are *not* applied to the operand of the &
3372/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor904eed32008-11-10 20:40:00 +00003373/// In C++, the operand might be an overloaded function name, in which case
3374/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00003375QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregor9103bb22008-12-17 22:52:20 +00003376 if (op->isTypeDependent())
3377 return Context.DependentTy;
3378
Steve Naroff08f19672008-01-13 17:10:08 +00003379 if (getLangOptions().C99) {
3380 // Implement C99-only parts of addressof rules.
3381 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3382 if (uOp->getOpcode() == UnaryOperator::Deref)
3383 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3384 // (assuming the deref expression is valid).
3385 return uOp->getSubExpr()->getType();
3386 }
3387 // Technically, there should be a check for array subscript
3388 // expressions here, but the result of one is always an lvalue anyway.
3389 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003390 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00003391 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00003392
Reid Spencer5f016e22007-07-11 17:01:13 +00003393 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00003394 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3395 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003396 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3397 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003398 return QualType();
3399 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00003400 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor86f19402008-12-20 23:49:58 +00003401 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3402 if (Field->isBitField()) {
3403 Diag(OpLoc, diag::err_typecheck_address_of)
3404 << "bit-field" << op->getSourceRange();
3405 return QualType();
3406 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00003407 }
3408 // Check for Apple extension for accessing vector components.
3409 } else if (isa<ArraySubscriptExpr>(op) &&
3410 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003411 Diag(OpLoc, diag::err_typecheck_address_of)
3412 << "vector" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00003413 return QualType();
3414 } else if (dcl) { // C99 6.5.3.2p1
Reid Spencer5f016e22007-07-11 17:01:13 +00003415 // We have an lvalue with a decl. Make sure the decl is not declared
3416 // with the register storage-class specifier.
3417 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3418 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003419 Diag(OpLoc, diag::err_typecheck_address_of)
3420 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003421 return QualType();
3422 }
Douglas Gregor29882052008-12-10 21:26:49 +00003423 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00003424 return Context.OverloadTy;
Douglas Gregor29882052008-12-10 21:26:49 +00003425 } else if (isa<FieldDecl>(dcl)) {
3426 // Okay: we can take the address of a field.
Nuno Lopes6fea8d22008-12-16 22:58:26 +00003427 } else if (isa<FunctionDecl>(dcl)) {
3428 // Okay: we can take the address of a function.
Douglas Gregor29882052008-12-10 21:26:49 +00003429 }
Nuno Lopes6fea8d22008-12-16 22:58:26 +00003430 else
Reid Spencer5f016e22007-07-11 17:01:13 +00003431 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00003432 }
Chris Lattnerc36d4052008-07-27 00:48:22 +00003433
Reid Spencer5f016e22007-07-11 17:01:13 +00003434 // If the operand has type "type", the result has type "pointer to type".
3435 return Context.getPointerType(op->getType());
3436}
3437
Chris Lattner22caddc2008-11-23 09:13:29 +00003438QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3439 UsualUnaryConversions(Op);
3440 QualType Ty = Op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003441
Chris Lattner22caddc2008-11-23 09:13:29 +00003442 // Note that per both C89 and C99, this is always legal, even if ptype is an
3443 // incomplete type or void. It would be possible to warn about dereferencing
3444 // a void pointer, but it's completely well-defined, and such a warning is
3445 // unlikely to catch any mistakes.
3446 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff08f19672008-01-13 17:10:08 +00003447 return PT->getPointeeType();
Chris Lattner22caddc2008-11-23 09:13:29 +00003448
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003449 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00003450 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003451 return QualType();
3452}
3453
3454static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3455 tok::TokenKind Kind) {
3456 BinaryOperator::Opcode Opc;
3457 switch (Kind) {
3458 default: assert(0 && "Unknown binop!");
3459 case tok::star: Opc = BinaryOperator::Mul; break;
3460 case tok::slash: Opc = BinaryOperator::Div; break;
3461 case tok::percent: Opc = BinaryOperator::Rem; break;
3462 case tok::plus: Opc = BinaryOperator::Add; break;
3463 case tok::minus: Opc = BinaryOperator::Sub; break;
3464 case tok::lessless: Opc = BinaryOperator::Shl; break;
3465 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3466 case tok::lessequal: Opc = BinaryOperator::LE; break;
3467 case tok::less: Opc = BinaryOperator::LT; break;
3468 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3469 case tok::greater: Opc = BinaryOperator::GT; break;
3470 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3471 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3472 case tok::amp: Opc = BinaryOperator::And; break;
3473 case tok::caret: Opc = BinaryOperator::Xor; break;
3474 case tok::pipe: Opc = BinaryOperator::Or; break;
3475 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3476 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3477 case tok::equal: Opc = BinaryOperator::Assign; break;
3478 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3479 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3480 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3481 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3482 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3483 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3484 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3485 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3486 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3487 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3488 case tok::comma: Opc = BinaryOperator::Comma; break;
3489 }
3490 return Opc;
3491}
3492
3493static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3494 tok::TokenKind Kind) {
3495 UnaryOperator::Opcode Opc;
3496 switch (Kind) {
3497 default: assert(0 && "Unknown unary op!");
3498 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3499 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3500 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3501 case tok::star: Opc = UnaryOperator::Deref; break;
3502 case tok::plus: Opc = UnaryOperator::Plus; break;
3503 case tok::minus: Opc = UnaryOperator::Minus; break;
3504 case tok::tilde: Opc = UnaryOperator::Not; break;
3505 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003506 case tok::kw___real: Opc = UnaryOperator::Real; break;
3507 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3508 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3509 }
3510 return Opc;
3511}
3512
Douglas Gregoreaebc752008-11-06 23:29:22 +00003513/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3514/// operator @p Opc at location @c TokLoc. This routine only supports
3515/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003516Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3517 unsigned Op,
3518 Expr *lhs, Expr *rhs) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00003519 QualType ResultTy; // Result type of the binary operator.
3520 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3521 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3522
3523 switch (Opc) {
3524 default:
3525 assert(0 && "Unknown binary expr!");
3526 case BinaryOperator::Assign:
3527 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3528 break;
3529 case BinaryOperator::Mul:
3530 case BinaryOperator::Div:
3531 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3532 break;
3533 case BinaryOperator::Rem:
3534 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3535 break;
3536 case BinaryOperator::Add:
3537 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3538 break;
3539 case BinaryOperator::Sub:
3540 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3541 break;
3542 case BinaryOperator::Shl:
3543 case BinaryOperator::Shr:
3544 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3545 break;
3546 case BinaryOperator::LE:
3547 case BinaryOperator::LT:
3548 case BinaryOperator::GE:
3549 case BinaryOperator::GT:
3550 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3551 break;
3552 case BinaryOperator::EQ:
3553 case BinaryOperator::NE:
3554 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3555 break;
3556 case BinaryOperator::And:
3557 case BinaryOperator::Xor:
3558 case BinaryOperator::Or:
3559 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3560 break;
3561 case BinaryOperator::LAnd:
3562 case BinaryOperator::LOr:
3563 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3564 break;
3565 case BinaryOperator::MulAssign:
3566 case BinaryOperator::DivAssign:
3567 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3568 if (!CompTy.isNull())
3569 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3570 break;
3571 case BinaryOperator::RemAssign:
3572 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3573 if (!CompTy.isNull())
3574 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3575 break;
3576 case BinaryOperator::AddAssign:
3577 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3578 if (!CompTy.isNull())
3579 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3580 break;
3581 case BinaryOperator::SubAssign:
3582 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3583 if (!CompTy.isNull())
3584 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3585 break;
3586 case BinaryOperator::ShlAssign:
3587 case BinaryOperator::ShrAssign:
3588 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3589 if (!CompTy.isNull())
3590 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3591 break;
3592 case BinaryOperator::AndAssign:
3593 case BinaryOperator::XorAssign:
3594 case BinaryOperator::OrAssign:
3595 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3596 if (!CompTy.isNull())
3597 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3598 break;
3599 case BinaryOperator::Comma:
3600 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3601 break;
3602 }
3603 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003604 return ExprError();
Steve Naroff6ece14c2009-01-21 00:14:39 +00003605 if (CompTy.isNull())
3606 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3607 else
3608 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Steve Naroff9e0b6002009-01-20 21:06:31 +00003609 CompTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00003610}
3611
Reid Spencer5f016e22007-07-11 17:01:13 +00003612// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003613Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3614 tok::TokenKind Kind,
3615 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003616 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003617 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Reid Spencer5f016e22007-07-11 17:01:13 +00003618
Steve Narofff69936d2007-09-16 03:34:24 +00003619 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3620 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00003621
Douglas Gregor898574e2008-12-05 23:32:09 +00003622 // If either expression is type-dependent, just build the AST.
3623 // FIXME: We'll need to perform some caching of the result of name
3624 // lookup for operator+.
3625 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff6ece14c2009-01-21 00:14:39 +00003626 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3627 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003628 Context.DependentTy,
3629 Context.DependentTy, TokLoc));
Steve Naroff6ece14c2009-01-21 00:14:39 +00003630 else
3631 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, Context.DependentTy,
3632 TokLoc));
Douglas Gregor898574e2008-12-05 23:32:09 +00003633 }
3634
Douglas Gregoreaebc752008-11-06 23:29:22 +00003635 if (getLangOptions().CPlusPlus &&
3636 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3637 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003638 // If this is one of the assignment operators, we only perform
3639 // overload resolution if the left-hand side is a class or
3640 // enumeration type (C++ [expr.ass]p3).
3641 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3642 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3643 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3644 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003645
Douglas Gregoreaebc752008-11-06 23:29:22 +00003646 // Determine which overloaded operator we're dealing with.
3647 static const OverloadedOperatorKind OverOps[] = {
3648 OO_Star, OO_Slash, OO_Percent,
3649 OO_Plus, OO_Minus,
3650 OO_LessLess, OO_GreaterGreater,
3651 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3652 OO_EqualEqual, OO_ExclaimEqual,
3653 OO_Amp,
3654 OO_Caret,
3655 OO_Pipe,
3656 OO_AmpAmp,
3657 OO_PipePipe,
3658 OO_Equal, OO_StarEqual,
3659 OO_SlashEqual, OO_PercentEqual,
3660 OO_PlusEqual, OO_MinusEqual,
3661 OO_LessLessEqual, OO_GreaterGreaterEqual,
3662 OO_AmpEqual, OO_CaretEqual,
3663 OO_PipeEqual,
3664 OO_Comma
3665 };
3666 OverloadedOperatorKind OverOp = OverOps[Opc];
3667
Douglas Gregor96176b32008-11-18 23:14:02 +00003668 // Add the appropriate overloaded operators (C++ [over.match.oper])
3669 // to the candidate set.
Douglas Gregor74253732008-11-19 15:42:04 +00003670 OverloadCandidateSet CandidateSet;
Douglas Gregoreaebc752008-11-06 23:29:22 +00003671 Expr *Args[2] = { lhs, rhs };
Douglas Gregor96176b32008-11-18 23:14:02 +00003672 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregoreaebc752008-11-06 23:29:22 +00003673
3674 // Perform overload resolution.
3675 OverloadCandidateSet::iterator Best;
3676 switch (BestViableFunction(CandidateSet, Best)) {
3677 case OR_Success: {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003678 // We found a built-in operator or an overloaded operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003679 FunctionDecl *FnDecl = Best->Function;
3680
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003681 if (FnDecl) {
3682 // We matched an overloaded operator. Build a call to that
3683 // operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003684
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003685 // Convert the arguments.
Douglas Gregor96176b32008-11-18 23:14:02 +00003686 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3687 if (PerformObjectArgumentInitialization(lhs, Method) ||
3688 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3689 "passing"))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003690 return ExprError();
Douglas Gregor96176b32008-11-18 23:14:02 +00003691 } else {
3692 // Convert the arguments.
3693 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3694 "passing") ||
3695 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3696 "passing"))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003697 return ExprError();
Douglas Gregor96176b32008-11-18 23:14:02 +00003698 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003699
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003700 // Determine the result type
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003701 QualType ResultTy
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003702 = FnDecl->getType()->getAsFunctionType()->getResultType();
3703 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003704
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003705 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00003706 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3707 SourceLocation());
Douglas Gregorb4609802008-11-14 16:09:21 +00003708 UsualUnaryConversions(FnExpr);
3709
Steve Naroff6ece14c2009-01-21 00:14:39 +00003710 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, Args, 2,
3711 ResultTy, TokLoc));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003712 } else {
3713 // We matched a built-in operator. Convert the arguments, then
3714 // break out so that we will build the appropriate built-in
3715 // operator node.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003716 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3717 Best->Conversions[0], "passing") ||
3718 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3719 Best->Conversions[1], "passing"))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003720 return ExprError();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003721
3722 break;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003723 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003724 }
3725
3726 case OR_No_Viable_Function:
3727 // No viable function; fall through to handling this as a
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003728 // built-in operator, which will produce an error message for us.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003729 break;
3730
3731 case OR_Ambiguous:
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003732 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3733 << BinaryOperator::getOpcodeStr(Opc)
3734 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregoreaebc752008-11-06 23:29:22 +00003735 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003736 return ExprError();
Douglas Gregoreaebc752008-11-06 23:29:22 +00003737 }
3738
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003739 // Either we found no viable overloaded operator or we matched a
3740 // built-in operator. In either case, fall through to trying to
3741 // build a built-in operation.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003742 }
3743
Douglas Gregoreaebc752008-11-06 23:29:22 +00003744 // Build a built-in binary operation.
3745 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00003746}
3747
3748// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003749Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3750 tok::TokenKind Op, ExprArg input) {
3751 // FIXME: Input is modified later, but smart pointer not reassigned.
3752 Expr *Input = (Expr*)input.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00003753 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor74253732008-11-19 15:42:04 +00003754
3755 if (getLangOptions().CPlusPlus &&
3756 (Input->getType()->isRecordType()
3757 || Input->getType()->isEnumeralType())) {
3758 // Determine which overloaded operator we're dealing with.
3759 static const OverloadedOperatorKind OverOps[] = {
3760 OO_None, OO_None,
3761 OO_PlusPlus, OO_MinusMinus,
3762 OO_Amp, OO_Star,
3763 OO_Plus, OO_Minus,
3764 OO_Tilde, OO_Exclaim,
3765 OO_None, OO_None,
3766 OO_None,
3767 OO_None
3768 };
3769 OverloadedOperatorKind OverOp = OverOps[Opc];
3770
3771 // Add the appropriate overloaded operators (C++ [over.match.oper])
3772 // to the candidate set.
3773 OverloadCandidateSet CandidateSet;
3774 if (OverOp != OO_None)
3775 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3776
3777 // Perform overload resolution.
3778 OverloadCandidateSet::iterator Best;
3779 switch (BestViableFunction(CandidateSet, Best)) {
3780 case OR_Success: {
3781 // We found a built-in operator or an overloaded operator.
3782 FunctionDecl *FnDecl = Best->Function;
3783
3784 if (FnDecl) {
3785 // We matched an overloaded operator. Build a call to that
3786 // operator.
3787
3788 // Convert the arguments.
3789 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3790 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003791 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00003792 } else {
3793 // Convert the arguments.
3794 if (PerformCopyInitialization(Input,
3795 FnDecl->getParamDecl(0)->getType(),
3796 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003797 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00003798 }
3799
3800 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00003801 QualType ResultTy
Douglas Gregor74253732008-11-19 15:42:04 +00003802 = FnDecl->getType()->getAsFunctionType()->getResultType();
3803 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003804
Douglas Gregor74253732008-11-19 15:42:04 +00003805 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00003806 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3807 SourceLocation());
Douglas Gregor74253732008-11-19 15:42:04 +00003808 UsualUnaryConversions(FnExpr);
3809
Sebastian Redl0eb23302009-01-19 00:08:26 +00003810 input.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00003811 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, &Input, 1,
3812 ResultTy, OpLoc));
Douglas Gregor74253732008-11-19 15:42:04 +00003813 } else {
3814 // We matched a built-in operator. Convert the arguments, then
3815 // break out so that we will build the appropriate built-in
3816 // operator node.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003817 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3818 Best->Conversions[0], "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003819 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00003820
3821 break;
Sebastian Redl0eb23302009-01-19 00:08:26 +00003822 }
Douglas Gregor74253732008-11-19 15:42:04 +00003823 }
3824
3825 case OR_No_Viable_Function:
3826 // No viable function; fall through to handling this as a
3827 // built-in operator, which will produce an error message for us.
3828 break;
3829
3830 case OR_Ambiguous:
3831 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3832 << UnaryOperator::getOpcodeStr(Opc)
3833 << Input->getSourceRange();
3834 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003835 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00003836 }
3837
3838 // Either we found no viable overloaded operator or we matched a
3839 // built-in operator. In either case, fall through to trying to
Sebastian Redl0eb23302009-01-19 00:08:26 +00003840 // build a built-in operation.
Douglas Gregor74253732008-11-19 15:42:04 +00003841 }
3842
Reid Spencer5f016e22007-07-11 17:01:13 +00003843 QualType resultType;
3844 switch (Opc) {
3845 default:
3846 assert(0 && "Unimplemented unary expr!");
3847 case UnaryOperator::PreInc:
3848 case UnaryOperator::PreDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003849 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3850 Opc == UnaryOperator::PreInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00003851 break;
3852 case UnaryOperator::AddrOf:
3853 resultType = CheckAddressOfOperand(Input, OpLoc);
3854 break;
3855 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00003856 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003857 resultType = CheckIndirectionOperand(Input, OpLoc);
3858 break;
3859 case UnaryOperator::Plus:
3860 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003861 UsualUnaryConversions(Input);
3862 resultType = Input->getType();
Douglas Gregor74253732008-11-19 15:42:04 +00003863 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3864 break;
3865 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3866 resultType->isEnumeralType())
3867 break;
3868 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3869 Opc == UnaryOperator::Plus &&
3870 resultType->isPointerType())
3871 break;
3872
Sebastian Redl0eb23302009-01-19 00:08:26 +00003873 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3874 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003875 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003876 UsualUnaryConversions(Input);
3877 resultType = Input->getType();
Chris Lattner02a65142008-07-25 23:52:49 +00003878 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3879 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3880 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003881 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00003882 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00003883 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003884 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3885 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003886 break;
3887 case UnaryOperator::LNot: // logical negation
3888 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003889 DefaultFunctionArrayConversion(Input);
3890 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003891 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00003892 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3893 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003894 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003895 // In C++, it's bool. C++ 5.3.1p8
3896 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003897 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00003898 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00003899 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00003900 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00003901 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003902 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00003903 resultType = Input->getType();
3904 break;
3905 }
3906 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003907 return ExprError();
3908 input.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00003909 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003910}
3911
Steve Naroff1b273c42007-09-16 14:56:35 +00003912/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3913Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00003914 SourceLocation LabLoc,
3915 IdentifierInfo *LabelII) {
3916 // Look up the record for this label identifier.
3917 LabelStmt *&LabelDecl = LabelMap[LabelII];
3918
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00003919 // If we haven't seen this label yet, create a forward reference. It
3920 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Reid Spencer5f016e22007-07-11 17:01:13 +00003921 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00003922 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00003923
3924 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff6ece14c2009-01-21 00:14:39 +00003925 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3926 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00003927}
3928
Steve Naroff1b273c42007-09-16 14:56:35 +00003929Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003930 SourceLocation RPLoc) { // "({..})"
3931 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3932 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3933 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3934
Eli Friedmandca2b732009-01-24 23:09:00 +00003935 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
3936 if (isFileScope) {
3937 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
3938 }
3939
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003940 // FIXME: there are a variety of strange constraints to enforce here, for
3941 // example, it is not possible to goto into a stmt expression apparently.
3942 // More semantic analysis is needed.
3943
3944 // FIXME: the last statement in the compount stmt has its value used. We
3945 // should not warn about it being unused.
3946
3947 // If there are sub stmts in the compound stmt, take the type of the last one
3948 // as the type of the stmtexpr.
3949 QualType Ty = Context.VoidTy;
3950
Chris Lattner611b2ec2008-07-26 19:51:01 +00003951 if (!Compound->body_empty()) {
3952 Stmt *LastStmt = Compound->body_back();
3953 // If LastStmt is a label, skip down through into the body.
3954 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3955 LastStmt = Label->getSubStmt();
3956
3957 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003958 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00003959 }
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003960
Steve Naroff6ece14c2009-01-21 00:14:39 +00003961 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003962}
Steve Naroffd34e9152007-08-01 22:05:33 +00003963
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003964Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
3965 SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003966 SourceLocation TypeLoc,
3967 TypeTy *argty,
3968 OffsetOfComponent *CompPtr,
3969 unsigned NumComponents,
3970 SourceLocation RPLoc) {
3971 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3972 assert(!ArgTy.isNull() && "Missing type argument!");
3973
3974 // We must have at least one component that refers to the type, and the first
3975 // one is known to be a field designator. Verify that the ArgTy represents
3976 // a struct/union/class.
3977 if (!ArgTy->isRecordType())
Chris Lattnerd1625842008-11-24 06:25:27 +00003978 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003979
3980 // Otherwise, create a compound literal expression as the base, and
3981 // iteratively process the offsetof designators.
Eli Friedman1d242592009-01-26 01:33:06 +00003982 InitListExpr *IList =
Douglas Gregor4c678342009-01-28 21:54:33 +00003983 new (Context) InitListExpr(SourceLocation(), 0, 0, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00003984 IList->setType(ArgTy);
3985 Expr *Res =
3986 new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, IList, false);
3987
Chris Lattner9e2b75c2007-08-31 21:49:13 +00003988 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3989 // GCC extension, diagnose them.
3990 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003991 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3992 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattner9e2b75c2007-08-31 21:49:13 +00003993
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003994 for (unsigned i = 0; i != NumComponents; ++i) {
3995 const OffsetOfComponent &OC = CompPtr[i];
3996 if (OC.isBrackets) {
3997 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003998 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003999 if (!AT) {
4000 delete Res;
Chris Lattnerd1625842008-11-24 06:25:27 +00004001 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004002 }
4003
Chris Lattner704fe352007-08-30 17:59:59 +00004004 // FIXME: C++: Verify that operator[] isn't overloaded.
4005
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004006 // C99 6.5.2.1p1
4007 Expr *Idx = static_cast<Expr*>(OC.U.E);
4008 if (!Idx->getType()->isIntegerType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004009 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4010 << Idx->getSourceRange();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004011
Steve Naroff6ece14c2009-01-21 00:14:39 +00004012 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4013 OC.LocEnd);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004014 continue;
4015 }
4016
4017 const RecordType *RC = Res->getType()->getAsRecordType();
4018 if (!RC) {
4019 delete Res;
Chris Lattnerd1625842008-11-24 06:25:27 +00004020 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004021 }
4022
4023 // Get the decl corresponding to this.
4024 RecordDecl *RD = RC->getDecl();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004025 FieldDecl *MemberDecl
Douglas Gregor4c921ae2009-01-30 01:04:22 +00004026 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4027 LookupMemberName)
4028 .getAsDecl());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004029 if (!MemberDecl)
Chris Lattner3c73c412008-11-19 08:23:25 +00004030 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4031 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner704fe352007-08-30 17:59:59 +00004032
4033 // FIXME: C++: Verify that MemberDecl isn't a static field.
4034 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman51019072008-02-06 22:48:16 +00004035 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4036 // matter here.
Steve Naroff6ece14c2009-01-21 00:14:39 +00004037 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4038 MemberDecl->getType().getNonReferenceType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004039 }
4040
Steve Naroff6ece14c2009-01-21 00:14:39 +00004041 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4042 Context.getSizeType(), BuiltinLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004043}
4044
4045
Steve Naroff1b273c42007-09-16 14:56:35 +00004046Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00004047 TypeTy *arg1, TypeTy *arg2,
4048 SourceLocation RPLoc) {
4049 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4050 QualType argT2 = QualType::getFromOpaquePtr(arg2);
4051
4052 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4053
Steve Naroff6ece14c2009-01-21 00:14:39 +00004054 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
4055 argT2, RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00004056}
4057
Steve Naroff1b273c42007-09-16 14:56:35 +00004058Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00004059 ExprTy *expr1, ExprTy *expr2,
4060 SourceLocation RPLoc) {
4061 Expr *CondExpr = static_cast<Expr*>(cond);
4062 Expr *LHSExpr = static_cast<Expr*>(expr1);
4063 Expr *RHSExpr = static_cast<Expr*>(expr2);
4064
4065 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4066
4067 // The conditional expression is required to be a constant expression.
4068 llvm::APSInt condEval(32);
4069 SourceLocation ExpLoc;
4070 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004071 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4072 << CondExpr->getSourceRange();
Steve Naroffd04fdd52007-08-03 21:21:27 +00004073
4074 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4075 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
4076 RHSExpr->getType();
Steve Naroff6ece14c2009-01-21 00:14:39 +00004077 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4078 resType, RPLoc);
Steve Naroffd04fdd52007-08-03 21:21:27 +00004079}
4080
Steve Naroff4eb206b2008-09-03 18:15:37 +00004081//===----------------------------------------------------------------------===//
4082// Clang Extensions.
4083//===----------------------------------------------------------------------===//
4084
4085/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00004086void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00004087 // Analyze block parameters.
4088 BlockSemaInfo *BSI = new BlockSemaInfo();
4089
4090 // Add BSI to CurBlock.
4091 BSI->PrevBlockInfo = CurBlock;
4092 CurBlock = BSI;
4093
4094 BSI->ReturnType = 0;
4095 BSI->TheScope = BlockScope;
4096
Steve Naroff090276f2008-10-10 01:28:17 +00004097 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00004098 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00004099}
4100
4101void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00004102 // Analyze arguments to block.
4103 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4104 "Not a function declarator!");
4105 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
4106
Steve Naroff090276f2008-10-10 01:28:17 +00004107 CurBlock->hasPrototype = FTI.hasPrototype;
4108 CurBlock->isVariadic = true;
Steve Naroff4eb206b2008-09-03 18:15:37 +00004109
4110 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4111 // no arguments, not a function that takes a single void argument.
4112 if (FTI.hasPrototype &&
4113 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4114 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4115 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4116 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00004117 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00004118 } else if (FTI.hasPrototype) {
4119 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff090276f2008-10-10 01:28:17 +00004120 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4121 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00004122 }
Steve Naroff090276f2008-10-10 01:28:17 +00004123 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4124
4125 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4126 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4127 // If this has an identifier, add it to the scope stack.
4128 if ((*AI)->getIdentifier())
4129 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004130}
4131
4132/// ActOnBlockError - If there is an error parsing a block, this callback
4133/// is invoked to pop the information about the block from the action impl.
4134void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4135 // Ensure that CurBlock is deleted.
4136 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4137
4138 // Pop off CurBlock, handle nested blocks.
4139 CurBlock = CurBlock->PrevBlockInfo;
4140
4141 // FIXME: Delete the ParmVarDecl objects as well???
4142
4143}
4144
4145/// ActOnBlockStmtExpr - This is called when the body of a block statement
4146/// literal was successfully completed. ^(int x){...}
4147Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4148 Scope *CurScope) {
4149 // Ensure that CurBlock is deleted.
4150 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
4151 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
4152
Steve Naroff090276f2008-10-10 01:28:17 +00004153 PopDeclContext();
4154
Steve Naroff4eb206b2008-09-03 18:15:37 +00004155 // Pop off CurBlock, handle nested blocks.
4156 CurBlock = CurBlock->PrevBlockInfo;
4157
4158 QualType RetTy = Context.VoidTy;
4159 if (BSI->ReturnType)
4160 RetTy = QualType(BSI->ReturnType, 0);
4161
4162 llvm::SmallVector<QualType, 8> ArgTypes;
4163 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4164 ArgTypes.push_back(BSI->Params[i]->getType());
4165
4166 QualType BlockTy;
4167 if (!BSI->hasPrototype)
4168 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4169 else
4170 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004171 BSI->isVariadic, 0);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004172
4173 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff56ee6892008-10-08 17:01:13 +00004174
Steve Naroff1c90bfc2008-10-08 18:44:00 +00004175 BSI->TheDecl->setBody(Body.take());
Steve Naroff6ece14c2009-01-21 00:14:39 +00004176 return new (Context) BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff4eb206b2008-09-03 18:15:37 +00004177}
4178
Nate Begeman67295d02008-01-30 20:50:20 +00004179/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begemane2ce1d92008-01-17 17:46:27 +00004180/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begeman67295d02008-01-30 20:50:20 +00004181/// The number of arguments has already been validated to match the number of
4182/// arguments in FnType.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004183static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4184 ASTContext &Context) {
Nate Begemane2ce1d92008-01-17 17:46:27 +00004185 unsigned NumParams = FnType->getNumArgs();
Nate Begemand6595fa2008-04-18 23:35:14 +00004186 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00004187 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4188 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begemand6595fa2008-04-18 23:35:14 +00004189
4190 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begemane2ce1d92008-01-17 17:46:27 +00004191 return false;
Nate Begemand6595fa2008-04-18 23:35:14 +00004192 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00004193 return true;
4194}
4195
4196Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4197 SourceLocation *CommaLocs,
4198 SourceLocation BuiltinLoc,
4199 SourceLocation RParenLoc) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00004200 // __builtin_overload requires at least 2 arguments
4201 if (NumArgs < 2)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004202 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4203 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004204
Nate Begemane2ce1d92008-01-17 17:46:27 +00004205 // The first argument is required to be a constant expression. It tells us
4206 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begeman796ef3d2008-01-31 05:38:29 +00004207 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004208 Expr *NParamsExpr = Args[0];
4209 llvm::APSInt constEval(32);
4210 SourceLocation ExpLoc;
4211 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004212 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4213 << NParamsExpr->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004214
4215 // Verify that the number of parameters is > 0
4216 unsigned NumParams = constEval.getZExtValue();
4217 if (NumParams == 0)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004218 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4219 << NParamsExpr->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004220 // Verify that we have at least 1 + NumParams arguments to the builtin.
4221 if ((NumParams + 1) > NumArgs)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004222 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4223 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004224
4225 // Figure out the return type, by matching the args to one of the functions
Nate Begeman67295d02008-01-30 20:50:20 +00004226 // listed after the parameters.
Nate Begeman796ef3d2008-01-31 05:38:29 +00004227 OverloadExpr *OE = 0;
Nate Begemane2ce1d92008-01-17 17:46:27 +00004228 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4229 // UsualUnaryConversions will convert the function DeclRefExpr into a
4230 // pointer to function.
4231 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerb77792e2008-07-26 22:17:49 +00004232 const FunctionTypeProto *FnType = 0;
4233 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4234 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004235
4236 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4237 // parameters, and the number of parameters must match the value passed to
4238 // the builtin.
4239 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004240 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4241 << Fn->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004242
4243 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begeman67295d02008-01-30 20:50:20 +00004244 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begemane2ce1d92008-01-17 17:46:27 +00004245 // If they match, return a new OverloadExpr.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004246 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00004247 if (OE)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004248 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4249 << OE->getFn()->getSourceRange();
Nate Begeman796ef3d2008-01-31 05:38:29 +00004250 // Remember our match, and continue processing the remaining arguments
4251 // to catch any errors.
Steve Naroff6ece14c2009-01-21 00:14:39 +00004252 OE = new (Context) OverloadExpr(Args, NumArgs, i,
Douglas Gregor9d293df2008-10-28 00:22:11 +00004253 FnType->getResultType().getNonReferenceType(),
Nate Begeman796ef3d2008-01-31 05:38:29 +00004254 BuiltinLoc, RParenLoc);
4255 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00004256 }
Nate Begeman796ef3d2008-01-31 05:38:29 +00004257 // Return the newly created OverloadExpr node, if we succeded in matching
4258 // exactly one of the candidate functions.
4259 if (OE)
4260 return OE;
Nate Begemane2ce1d92008-01-17 17:46:27 +00004261
4262 // If we didn't find a matching function Expr in the __builtin_overload list
4263 // the return an error.
4264 std::string typeNames;
Nate Begeman67295d02008-01-30 20:50:20 +00004265 for (unsigned i = 0; i != NumParams; ++i) {
4266 if (i != 0) typeNames += ", ";
4267 typeNames += Args[i+1]->getType().getAsString();
4268 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00004269
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004270 return Diag(BuiltinLoc, diag::err_overload_no_match)
4271 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004272}
4273
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004274Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4275 ExprTy *expr, TypeTy *type,
Chris Lattner5cf216b2008-01-04 18:04:52 +00004276 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004277 Expr *E = static_cast<Expr*>(expr);
4278 QualType T = QualType::getFromOpaquePtr(type);
4279
4280 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00004281
4282 // Get the va_list type
4283 QualType VaListType = Context.getBuiltinVaListType();
4284 // Deal with implicit array decay; for example, on x86-64,
4285 // va_list is an array, but it's supposed to decay to
4286 // a pointer for va_arg.
4287 if (VaListType->isArrayType())
4288 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmanefbe85c2008-08-20 22:17:17 +00004289 // Make sure the input expression also decays appropriately.
4290 UsualUnaryConversions(E);
Eli Friedmanc34bcde2008-08-09 23:32:40 +00004291
4292 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004293 return Diag(E->getLocStart(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004294 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerd1625842008-11-24 06:25:27 +00004295 << E->getType() << E->getSourceRange();
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004296
4297 // FIXME: Warn if a non-POD type is passed in.
4298
Steve Naroff6ece14c2009-01-21 00:14:39 +00004299 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004300}
4301
Douglas Gregor2d8b2732008-11-29 04:51:27 +00004302Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4303 // The type of __null will be int or long, depending on the size of
4304 // pointers on the target.
4305 QualType Ty;
4306 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4307 Ty = Context.IntTy;
4308 else
4309 Ty = Context.LongTy;
4310
Steve Naroff6ece14c2009-01-21 00:14:39 +00004311 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregor2d8b2732008-11-29 04:51:27 +00004312}
4313
Chris Lattner5cf216b2008-01-04 18:04:52 +00004314bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4315 SourceLocation Loc,
4316 QualType DstType, QualType SrcType,
4317 Expr *SrcExpr, const char *Flavor) {
4318 // Decode the result (notice that AST's are still created for extensions).
4319 bool isInvalid = false;
4320 unsigned DiagKind;
4321 switch (ConvTy) {
4322 default: assert(0 && "Unknown conversion type");
4323 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00004324 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00004325 DiagKind = diag::ext_typecheck_convert_pointer_int;
4326 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00004327 case IntToPointer:
4328 DiagKind = diag::ext_typecheck_convert_int_pointer;
4329 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004330 case IncompatiblePointer:
4331 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4332 break;
4333 case FunctionVoidPointer:
4334 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4335 break;
4336 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00004337 // If the qualifiers lost were because we were applying the
4338 // (deprecated) C++ conversion from a string literal to a char*
4339 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4340 // Ideally, this check would be performed in
4341 // CheckPointerTypesForAssignment. However, that would require a
4342 // bit of refactoring (so that the second argument is an
4343 // expression, rather than a type), which should be done as part
4344 // of a larger effort to fix CheckPointerTypesForAssignment for
4345 // C++ semantics.
4346 if (getLangOptions().CPlusPlus &&
4347 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4348 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004349 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4350 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004351 case IntToBlockPointer:
4352 DiagKind = diag::err_int_to_block_pointer;
4353 break;
4354 case IncompatibleBlockPointer:
Steve Naroffba80c9a2008-09-24 23:31:10 +00004355 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004356 break;
Steve Naroff39579072008-10-14 22:18:38 +00004357 case IncompatibleObjCQualifiedId:
4358 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4359 // it can give a more specific diagnostic.
4360 DiagKind = diag::warn_incompatible_qualified_id;
4361 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004362 case Incompatible:
4363 DiagKind = diag::err_typecheck_convert_incompatible;
4364 isInvalid = true;
4365 break;
4366 }
4367
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004368 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4369 << SrcExpr->getSourceRange();
Chris Lattner5cf216b2008-01-04 18:04:52 +00004370 return isInvalid;
4371}
Anders Carlssone21555e2008-11-30 19:50:32 +00004372
4373bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4374{
4375 Expr::EvalResult EvalResult;
4376
4377 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4378 EvalResult.HasSideEffects) {
4379 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4380
4381 if (EvalResult.Diag) {
4382 // We only show the note if it's not the usual "invalid subexpression"
4383 // or if it's actually in a subexpression.
4384 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4385 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4386 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4387 }
4388
4389 return true;
4390 }
4391
4392 if (EvalResult.Diag) {
4393 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4394 E->getSourceRange();
4395
4396 // Print the reason it's not a constant.
4397 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4398 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4399 }
4400
4401 if (Result)
4402 *Result = EvalResult.Val.getInt();
4403 return false;
4404}