blob: 8ce8bfdd8baf7e93b2a1d162487c3ea9702cf5da [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
Sebastian Redl95216a62009-02-07 00:15:38 +000014#include "SemaInherit.h"
Chris Lattner4b009652007-07-25 00:24:17 +000015#include "Sema.h"
16#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000017#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000018#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000019#include "clang/AST/ExprObjC.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000020#include "clang/AST/DeclTemplate.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021#include "clang/Lex/Preprocessor.h"
22#include "clang/Lex/LiteralSupport.h"
23#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000024#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000025#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000026#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000027#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000028using namespace clang;
29
Chris Lattner299b8842008-07-25 21:10:04 +000030//===----------------------------------------------------------------------===//
31// Standard Promotions and Conversions
32//===----------------------------------------------------------------------===//
33
Chris Lattner299b8842008-07-25 21:10:04 +000034/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
35void Sema::DefaultFunctionArrayConversion(Expr *&E) {
36 QualType Ty = E->getType();
37 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
38
Chris Lattner299b8842008-07-25 21:10:04 +000039 if (Ty->isFunctionType())
40 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +000041 else if (Ty->isArrayType()) {
42 // In C90 mode, arrays only promote to pointers if the array expression is
43 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
44 // type 'array of type' is converted to an expression that has type 'pointer
45 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
46 // that has type 'array of type' ...". The relevant change is "an lvalue"
47 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +000048 //
49 // C++ 4.2p1:
50 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
51 // T" can be converted to an rvalue of type "pointer to T".
52 //
53 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
54 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +000055 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
56 }
Chris Lattner299b8842008-07-25 21:10:04 +000057}
58
59/// UsualUnaryConversions - Performs various conversions that are common to most
60/// operators (C99 6.3). The conversions of array and function types are
61/// sometimes surpressed. For example, the array->pointer conversion doesn't
62/// apply if the array is an argument to the sizeof or address (&) operators.
63/// In these instances, this routine should *not* be called.
64Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
65 QualType Ty = Expr->getType();
66 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
67
Chris Lattner299b8842008-07-25 21:10:04 +000068 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
69 ImpCastExprToType(Expr, Context.IntTy);
70 else
71 DefaultFunctionArrayConversion(Expr);
72
73 return Expr;
74}
75
Chris Lattner9305c3d2008-07-25 22:25:12 +000076/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
77/// do not have a prototype. Arguments that have type float are promoted to
78/// double. All other argument types are converted by UsualUnaryConversions().
79void Sema::DefaultArgumentPromotion(Expr *&Expr) {
80 QualType Ty = Expr->getType();
81 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
82
83 // If this is a 'float' (CVR qualified or typedef) promote to double.
84 if (const BuiltinType *BT = Ty->getAsBuiltinType())
85 if (BT->getKind() == BuiltinType::Float)
86 return ImpCastExprToType(Expr, Context.DoubleTy);
87
88 UsualUnaryConversions(Expr);
89}
90
Anders Carlsson4b8e38c2009-01-16 16:48:51 +000091// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
92// will warn if the resulting type is not a POD type.
93void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT)
94
95{
96 DefaultArgumentPromotion(Expr);
97
98 if (!Expr->getType()->isPODType()) {
99 Diag(Expr->getLocStart(),
100 diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
101 Expr->getType() << CT;
102 }
103}
104
105
Chris Lattner299b8842008-07-25 21:10:04 +0000106/// UsualArithmeticConversions - Performs various conversions that are common to
107/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
108/// routine returns the first non-arithmetic type found. The client is
109/// responsible for emitting appropriate error diagnostics.
110/// FIXME: verify the conversion rules for "complex int" are consistent with
111/// GCC.
112QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
113 bool isCompAssign) {
114 if (!isCompAssign) {
115 UsualUnaryConversions(lhsExpr);
116 UsualUnaryConversions(rhsExpr);
117 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000118
Chris Lattner299b8842008-07-25 21:10:04 +0000119 // For conversion purposes, we ignore any qualifiers.
120 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000121 QualType lhs =
122 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
123 QualType rhs =
124 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000125
126 // If both types are identical, no conversion is needed.
127 if (lhs == rhs)
128 return lhs;
129
130 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
131 // The caller can deal with this (e.g. pointer + int).
132 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
133 return lhs;
134
135 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
136 if (!isCompAssign) {
137 ImpCastExprToType(lhsExpr, destType);
138 ImpCastExprToType(rhsExpr, destType);
139 }
140 return destType;
141}
142
143QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
144 // Perform the usual unary conversions. We do this early so that
145 // integral promotions to "int" can allow us to exit early, in the
146 // lhs == rhs check. Also, for conversion purposes, we ignore any
147 // qualifiers. For example, "const float" and "float" are
148 // equivalent.
Douglas Gregor3d4492e2008-11-13 20:12:29 +0000149 if (lhs->isPromotableIntegerType()) lhs = Context.IntTy;
150 else lhs = lhs.getUnqualifiedType();
151 if (rhs->isPromotableIntegerType()) rhs = Context.IntTy;
152 else rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000153
Chris Lattner299b8842008-07-25 21:10:04 +0000154 // If both types are identical, no conversion is needed.
155 if (lhs == rhs)
156 return lhs;
157
158 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
159 // The caller can deal with this (e.g. pointer + int).
160 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
161 return lhs;
162
163 // At this point, we have two different arithmetic types.
164
165 // Handle complex types first (C99 6.3.1.8p1).
166 if (lhs->isComplexType() || rhs->isComplexType()) {
167 // if we have an integer operand, the result is the complex type.
168 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
169 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000170 return lhs;
171 }
172 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
173 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000174 return rhs;
175 }
176 // This handles complex/complex, complex/float, or float/complex.
177 // When both operands are complex, the shorter operand is converted to the
178 // type of the longer, and that is the type of the result. This corresponds
179 // to what is done when combining two real floating-point operands.
180 // The fun begins when size promotion occur across type domains.
181 // From H&S 6.3.4: When one operand is complex and the other is a real
182 // floating-point type, the less precise type is converted, within it's
183 // real or complex domain, to the precision of the other type. For example,
184 // when combining a "long double" with a "double _Complex", the
185 // "double _Complex" is promoted to "long double _Complex".
186 int result = Context.getFloatingTypeOrder(lhs, rhs);
187
188 if (result > 0) { // The left side is bigger, convert rhs.
189 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000190 } else if (result < 0) { // The right side is bigger, convert lhs.
191 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000192 }
193 // At this point, lhs and rhs have the same rank/size. Now, make sure the
194 // domains match. This is a requirement for our implementation, C99
195 // does not require this promotion.
196 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
197 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000198 return rhs;
199 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000200 return lhs;
201 }
202 }
203 return lhs; // The domain/size match exactly.
204 }
205 // Now handle "real" floating types (i.e. float, double, long double).
206 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
207 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000208 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000209 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000210 return lhs;
211 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000212 if (rhs->isComplexIntegerType()) {
213 // convert rhs to the complex floating point type.
214 return Context.getComplexType(lhs);
215 }
216 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000217 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000218 return rhs;
219 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000220 if (lhs->isComplexIntegerType()) {
221 // convert lhs to the complex floating point type.
222 return Context.getComplexType(rhs);
223 }
Chris Lattner299b8842008-07-25 21:10:04 +0000224 // We have two real floating types, float/complex combos were handled above.
225 // Convert the smaller operand to the bigger result.
226 int result = Context.getFloatingTypeOrder(lhs, rhs);
227
228 if (result > 0) { // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000229 return lhs;
230 }
231 if (result < 0) { // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000232 return rhs;
233 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000234 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
Chris Lattner299b8842008-07-25 21:10:04 +0000235 }
236 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
237 // Handle GCC complex int extension.
238 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
239 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
240
241 if (lhsComplexInt && rhsComplexInt) {
242 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
243 rhsComplexInt->getElementType()) >= 0) {
244 // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000245 return lhs;
246 }
Chris Lattner299b8842008-07-25 21:10:04 +0000247 return rhs;
248 } else if (lhsComplexInt && rhs->isIntegerType()) {
249 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000250 return lhs;
251 } else if (rhsComplexInt && lhs->isIntegerType()) {
252 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000253 return rhs;
254 }
255 }
256 // Finally, we have two differing integer types.
257 // The rules for this case are in C99 6.3.1.8
258 int compare = Context.getIntegerTypeOrder(lhs, rhs);
259 bool lhsSigned = lhs->isSignedIntegerType(),
260 rhsSigned = rhs->isSignedIntegerType();
261 QualType destType;
262 if (lhsSigned == rhsSigned) {
263 // Same signedness; use the higher-ranked type
264 destType = compare >= 0 ? lhs : rhs;
265 } else if (compare != (lhsSigned ? 1 : -1)) {
266 // The unsigned type has greater than or equal rank to the
267 // signed type, so use the unsigned type
268 destType = lhsSigned ? rhs : lhs;
269 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
270 // The two types are different widths; if we are here, that
271 // means the signed type is larger than the unsigned type, so
272 // use the signed type.
273 destType = lhsSigned ? lhs : rhs;
274 } else {
275 // The signed type is higher-ranked than the unsigned type,
276 // but isn't actually any bigger (like unsigned int and long
277 // on most 32-bit systems). Use the unsigned type corresponding
278 // to the signed type.
279 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
280 }
Chris Lattner299b8842008-07-25 21:10:04 +0000281 return destType;
282}
283
284//===----------------------------------------------------------------------===//
285// Semantic Analysis for various Expression Types
286//===----------------------------------------------------------------------===//
287
288
Steve Naroff87d58b42007-09-16 03:34:24 +0000289/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000290/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
291/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
292/// multiple tokens. However, the common case is that StringToks points to one
293/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000294///
295Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000296Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000297 assert(NumStringToks && "Must have at least one string!");
298
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000299 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000300 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000301 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000302
303 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
304 for (unsigned i = 0; i != NumStringToks; ++i)
305 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000306
Chris Lattnera6dcce32008-02-11 00:02:17 +0000307 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000308 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000309 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000310
311 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
312 if (getLangOptions().CPlusPlus)
313 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000314
Chris Lattnera6dcce32008-02-11 00:02:17 +0000315 // Get an array type for the string, according to C99 6.4.5. This includes
316 // the nul terminator character as well as the string length for pascal
317 // strings.
318 StrTy = Context.getConstantArrayType(StrTy,
319 llvm::APInt(32, Literal.GetStringLength()+1),
320 ArrayType::Normal, 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000321
Chris Lattner4b009652007-07-25 00:24:17 +0000322 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Ted Kremenek4f530a92009-02-06 19:55:15 +0000323 return Owned(new (Context) StringLiteral(Context, Literal.GetString(),
Steve Naroff774e4152009-01-21 00:14:39 +0000324 Literal.GetStringLength(),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000325 Literal.AnyWide, StrTy,
326 StringToks[0].getLocation(),
327 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000328}
329
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000330/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
331/// CurBlock to VD should cause it to be snapshotted (as we do for auto
332/// variables defined outside the block) or false if this is not needed (e.g.
333/// for values inside the block or for globals).
334///
335/// FIXME: This will create BlockDeclRefExprs for global variables,
336/// function references, etc which is suboptimal :) and breaks
337/// things like "integer constant expression" tests.
338static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
339 ValueDecl *VD) {
340 // If the value is defined inside the block, we couldn't snapshot it even if
341 // we wanted to.
342 if (CurBlock->TheDecl == VD->getDeclContext())
343 return false;
344
345 // If this is an enum constant or function, it is constant, don't snapshot.
346 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
347 return false;
348
349 // If this is a reference to an extern, static, or global variable, no need to
350 // snapshot it.
351 // FIXME: What about 'const' variables in C++?
352 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
353 return Var->hasLocalStorage();
354
355 return true;
356}
357
358
359
Steve Naroff0acc9c92007-09-15 18:49:24 +0000360/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000361/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000362/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000363/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000364/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000365Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
366 IdentifierInfo &II,
367 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000368 const CXXScopeSpec *SS,
369 bool isAddressOfOperand) {
370 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000371 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000372}
373
Douglas Gregor566782a2009-01-06 05:10:23 +0000374/// BuildDeclRefExpr - Build either a DeclRefExpr or a
375/// QualifiedDeclRefExpr based on whether or not SS is a
376/// nested-name-specifier.
Sebastian Redl0c9da212009-02-03 20:19:35 +0000377DeclRefExpr *
378Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
379 bool TypeDependent, bool ValueDependent,
380 const CXXScopeSpec *SS) {
Steve Naroff774e4152009-01-21 00:14:39 +0000381 if (SS && !SS->isEmpty())
382 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000383 ValueDependent, SS->getRange().getBegin());
Steve Naroff774e4152009-01-21 00:14:39 +0000384 else
385 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000386}
387
Douglas Gregor723d3332009-01-07 00:43:41 +0000388/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
389/// variable corresponding to the anonymous union or struct whose type
390/// is Record.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000391static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000392 assert(Record->isAnonymousStructOrUnion() &&
393 "Record must be an anonymous struct or union!");
394
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000395 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000396 // be an O(1) operation rather than a slow walk through DeclContext's
397 // vector (which itself will be eliminated). DeclGroups might make
398 // this even better.
399 DeclContext *Ctx = Record->getDeclContext();
400 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
401 DEnd = Ctx->decls_end();
402 D != DEnd; ++D) {
403 if (*D == Record) {
404 // The object for the anonymous struct/union directly
405 // follows its type in the list of declarations.
406 ++D;
407 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000408 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000409 return *D;
410 }
411 }
412
413 assert(false && "Missing object for anonymous record");
414 return 0;
415}
416
Sebastian Redlcd883f72009-01-18 18:53:16 +0000417Sema::OwningExprResult
Douglas Gregor723d3332009-01-07 00:43:41 +0000418Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
419 FieldDecl *Field,
420 Expr *BaseObjectExpr,
421 SourceLocation OpLoc) {
422 assert(Field->getDeclContext()->isRecord() &&
423 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
424 && "Field must be stored inside an anonymous struct or union");
425
426 // Construct the sequence of field member references
427 // we'll have to perform to get to the field in the anonymous
428 // union/struct. The list of members is built from the field
429 // outward, so traverse it backwards to go from an object in
430 // the current context to the field we found.
431 llvm::SmallVector<FieldDecl *, 4> AnonFields;
432 AnonFields.push_back(Field);
433 VarDecl *BaseObject = 0;
434 DeclContext *Ctx = Field->getDeclContext();
435 do {
436 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000437 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000438 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
439 AnonFields.push_back(AnonField);
440 else {
441 BaseObject = cast<VarDecl>(AnonObject);
442 break;
443 }
444 Ctx = Ctx->getParent();
445 } while (Ctx->isRecord() &&
446 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
447
448 // Build the expression that refers to the base object, from
449 // which we will build a sequence of member references to each
450 // of the anonymous union objects and, eventually, the field we
451 // found via name lookup.
452 bool BaseObjectIsPointer = false;
453 unsigned ExtraQuals = 0;
454 if (BaseObject) {
455 // BaseObject is an anonymous struct/union variable (and is,
456 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000457 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff774e4152009-01-21 00:14:39 +0000458 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000459 SourceLocation());
460 ExtraQuals
461 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
462 } else if (BaseObjectExpr) {
463 // The caller provided the base object expression. Determine
464 // whether its a pointer and whether it adds any qualifiers to the
465 // anonymous struct/union fields we're looking into.
466 QualType ObjectType = BaseObjectExpr->getType();
467 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
468 BaseObjectIsPointer = true;
469 ObjectType = ObjectPtr->getPointeeType();
470 }
471 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
472 } else {
473 // We've found a member of an anonymous struct/union that is
474 // inside a non-anonymous struct/union, so in a well-formed
475 // program our base object expression is "this".
476 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
477 if (!MD->isStatic()) {
478 QualType AnonFieldType
479 = Context.getTagDeclType(
480 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
481 QualType ThisType = Context.getTagDeclType(MD->getParent());
482 if ((Context.getCanonicalType(AnonFieldType)
483 == Context.getCanonicalType(ThisType)) ||
484 IsDerivedFrom(ThisType, AnonFieldType)) {
485 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000486 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000487 MD->getThisType(Context));
488 BaseObjectIsPointer = true;
489 }
490 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000491 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
492 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000493 }
494 ExtraQuals = MD->getTypeQualifiers();
495 }
496
497 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000498 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
499 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000500 }
501
502 // Build the implicit member references to the field of the
503 // anonymous struct/union.
504 Expr *Result = BaseObjectExpr;
505 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
506 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
507 FI != FIEnd; ++FI) {
508 QualType MemberType = (*FI)->getType();
509 if (!(*FI)->isMutable()) {
510 unsigned combinedQualifiers
511 = MemberType.getCVRQualifiers() | ExtraQuals;
512 MemberType = MemberType.getQualifiedType(combinedQualifiers);
513 }
Steve Naroff774e4152009-01-21 00:14:39 +0000514 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
515 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000516 BaseObjectIsPointer = false;
517 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
518 OpLoc = SourceLocation();
519 }
520
Sebastian Redlcd883f72009-01-18 18:53:16 +0000521 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000522}
523
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000524/// ActOnDeclarationNameExpr - The parser has read some kind of name
525/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
526/// performs lookup on that name and returns an expression that refers
527/// to that name. This routine isn't directly called from the parser,
528/// because the parser doesn't know about DeclarationName. Rather,
529/// this routine is called by ActOnIdentifierExpr,
530/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
531/// which form the DeclarationName from the corresponding syntactic
532/// forms.
533///
534/// HasTrailingLParen indicates whether this identifier is used in a
535/// function call context. LookupCtx is only used for a C++
536/// qualified-id (foo::bar) to indicate the class or namespace that
537/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000538///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000539/// isAddressOfOperand means that this expression is the direct operand
540/// of an address-of operator. This matters because this is the only
541/// situation where a qualified name referencing a non-static member may
542/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000543Sema::OwningExprResult
544Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
545 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000546 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000547 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000548 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000549 if (SS && SS->isInvalid())
550 return ExprError();
551 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000552
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000553 if (getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
554 HasTrailingLParen && Lookup.getKind() == LookupResult::NotFound) {
555 // We've seen something of the form
556 //
557 // identifier(
558 //
559 // and we did not find any entity by the name
560 // "identifier". However, this identifier is still subject to
561 // argument-dependent lookup, so keep track of the name.
562 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
563 Context.OverloadTy,
564 Loc));
565 }
566
Douglas Gregor09be81b2009-02-04 17:27:36 +0000567 NamedDecl *D = 0;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000568 if (Lookup.isAmbiguous()) {
569 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
570 SS && SS->isSet() ? SS->getRange()
571 : SourceRange());
572 return ExprError();
573 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000574 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000575
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000576 // If this reference is in an Objective-C method, then ivar lookup happens as
577 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000578 IdentifierInfo *II = Name.getAsIdentifierInfo();
579 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000580 // There are two cases to handle here. 1) scoped lookup could have failed,
581 // in which case we should look for an ivar. 2) scoped lookup could have
582 // found a decl, but that decl is outside the current method (i.e. a global
583 // variable). In these two cases, we do a lookup for an ivar with this
584 // name, if the lookup suceeds, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000585 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000586 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000587 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000588 // FIXME: This should use a new expr for a direct reference, don't turn
589 // this into Self->ivar, just return a BareIVarExpr or something.
590 IdentifierInfo &II = Context.Idents.get("self");
Sebastian Redlcd883f72009-01-18 18:53:16 +0000591 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Steve Naroff774e4152009-01-21 00:14:39 +0000592 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
593 Loc, static_cast<Expr*>(SelfExpr.release()),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000594 true, true);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000595 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000596 return Owned(MRef);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000597 }
598 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000599 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000600 if (D == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000601 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000602 getCurMethodDecl()->getClassInterface()));
Steve Naroff774e4152009-01-21 00:14:39 +0000603 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000604 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000605 }
Chris Lattner4b009652007-07-25 00:24:17 +0000606 if (D == 0) {
607 // Otherwise, this could be an implicitly declared function reference (legal
608 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000609 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000610 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000611 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000612 else {
613 // If this name wasn't predeclared and if this is not a function call,
614 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000615 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000616 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
617 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000618 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
619 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000620 return ExprError(Diag(Loc, diag::err_undeclared_use)
621 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000622 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000623 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000624 }
625 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000626
Sebastian Redl0c9da212009-02-03 20:19:35 +0000627 // If this is an expression of the form &Class::member, don't build an
628 // implicit member ref, because we want a pointer to the member in general,
629 // not any specific instance's member.
630 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000631 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
Douglas Gregor09be81b2009-02-04 17:27:36 +0000632 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000633 QualType DType;
634 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
635 DType = FD->getType().getNonReferenceType();
636 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
637 DType = Method->getType();
638 } else if (isa<OverloadedFunctionDecl>(D)) {
639 DType = Context.OverloadTy;
640 }
641 // Could be an inner type. That's diagnosed below, so ignore it here.
642 if (!DType.isNull()) {
643 // The pointer is type- and value-dependent if it points into something
644 // dependent.
645 bool Dependent = false;
646 for (; DC; DC = DC->getParent()) {
647 // FIXME: could stop early at namespace scope.
648 if (DC->isRecord()) {
649 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
650 if (Context.getTypeDeclType(Record)->isDependentType()) {
651 Dependent = true;
652 break;
653 }
654 }
655 }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000656 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000657 }
658 }
659 }
660
Douglas Gregor723d3332009-01-07 00:43:41 +0000661 // We may have found a field within an anonymous union or struct
662 // (C++ [class.union]).
663 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
664 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
665 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000666
Douglas Gregor3257fb52008-12-22 05:46:06 +0000667 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
668 if (!MD->isStatic()) {
669 // C++ [class.mfct.nonstatic]p2:
670 // [...] if name lookup (3.4.1) resolves the name in the
671 // id-expression to a nonstatic nontype member of class X or of
672 // a base class of X, the id-expression is transformed into a
673 // class member access expression (5.2.5) using (*this) (9.3.2)
674 // as the postfix-expression to the left of the '.' operator.
675 DeclContext *Ctx = 0;
676 QualType MemberType;
677 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
678 Ctx = FD->getDeclContext();
679 MemberType = FD->getType();
680
681 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
682 MemberType = RefType->getPointeeType();
683 else if (!FD->isMutable()) {
684 unsigned combinedQualifiers
685 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
686 MemberType = MemberType.getQualifiedType(combinedQualifiers);
687 }
688 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
689 if (!Method->isStatic()) {
690 Ctx = Method->getParent();
691 MemberType = Method->getType();
692 }
693 } else if (OverloadedFunctionDecl *Ovl
694 = dyn_cast<OverloadedFunctionDecl>(D)) {
695 for (OverloadedFunctionDecl::function_iterator
696 Func = Ovl->function_begin(),
697 FuncEnd = Ovl->function_end();
698 Func != FuncEnd; ++Func) {
699 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
700 if (!DMethod->isStatic()) {
701 Ctx = Ovl->getDeclContext();
702 MemberType = Context.OverloadTy;
703 break;
704 }
705 }
706 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000707
708 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000709 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
710 QualType ThisType = Context.getTagDeclType(MD->getParent());
711 if ((Context.getCanonicalType(CtxType)
712 == Context.getCanonicalType(ThisType)) ||
713 IsDerivedFrom(ThisType, CtxType)) {
714 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000715 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor3257fb52008-12-22 05:46:06 +0000716 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +0000717 return Owned(new (Context) MemberExpr(This, true, D,
Sebastian Redlcd883f72009-01-18 18:53:16 +0000718 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000719 }
720 }
721 }
722 }
723
Douglas Gregor8acb7272008-12-11 16:49:14 +0000724 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000725 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
726 if (MD->isStatic())
727 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000728 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
729 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000730 }
731
Douglas Gregor3257fb52008-12-22 05:46:06 +0000732 // Any other ways we could have found the field in a well-formed
733 // program would have been turned into implicit member expressions
734 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000735 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
736 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000737 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000738
Chris Lattner4b009652007-07-25 00:24:17 +0000739 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000740 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000741 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000742 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000743 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000744 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000745
Steve Naroffd6163f32008-09-05 22:11:13 +0000746 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000747 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000748 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
749 false, false, SS));
Douglas Gregord2baafd2008-10-21 16:13:35 +0000750
Steve Naroffd6163f32008-09-05 22:11:13 +0000751 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000752
Steve Naroffd6163f32008-09-05 22:11:13 +0000753 // check if referencing an identifier with __attribute__((deprecated)).
754 if (VD->getAttr<DeprecatedAttr>())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000755 ExprError(Diag(Loc, diag::warn_deprecated) << VD->getDeclName());
756
Douglas Gregor48840c72008-12-10 23:01:14 +0000757 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
758 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
759 Scope *CheckS = S;
760 while (CheckS) {
761 if (CheckS->isWithinElse() &&
762 CheckS->getControlParent()->isDeclScope(Var)) {
763 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000764 ExprError(Diag(Loc, diag::warn_value_always_false)
765 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000766 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000767 ExprError(Diag(Loc, diag::warn_value_always_zero)
768 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000769 break;
770 }
771
772 // Move up one more control parent to check again.
773 CheckS = CheckS->getControlParent();
774 if (CheckS)
775 CheckS = CheckS->getParent();
776 }
777 }
778 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000779
780 // Only create DeclRefExpr's for valid Decl's.
781 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000782 return ExprError();
783
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000784 // If the identifier reference is inside a block, and it refers to a value
785 // that is outside the block, create a BlockDeclRefExpr instead of a
786 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
787 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000788 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000789 // We do not do this for things like enum constants, global variables, etc,
790 // as they do not get snapshotted.
791 //
792 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000793 // The BlocksAttr indicates the variable is bound by-reference.
794 if (VD->getAttr<BlocksAttr>())
Steve Naroff774e4152009-01-21 00:14:39 +0000795 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000796 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000797
Steve Naroff52059382008-10-10 01:28:17 +0000798 // Variable will be bound by-copy, make it const within the closure.
799 VD->getType().addConst();
Steve Naroff774e4152009-01-21 00:14:39 +0000800 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000801 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000802 }
803 // If this reference is not in a block or if the referenced variable is
804 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000805
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000806 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000807 bool ValueDependent = false;
808 if (getLangOptions().CPlusPlus) {
809 // C++ [temp.dep.expr]p3:
810 // An id-expression is type-dependent if it contains:
811 // - an identifier that was declared with a dependent type,
812 if (VD->getType()->isDependentType())
813 TypeDependent = true;
814 // - FIXME: a template-id that is dependent,
815 // - a conversion-function-id that specifies a dependent type,
816 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
817 Name.getCXXNameType()->isDependentType())
818 TypeDependent = true;
819 // - a nested-name-specifier that contains a class-name that
820 // names a dependent type.
821 else if (SS && !SS->isEmpty()) {
822 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
823 DC; DC = DC->getParent()) {
824 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000825 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000826 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
827 if (Context.getTypeDeclType(Record)->isDependentType()) {
828 TypeDependent = true;
829 break;
830 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000831 }
832 }
833 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000834
Douglas Gregora5d84612008-12-10 20:57:37 +0000835 // C++ [temp.dep.constexpr]p2:
836 //
837 // An identifier is value-dependent if it is:
838 // - a name declared with a dependent type,
839 if (TypeDependent)
840 ValueDependent = true;
841 // - the name of a non-type template parameter,
842 else if (isa<NonTypeTemplateParmDecl>(VD))
843 ValueDependent = true;
844 // - a constant with integral or enumeration type and is
845 // initialized with an expression that is value-dependent
846 // (FIXME!).
847 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000848
Sebastian Redlcd883f72009-01-18 18:53:16 +0000849 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
850 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000851}
852
Sebastian Redlcd883f72009-01-18 18:53:16 +0000853Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
854 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000855 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000856
Chris Lattner4b009652007-07-25 00:24:17 +0000857 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000858 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000859 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
860 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
861 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000862 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000863
Chris Lattner7e637512008-01-12 08:14:25 +0000864 // Pre-defined identifiers are of type char[x], where x is the length of the
865 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000866 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000867 if (FunctionDecl *FD = getCurFunctionDecl())
868 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000869 else if (ObjCMethodDecl *MD = getCurMethodDecl())
870 Length = MD->getSynthesizedMethodSize();
871 else {
872 Diag(Loc, diag::ext_predef_outside_function);
873 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
874 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
875 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000876
877
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000878 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000879 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000880 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +0000881 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +0000882}
883
Sebastian Redlcd883f72009-01-18 18:53:16 +0000884Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000885 llvm::SmallString<16> CharBuffer;
886 CharBuffer.resize(Tok.getLength());
887 const char *ThisTokBegin = &CharBuffer[0];
888 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000889
Chris Lattner4b009652007-07-25 00:24:17 +0000890 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
891 Tok.getLocation(), PP);
892 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000893 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +0000894
895 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
896
Sebastian Redl75324932009-01-20 22:23:13 +0000897 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
898 Literal.isWide(),
899 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000900}
901
Sebastian Redlcd883f72009-01-18 18:53:16 +0000902Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
903 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +0000904 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
905 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +0000906 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +0000907 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +0000908 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +0000909 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000910 }
Ted Kremenekdbde2282009-01-13 23:19:12 +0000911
Chris Lattner4b009652007-07-25 00:24:17 +0000912 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000913 // Add padding so that NumericLiteralParser can overread by one character.
914 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000915 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +0000916
Chris Lattner4b009652007-07-25 00:24:17 +0000917 // Get the spelling of the token, which eliminates trigraphs, etc.
918 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000919
Chris Lattner4b009652007-07-25 00:24:17 +0000920 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
921 Tok.getLocation(), PP);
922 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000923 return ExprError();
924
Chris Lattner1de66eb2007-08-26 03:42:43 +0000925 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000926
Chris Lattner1de66eb2007-08-26 03:42:43 +0000927 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000928 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000929 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000930 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000931 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000932 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000933 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000934 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000935
936 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
937
Ted Kremenekddedbe22007-11-29 00:56:49 +0000938 // isExact will be set by GetFloatValue().
939 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +0000940 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
941 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +0000942
Chris Lattner1de66eb2007-08-26 03:42:43 +0000943 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000944 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +0000945 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000946 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000947
Neil Booth7421e9c2007-08-29 22:00:19 +0000948 // long long is a C99 feature.
949 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000950 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000951 Diag(Tok.getLocation(), diag::ext_longlong);
952
Chris Lattner4b009652007-07-25 00:24:17 +0000953 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000954 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000955
Chris Lattner4b009652007-07-25 00:24:17 +0000956 if (Literal.GetIntegerValue(ResultVal)) {
957 // If this value didn't fit into uintmax_t, warn and force to ull.
958 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000959 Ty = Context.UnsignedLongLongTy;
960 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000961 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000962 } else {
963 // If this value fits into a ULL, try to figure out what else it fits into
964 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000965
Chris Lattner4b009652007-07-25 00:24:17 +0000966 // Octal, Hexadecimal, and integers with a U suffix are allowed to
967 // be an unsigned int.
968 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
969
970 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000971 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000972 if (!Literal.isLong && !Literal.isLongLong) {
973 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000974 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000975
Chris Lattner4b009652007-07-25 00:24:17 +0000976 // Does it fit in a unsigned int?
977 if (ResultVal.isIntN(IntSize)) {
978 // Does it fit in a signed int?
979 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000980 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000981 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000982 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000983 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000984 }
Chris Lattner4b009652007-07-25 00:24:17 +0000985 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000986
Chris Lattner4b009652007-07-25 00:24:17 +0000987 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000988 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000989 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000990
Chris Lattner4b009652007-07-25 00:24:17 +0000991 // Does it fit in a unsigned long?
992 if (ResultVal.isIntN(LongSize)) {
993 // Does it fit in a signed long?
994 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000995 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000996 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000997 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000998 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000999 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001000 }
1001
Chris Lattner4b009652007-07-25 00:24:17 +00001002 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001003 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001004 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001005
Chris Lattner4b009652007-07-25 00:24:17 +00001006 // Does it fit in a unsigned long long?
1007 if (ResultVal.isIntN(LongLongSize)) {
1008 // Does it fit in a signed long long?
1009 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001010 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001011 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001012 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001013 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001014 }
1015 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001016
Chris Lattner4b009652007-07-25 00:24:17 +00001017 // If we still couldn't decide a type, we probably have something that
1018 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001019 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001020 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001021 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001022 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001023 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001024
Chris Lattnere4068872008-05-09 05:59:00 +00001025 if (ResultVal.getBitWidth() != Width)
1026 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001027 }
Sebastian Redl75324932009-01-20 22:23:13 +00001028 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001029 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001030
Chris Lattner1de66eb2007-08-26 03:42:43 +00001031 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1032 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001033 Res = new (Context) ImaginaryLiteral(Res,
1034 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001035
1036 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001037}
1038
Sebastian Redlcd883f72009-01-18 18:53:16 +00001039Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1040 SourceLocation R, ExprArg Val) {
1041 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001042 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001043 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001044}
1045
1046/// The UsualUnaryConversions() function is *not* called by this routine.
1047/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001048bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1049 SourceLocation OpLoc,
1050 const SourceRange &ExprRange,
1051 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +00001052 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001053 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001054 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001055 if (isSizeof)
1056 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1057 return false;
1058 }
1059
1060 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001061 Diag(OpLoc, diag::ext_sizeof_void_type)
1062 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001063 return false;
1064 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001065
Chris Lattner159fe082009-01-24 19:46:37 +00001066 return DiagnoseIncompleteType(OpLoc, exprType,
1067 isSizeof ? diag::err_sizeof_incomplete_type :
1068 diag::err_alignof_incomplete_type,
1069 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001070}
1071
Chris Lattner8d9f7962009-01-24 20:17:12 +00001072bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1073 const SourceRange &ExprRange) {
1074 E = E->IgnoreParens();
1075
1076 // alignof decl is always ok.
1077 if (isa<DeclRefExpr>(E))
1078 return false;
1079
1080 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1081 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1082 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001083 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001084 return true;
1085 }
1086 // Other fields are ok.
1087 return false;
1088 }
1089 }
1090 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1091}
1092
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001093/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1094/// the same for @c alignof and @c __alignof
1095/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001096Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001097Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1098 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001099 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001100 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001101
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001102 QualType ArgTy;
1103 SourceRange Range;
1104 if (isType) {
1105 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1106 Range = ArgRange;
Chris Lattnera78909b2009-01-24 19:49:13 +00001107
1108 // Verify that the operand is valid.
1109 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1110 return ExprError();
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001111 } else {
1112 // Get the end location.
1113 Expr *ArgEx = (Expr *)TyOrEx;
1114 Range = ArgEx->getSourceRange();
1115 ArgTy = ArgEx->getType();
Chris Lattnera78909b2009-01-24 19:49:13 +00001116
1117 // Verify that the operand is valid.
Chris Lattner8d9f7962009-01-24 20:17:12 +00001118 bool isInvalid;
Chris Lattner364a42d2009-01-24 21:29:22 +00001119 if (!isSizeof) {
Chris Lattner8d9f7962009-01-24 20:17:12 +00001120 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattner364a42d2009-01-24 21:29:22 +00001121 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1122 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1123 isInvalid = true;
1124 } else {
1125 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1126 }
Chris Lattner8d9f7962009-01-24 20:17:12 +00001127
1128 if (isInvalid) {
Chris Lattnera78909b2009-01-24 19:49:13 +00001129 DeleteExpr(ArgEx);
1130 return ExprError();
1131 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001132 }
1133
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001134 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff774e4152009-01-21 00:14:39 +00001135 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner159fe082009-01-24 19:46:37 +00001136 Context.getSizeType(), OpLoc,
1137 Range.getEnd()));
Chris Lattner4b009652007-07-25 00:24:17 +00001138}
1139
Chris Lattner5110ad52007-08-24 21:41:10 +00001140QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +00001141 DefaultFunctionArrayConversion(V);
1142
Chris Lattnera16e42d2007-08-26 05:39:26 +00001143 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001144 if (const ComplexType *CT = V->getType()->getAsComplexType())
1145 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001146
1147 // Otherwise they pass through real integer and floating point types here.
1148 if (V->getType()->isArithmeticType())
1149 return V->getType();
1150
1151 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +00001152 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001153 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001154}
1155
1156
Chris Lattner4b009652007-07-25 00:24:17 +00001157
Sebastian Redl8b769972009-01-19 00:08:26 +00001158Action::OwningExprResult
1159Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1160 tok::TokenKind Kind, ExprArg Input) {
1161 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001162
Chris Lattner4b009652007-07-25 00:24:17 +00001163 UnaryOperator::Opcode Opc;
1164 switch (Kind) {
1165 default: assert(0 && "Unknown unary op!");
1166 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1167 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1168 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001169
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001170 if (getLangOptions().CPlusPlus &&
1171 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1172 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001173 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001174 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1175
1176 // C++ [over.inc]p1:
1177 //
1178 // [...] If the function is a member function with one
1179 // parameter (which shall be of type int) or a non-member
1180 // function with two parameters (the second of which shall be
1181 // of type int), it defines the postfix increment operator ++
1182 // for objects of that type. When the postfix increment is
1183 // called as a result of using the ++ operator, the int
1184 // argument will have value zero.
1185 Expr *Args[2] = {
1186 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001187 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1188 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001189 };
1190
1191 // Build the candidate set for overloading
1192 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00001193 if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet))
1194 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001195
1196 // Perform overload resolution.
1197 OverloadCandidateSet::iterator Best;
1198 switch (BestViableFunction(CandidateSet, Best)) {
1199 case OR_Success: {
1200 // We found a built-in operator or an overloaded operator.
1201 FunctionDecl *FnDecl = Best->Function;
1202
1203 if (FnDecl) {
1204 // We matched an overloaded operator. Build a call to that
1205 // operator.
1206
1207 // Convert the arguments.
1208 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1209 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001210 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001211 } else {
1212 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001213 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001214 FnDecl->getParamDecl(0)->getType(),
1215 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001216 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001217 }
1218
1219 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001220 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001221 = FnDecl->getType()->getAsFunctionType()->getResultType();
1222 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001223
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001224 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001225 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001226 SourceLocation());
1227 UsualUnaryConversions(FnExpr);
1228
Sebastian Redl8b769972009-01-19 00:08:26 +00001229 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001230 return Owned(new (Context)CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy,
Steve Naroffe5f128a2009-01-20 19:53:53 +00001231 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001232 } else {
1233 // We matched a built-in operator. Convert the arguments, then
1234 // break out so that we will build the appropriate built-in
1235 // operator node.
1236 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1237 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001238 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001239
1240 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001241 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001242 }
1243
1244 case OR_No_Viable_Function:
1245 // No viable function; fall through to handling this as a
1246 // built-in operator, which will produce an error message for us.
1247 break;
1248
1249 case OR_Ambiguous:
1250 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1251 << UnaryOperator::getOpcodeStr(Opc)
1252 << Arg->getSourceRange();
1253 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001254 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001255 }
1256
1257 // Either we found no viable overloaded operator or we matched a
1258 // built-in operator. In either case, fall through to trying to
1259 // build a built-in operation.
1260 }
1261
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001262 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1263 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001264 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001265 return ExprError();
1266 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001267 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001268}
1269
Sebastian Redl8b769972009-01-19 00:08:26 +00001270Action::OwningExprResult
1271Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1272 ExprArg Idx, SourceLocation RLoc) {
1273 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1274 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001275
Douglas Gregor80723c52008-11-19 17:17:41 +00001276 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001277 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001278 LHSExp->getType()->isEnumeralType() ||
1279 RHSExp->getType()->isRecordType() ||
1280 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001281 // Add the appropriate overloaded operators (C++ [over.match.oper])
1282 // to the candidate set.
1283 OverloadCandidateSet CandidateSet;
1284 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor48a87322009-02-04 16:44:47 +00001285 if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1286 SourceRange(LLoc, RLoc)))
1287 return ExprError();
Sebastian Redl8b769972009-01-19 00:08:26 +00001288
Douglas Gregor80723c52008-11-19 17:17:41 +00001289 // Perform overload resolution.
1290 OverloadCandidateSet::iterator Best;
1291 switch (BestViableFunction(CandidateSet, Best)) {
1292 case OR_Success: {
1293 // We found a built-in operator or an overloaded operator.
1294 FunctionDecl *FnDecl = Best->Function;
1295
1296 if (FnDecl) {
1297 // We matched an overloaded operator. Build a call to that
1298 // operator.
1299
1300 // Convert the arguments.
1301 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1302 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1303 PerformCopyInitialization(RHSExp,
1304 FnDecl->getParamDecl(0)->getType(),
1305 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001306 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001307 } else {
1308 // Convert the arguments.
1309 if (PerformCopyInitialization(LHSExp,
1310 FnDecl->getParamDecl(0)->getType(),
1311 "passing") ||
1312 PerformCopyInitialization(RHSExp,
1313 FnDecl->getParamDecl(1)->getType(),
1314 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001315 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001316 }
1317
1318 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001319 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001320 = FnDecl->getType()->getAsFunctionType()->getResultType();
1321 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001322
Douglas Gregor80723c52008-11-19 17:17:41 +00001323 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001324 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor80723c52008-11-19 17:17:41 +00001325 SourceLocation());
1326 UsualUnaryConversions(FnExpr);
1327
Sebastian Redl8b769972009-01-19 00:08:26 +00001328 Base.release();
1329 Idx.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001330 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, Args, 2,
1331 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001332 } else {
1333 // We matched a built-in operator. Convert the arguments, then
1334 // break out so that we will build the appropriate built-in
1335 // operator node.
1336 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1337 "passing") ||
1338 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1339 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001340 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001341
1342 break;
1343 }
1344 }
1345
1346 case OR_No_Viable_Function:
1347 // No viable function; fall through to handling this as a
1348 // built-in operator, which will produce an error message for us.
1349 break;
1350
1351 case OR_Ambiguous:
1352 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1353 << "[]"
1354 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1355 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001356 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001357 }
1358
1359 // Either we found no viable overloaded operator or we matched a
1360 // built-in operator. In either case, fall through to trying to
1361 // build a built-in operation.
1362 }
1363
Chris Lattner4b009652007-07-25 00:24:17 +00001364 // Perform default conversions.
1365 DefaultFunctionArrayConversion(LHSExp);
1366 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001367
Chris Lattner4b009652007-07-25 00:24:17 +00001368 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1369
1370 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001371 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001372 // in the subscript position. As a result, we need to derive the array base
1373 // and index from the expression types.
1374 Expr *BaseExpr, *IndexExpr;
1375 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001376 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001377 BaseExpr = LHSExp;
1378 IndexExpr = RHSExp;
1379 // FIXME: need to deal with const...
1380 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001381 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001382 // Handle the uncommon case of "123[Ptr]".
1383 BaseExpr = RHSExp;
1384 IndexExpr = LHSExp;
1385 // FIXME: need to deal with const...
1386 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001387 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1388 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001389 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001390
Chris Lattner4b009652007-07-25 00:24:17 +00001391 // FIXME: need to deal with const...
1392 ResultType = VTy->getElementType();
1393 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001394 return ExprError(Diag(LHSExp->getLocStart(),
1395 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1396 }
Chris Lattner4b009652007-07-25 00:24:17 +00001397 // C99 6.5.2.1p1
1398 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001399 return ExprError(Diag(IndexExpr->getLocStart(),
1400 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001401
1402 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1403 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001404 // void (*)(int)) and pointers to incomplete types. Functions are not
1405 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001406 if (!ResultType->isObjectType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001407 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001408 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001409 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001410
Sebastian Redl8b769972009-01-19 00:08:26 +00001411 Base.release();
1412 Idx.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001413 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1414 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001415}
1416
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001417QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001418CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001419 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001420 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001421
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001422 // The vector accessor can't exceed the number of elements.
1423 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001424
1425 // This flag determines whether or not the component is one of the four
1426 // special names that indicate a subset of exactly half the elements are
1427 // to be selected.
1428 bool HalvingSwizzle = false;
1429
1430 // This flag determines whether or not CompName has an 's' char prefix,
1431 // indicating that it is a string of hex values to be used as vector indices.
1432 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001433
1434 // Check that we've found one of the special components, or that the component
1435 // names must come from the same set.
1436 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001437 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1438 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001439 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001440 do
1441 compStr++;
1442 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001443 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001444 do
1445 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001446 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001447 }
Nate Begeman1486b502009-01-18 01:47:54 +00001448
1449 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001450 // We didn't get to the end of the string. This means the component names
1451 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001452 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1453 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001454 return QualType();
1455 }
Nate Begeman1486b502009-01-18 01:47:54 +00001456
1457 // Ensure no component accessor exceeds the width of the vector type it
1458 // operates on.
1459 if (!HalvingSwizzle) {
1460 compStr = CompName.getName();
1461
1462 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001463 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001464
1465 while (*compStr) {
1466 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1467 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1468 << baseType << SourceRange(CompLoc);
1469 return QualType();
1470 }
1471 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001472 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001473
Nate Begeman1486b502009-01-18 01:47:54 +00001474 // If this is a halving swizzle, verify that the base type has an even
1475 // number of elements.
1476 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001477 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001478 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001479 return QualType();
1480 }
1481
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001482 // The component accessor looks fine - now we need to compute the actual type.
1483 // The vector type is implied by the component accessor. For example,
1484 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001485 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001486 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001487 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1488 : CompName.getLength();
1489 if (HexSwizzle)
1490 CompSize--;
1491
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001492 if (CompSize == 1)
1493 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001494
Nate Begemanaf6ed502008-04-18 23:10:10 +00001495 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001496 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001497 // diagostics look bad. We want extended vector types to appear built-in.
1498 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1499 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1500 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001501 }
1502 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001503}
1504
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001505/// constructSetterName - Return the setter name for the given
1506/// identifier, i.e. "set" + Name where the initial character of Name
1507/// has been capitalized.
1508// FIXME: Merge with same routine in Parser. But where should this
1509// live?
1510static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1511 const IdentifierInfo *Name) {
1512 llvm::SmallString<100> SelectorName;
1513 SelectorName = "set";
1514 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1515 SelectorName[3] = toupper(SelectorName[3]);
1516 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1517}
1518
Sebastian Redl8b769972009-01-19 00:08:26 +00001519Action::OwningExprResult
1520Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1521 tok::TokenKind OpKind, SourceLocation MemberLoc,
1522 IdentifierInfo &Member) {
1523 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001524 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001525
1526 // Perform default conversions.
1527 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001528
Steve Naroff2cb66382007-07-26 03:11:44 +00001529 QualType BaseType = BaseExpr->getType();
1530 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001531
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001532 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1533 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001534 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001535 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001536 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001537 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001538 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1539 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001540 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001541 return ExprError(Diag(MemberLoc,
1542 diag::err_typecheck_member_reference_arrow)
1543 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001544 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001545
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001546 // Handle field access to simple records. This also handles access to fields
1547 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001548 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001549 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001550 if (DiagnoseIncompleteType(OpLoc, BaseType,
1551 diag::err_typecheck_incomplete_tag,
1552 BaseExpr->getSourceRange()))
1553 return ExprError();
1554
Steve Naroff2cb66382007-07-26 03:11:44 +00001555 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001556 // FIXME: Qualified name lookup for C++ is a bit more complicated
1557 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001558 LookupResult Result
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001559 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001560 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001561
Douglas Gregor09be81b2009-02-04 17:27:36 +00001562 NamedDecl *MemberDecl = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001563 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001564 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1565 << &Member << BaseExpr->getSourceRange());
1566 else if (Result.isAmbiguous()) {
1567 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1568 MemberLoc, BaseExpr->getSourceRange());
1569 return ExprError();
1570 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001571 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001572
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001573 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001574 // We may have found a field within an anonymous union or struct
1575 // (C++ [class.union]).
1576 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001577 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001578 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001579
Douglas Gregor82d44772008-12-20 23:49:58 +00001580 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1581 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001582 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001583 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1584 MemberType = Ref->getPointeeType();
1585 else {
1586 unsigned combinedQualifiers =
1587 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001588 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001589 combinedQualifiers &= ~QualType::Const;
1590 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1591 }
Eli Friedman76b49832008-02-06 22:48:16 +00001592
Steve Naroff774e4152009-01-21 00:14:39 +00001593 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1594 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001595 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001596 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001597 Var, MemberLoc,
1598 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001599 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001600 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1601 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001602 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001603 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001604 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001605 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001606 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001607 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Enum,
Sebastian Redl8b769972009-01-19 00:08:26 +00001608 MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001609 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001610 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1611 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001612
Douglas Gregor82d44772008-12-20 23:49:58 +00001613 // We found a declaration kind that we didn't expect. This is a
1614 // generic error message that tells the user that she can't refer
1615 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001616 return ExprError(Diag(MemberLoc,
1617 diag::err_typecheck_member_reference_unknown)
1618 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001619 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001620
Chris Lattnere9d71612008-07-21 04:59:05 +00001621 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1622 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001623 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001624 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Steve Naroff774e4152009-01-21 00:14:39 +00001625 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1626 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001627 OpKind == tok::arrow);
1628 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001629 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001630 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001631 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1632 << IFTy->getDecl()->getDeclName() << &Member
1633 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001634 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001635
Chris Lattnere9d71612008-07-21 04:59:05 +00001636 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1637 // pointer to a (potentially qualified) interface type.
1638 const PointerType *PTy;
1639 const ObjCInterfaceType *IFTy;
1640 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1641 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1642 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001643
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001644 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001645 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001646 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001647 MemberLoc, BaseExpr));
1648
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001649 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001650 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1651 E = IFTy->qual_end(); I != E; ++I)
1652 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001653 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001654 MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001655
1656 // If that failed, look for an "implicit" property by seeing if the nullary
1657 // selector is implemented.
1658
1659 // FIXME: The logic for looking up nullary and unary selectors should be
1660 // shared with the code in ActOnInstanceMessage.
1661
1662 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1663 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001664
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001665 // If this reference is in an @implementation, check for 'private' methods.
1666 if (!Getter)
1667 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1668 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1669 if (ObjCImplementationDecl *ImpDecl =
1670 ObjCImplementations[ClassDecl->getIdentifier()])
1671 Getter = ImpDecl->getInstanceMethod(Sel);
1672
Steve Naroff04151f32008-10-22 19:16:27 +00001673 // Look through local category implementations associated with the class.
1674 if (!Getter) {
1675 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1676 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1677 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1678 }
1679 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001680 if (Getter) {
1681 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001682 // will look for the matching setter, in case it is needed.
1683 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1684 &Member);
1685 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1686 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1687 if (!Setter) {
1688 // If this reference is in an @implementation, also check for 'private'
1689 // methods.
1690 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1691 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1692 if (ObjCImplementationDecl *ImpDecl =
1693 ObjCImplementations[ClassDecl->getIdentifier()])
1694 Setter = ImpDecl->getInstanceMethod(SetterSel);
1695 }
1696 // Look through local category implementations associated with the class.
1697 if (!Setter) {
1698 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1699 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1700 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1701 }
1702 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001703
1704 // FIXME: we must check that the setter has property type.
Steve Naroff774e4152009-01-21 00:14:39 +00001705 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
1706 Setter, MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001707 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001708
1709 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1710 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001711 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001712 // Handle properties on qualified "id" protocols.
1713 const ObjCQualifiedIdType *QIdTy;
1714 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1715 // Check protocols on qualified interfaces.
1716 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001717 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroffd1d44402008-10-20 22:53:06 +00001718 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001719 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001720 MemberLoc, BaseExpr));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001721 // Also must look for a getter name which uses property syntax.
1722 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1723 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Steve Naroff774e4152009-01-21 00:14:39 +00001724 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
1725 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001726 }
1727 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001728
1729 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1730 << &Member << BaseType);
1731 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001732 // Handle 'field access' to vectors, such as 'V.xx'.
1733 if (BaseType->isExtVectorType() && OpKind == tok::period) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001734 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1735 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001736 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00001737 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
1738 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001739 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001740
1741 return ExprError(Diag(MemberLoc,
1742 diag::err_typecheck_member_reference_struct_union)
1743 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001744}
1745
Douglas Gregor3257fb52008-12-22 05:46:06 +00001746/// ConvertArgumentsForCall - Converts the arguments specified in
1747/// Args/NumArgs to the parameter types of the function FDecl with
1748/// function prototype Proto. Call is the call expression itself, and
1749/// Fn is the function expression. For a C++ member function, this
1750/// routine does not attempt to convert the object argument. Returns
1751/// true if the call is ill-formed.
1752bool
1753Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1754 FunctionDecl *FDecl,
1755 const FunctionTypeProto *Proto,
1756 Expr **Args, unsigned NumArgs,
1757 SourceLocation RParenLoc) {
1758 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1759 // assignment, to the types of the corresponding parameter, ...
1760 unsigned NumArgsInProto = Proto->getNumArgs();
1761 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001762 bool Invalid = false;
1763
Douglas Gregor3257fb52008-12-22 05:46:06 +00001764 // If too few arguments are available (and we don't have default
1765 // arguments for the remaining parameters), don't make the call.
1766 if (NumArgs < NumArgsInProto) {
1767 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1768 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1769 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1770 // Use default arguments for missing arguments
1771 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001772 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001773 }
1774
1775 // If too many are passed and not variadic, error on the extras and drop
1776 // them.
1777 if (NumArgs > NumArgsInProto) {
1778 if (!Proto->isVariadic()) {
1779 Diag(Args[NumArgsInProto]->getLocStart(),
1780 diag::err_typecheck_call_too_many_args)
1781 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1782 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1783 Args[NumArgs-1]->getLocEnd());
1784 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001785 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001786 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001787 }
1788 NumArgsToCheck = NumArgsInProto;
1789 }
1790
1791 // Continue to check argument types (even if we have too few/many args).
1792 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1793 QualType ProtoArgType = Proto->getArgType(i);
1794
1795 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001796 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001797 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001798
1799 // Pass the argument.
1800 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1801 return true;
1802 } else
1803 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00001804 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001805 QualType ArgType = Arg->getType();
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001806
Douglas Gregor3257fb52008-12-22 05:46:06 +00001807 Call->setArg(i, Arg);
1808 }
1809
1810 // If this is a variadic call, handle args passed through "...".
1811 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001812 VariadicCallType CallType = VariadicFunction;
1813 if (Fn->getType()->isBlockPointerType())
1814 CallType = VariadicBlock; // Block
1815 else if (isa<MemberExpr>(Fn))
1816 CallType = VariadicMethod;
1817
Douglas Gregor3257fb52008-12-22 05:46:06 +00001818 // Promote the arguments (C99 6.5.2.2p7).
1819 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1820 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001821 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001822 Call->setArg(i, Arg);
1823 }
1824 }
1825
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001826 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001827}
1828
Steve Naroff87d58b42007-09-16 03:34:24 +00001829/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001830/// This provides the location of the left/right parens and a list of comma
1831/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00001832Action::OwningExprResult
1833Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1834 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001835 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001836 unsigned NumArgs = args.size();
1837 Expr *Fn = static_cast<Expr *>(fn.release());
1838 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00001839 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001840 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001841 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001842
Douglas Gregor3257fb52008-12-22 05:46:06 +00001843 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001844 // Determine whether this is a dependent call inside a C++ template,
1845 // in which case we won't do any semantic analysis now.
1846 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
1847 bool Dependent = false;
1848 if (Fn->isTypeDependent())
1849 Dependent = true;
1850 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1851 Dependent = true;
1852
1853 if (Dependent)
1854 return Owned(new (Context) CallExpr(Fn, Args, NumArgs,
1855 Context.DependentTy, RParenLoc));
1856
1857 // Determine whether this is a call to an object (C++ [over.call.object]).
1858 if (Fn->getType()->isRecordType())
1859 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1860 CommaLocs, RParenLoc));
1861
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001862 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00001863 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1864 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1865 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00001866 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1867 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001868 }
1869
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001870 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00001871 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001872 Expr *FnExpr = Fn;
1873 bool ADL = true;
1874 while (true) {
1875 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
1876 FnExpr = IcExpr->getSubExpr();
1877 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001878 // Parentheses around a function disable ADL
1879 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001880 ADL = false;
1881 FnExpr = PExpr->getSubExpr();
1882 } else if (isa<UnaryOperator>(FnExpr) &&
1883 cast<UnaryOperator>(FnExpr)->getOpcode()
1884 == UnaryOperator::AddrOf) {
1885 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
1886 } else {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001887 if (isa<DeclRefExpr>(FnExpr)) {
1888 DRExpr = cast<DeclRefExpr>(FnExpr);
1889
1890 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
1891 ADL = ADL && !isa<QualifiedDeclRefExpr>(DRExpr);
1892 }
1893 else if (UnresolvedFunctionNameExpr *DepName
1894 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr))
1895 UnqualifiedName = DepName->getName();
1896 else {
1897 // Any kind of name that does not refer to a declaration (or
1898 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
1899 ADL = false;
1900 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001901 break;
1902 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001903 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001904
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001905 OverloadedFunctionDecl *Ovl = 0;
1906 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001907 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001908 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1909 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001910
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001911 if (getLangOptions().CPlusPlus && (FDecl || Ovl || UnqualifiedName)) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001912 // We don't perform ADL for builtins.
1913 if (FDecl && FDecl->getIdentifier() &&
1914 FDecl->getIdentifier()->getBuiltinID())
1915 ADL = false;
1916
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001917 if (Ovl || ADL) {
1918 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
1919 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001920 NumArgs, CommaLocs, RParenLoc, ADL);
1921 if (!FDecl)
1922 return ExprError();
1923
1924 // Update Fn to refer to the actual function selected.
1925 Expr *NewFn = 0;
1926 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001927 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001928 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
1929 QDRExpr->getLocation(),
1930 false, false,
1931 QDRExpr->getSourceRange().getBegin());
1932 else
1933 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
1934 Fn->getSourceRange().getBegin());
1935 Fn->Destroy(Context);
1936 Fn = NewFn;
1937 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001938 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001939
1940 // Promote the function operand.
1941 UsualUnaryConversions(Fn);
1942
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001943 // Make the call expr early, before semantic checks. This guarantees cleanup
1944 // of arguments and function on error.
Sebastian Redl8b769972009-01-19 00:08:26 +00001945 // FIXME: Except that llvm::OwningPtr uses delete, when it really must be
1946 // Destroy(), or nothing gets cleaned up.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001947 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Fn, Args,NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001948 Context.BoolTy, RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001949
Steve Naroffd6163f32008-09-05 22:11:13 +00001950 const FunctionType *FuncT;
1951 if (!Fn->getType()->isBlockPointerType()) {
1952 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1953 // have type pointer to function".
1954 const PointerType *PT = Fn->getType()->getAsPointerType();
1955 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00001956 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1957 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00001958 FuncT = PT->getPointeeType()->getAsFunctionType();
1959 } else { // This is a block call.
1960 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1961 getAsFunctionType();
1962 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001963 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00001964 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1965 << Fn->getType() << Fn->getSourceRange());
1966
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001967 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001968 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00001969
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001970 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001971 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
1972 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00001973 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001974 } else {
1975 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00001976
Steve Naroffdb65e052007-08-28 23:30:39 +00001977 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001978 for (unsigned i = 0; i != NumArgs; i++) {
1979 Expr *Arg = Args[i];
1980 DefaultArgumentPromotion(Arg);
1981 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001982 }
Chris Lattner4b009652007-07-25 00:24:17 +00001983 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001984
Douglas Gregor3257fb52008-12-22 05:46:06 +00001985 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
1986 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00001987 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
1988 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00001989
Chris Lattner2e64c072007-08-10 20:18:51 +00001990 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001991 if (FDecl)
1992 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001993
Sebastian Redl8b769972009-01-19 00:08:26 +00001994 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00001995}
1996
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001997Action::OwningExprResult
1998Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
1999 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002000 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002001 QualType literalType = QualType::getFromOpaquePtr(Ty);
2002 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002003 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002004 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002005
Eli Friedman8c2173d2008-05-20 05:22:08 +00002006 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002007 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002008 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2009 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002010 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2011 diag::err_typecheck_decl_incomplete_type,
2012 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002013 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002014
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002015 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002016 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002017 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002018
Chris Lattnere5cb5862008-12-04 23:50:19 +00002019 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002020 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002021 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002022 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002023 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002024 InitExpr.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002025 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
2026 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002027}
2028
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002029Action::OwningExprResult
2030Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2031 InitListDesignations &Designators,
2032 SourceLocation RBraceLoc) {
2033 unsigned NumInit = initlist.size();
2034 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002035
Steve Naroff0acc9c92007-09-15 18:49:24 +00002036 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00002037 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002038
Steve Naroff774e4152009-01-21 00:14:39 +00002039 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002040 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002041 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002042 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002043}
2044
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002045/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002046bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002047 UsualUnaryConversions(castExpr);
2048
2049 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2050 // type needs to be scalar.
2051 if (castType->isVoidType()) {
2052 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002053 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2054 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002055 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002056 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2057 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2058 (castType->isStructureType() || castType->isUnionType())) {
2059 // GCC struct/union extension: allow cast to self.
2060 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2061 << castType << castExpr->getSourceRange();
2062 } else if (castType->isUnionType()) {
2063 // GCC cast to union extension
2064 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2065 RecordDecl::field_iterator Field, FieldEnd;
2066 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2067 Field != FieldEnd; ++Field) {
2068 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2069 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2070 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2071 << castExpr->getSourceRange();
2072 break;
2073 }
2074 }
2075 if (Field == FieldEnd)
2076 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2077 << castExpr->getType() << castExpr->getSourceRange();
2078 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002079 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002080 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002081 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002082 }
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002083 } else if (!castExpr->getType()->isScalarType() &&
2084 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002085 return Diag(castExpr->getLocStart(),
2086 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002087 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002088 } else if (castExpr->getType()->isVectorType()) {
2089 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2090 return true;
2091 } else if (castType->isVectorType()) {
2092 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2093 return true;
2094 }
2095 return false;
2096}
2097
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002098bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002099 assert(VectorTy->isVectorType() && "Not a vector type!");
2100
2101 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002102 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002103 return Diag(R.getBegin(),
2104 Ty->isVectorType() ?
2105 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002106 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002107 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002108 } else
2109 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002110 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002111 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002112
2113 return false;
2114}
2115
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002116Action::OwningExprResult
2117Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2118 SourceLocation RParenLoc, ExprArg Op) {
2119 assert((Ty != 0) && (Op.get() != 0) &&
2120 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002121
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002122 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002123 QualType castType = QualType::getFromOpaquePtr(Ty);
2124
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002125 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002126 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002127 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002128 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002129}
2130
Chris Lattner98a425c2007-11-26 01:40:58 +00002131/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2132/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00002133inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
2134 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
2135 UsualUnaryConversions(cond);
2136 UsualUnaryConversions(lex);
2137 UsualUnaryConversions(rex);
2138 QualType condT = cond->getType();
2139 QualType lexT = lex->getType();
2140 QualType rexT = rex->getType();
2141
2142 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002143 if (!cond->isTypeDependent()) {
2144 if (!condT->isScalarType()) { // C99 6.5.15p2
2145 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
2146 return QualType();
2147 }
Chris Lattner4b009652007-07-25 00:24:17 +00002148 }
Chris Lattner992ae932008-01-06 22:42:25 +00002149
2150 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002151 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
2152 return Context.DependentTy;
2153
Chris Lattner992ae932008-01-06 22:42:25 +00002154 // If both operands have arithmetic type, do the usual arithmetic conversions
2155 // to find a common type: C99 6.5.15p3,5.
2156 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002157 UsualArithmeticConversions(lex, rex);
2158 return lex->getType();
2159 }
Chris Lattner992ae932008-01-06 22:42:25 +00002160
2161 // If both operands are the same structure or union type, the result is that
2162 // type.
Chris Lattner71225142007-07-31 21:27:01 +00002163 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00002164 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002165 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00002166 // "If both the operands have structure or union type, the result has
2167 // that type." This implies that CV qualifiers are dropped.
2168 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002169 }
Chris Lattner992ae932008-01-06 22:42:25 +00002170
2171 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002172 // The following || allows only one side to be void (a GCC-ism).
2173 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00002174 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002175 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2176 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00002177 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002178 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2179 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00002180 ImpCastExprToType(lex, Context.VoidTy);
2181 ImpCastExprToType(rex, Context.VoidTy);
2182 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002183 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002184 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2185 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002186 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2187 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002188 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002189 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002190 return lexT;
2191 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002192 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2193 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002194 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002195 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002196 return rexT;
2197 }
Chris Lattner0ac51632008-01-06 22:50:31 +00002198 // Handle the case where both operands are pointers before we handle null
2199 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00002200 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2201 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2202 // get the "pointed to" types
2203 QualType lhptee = LHSPT->getPointeeType();
2204 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002205
Chris Lattner71225142007-07-31 21:27:01 +00002206 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2207 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002208 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002209 // Figure out necessary qualifiers (C99 6.5.15p6)
2210 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002211 QualType destType = Context.getPointerType(destPointee);
2212 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2213 ImpCastExprToType(rex, destType); // promote to void*
2214 return destType;
2215 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002216 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002217 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002218 QualType destType = Context.getPointerType(destPointee);
2219 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2220 ImpCastExprToType(rex, destType); // promote to void*
2221 return destType;
2222 }
Chris Lattner4b009652007-07-25 00:24:17 +00002223
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002224 QualType compositeType = lexT;
2225
2226 // If either type is an Objective-C object type then check
2227 // compatibility according to Objective-C.
2228 if (Context.isObjCObjectPointerType(lexT) ||
2229 Context.isObjCObjectPointerType(rexT)) {
2230 // If both operands are interfaces and either operand can be
2231 // assigned to the other, use that type as the composite
2232 // type. This allows
2233 // xxx ? (A*) a : (B*) b
2234 // where B is a subclass of A.
2235 //
2236 // Additionally, as for assignment, if either type is 'id'
2237 // allow silent coercion. Finally, if the types are
2238 // incompatible then make sure to use 'id' as the composite
2239 // type so the result is acceptable for sending messages to.
2240
2241 // FIXME: This code should not be localized to here. Also this
2242 // should use a compatible check instead of abusing the
2243 // canAssignObjCInterfaces code.
2244 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2245 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2246 if (LHSIface && RHSIface &&
2247 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2248 compositeType = lexT;
2249 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002250 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002251 compositeType = rexT;
2252 } else if (Context.isObjCIdType(lhptee) ||
2253 Context.isObjCIdType(rhptee)) {
2254 // FIXME: This code looks wrong, because isObjCIdType checks
2255 // the struct but getObjCIdType returns the pointer to
2256 // struct. This is horrible and should be fixed.
2257 compositeType = Context.getObjCIdType();
2258 } else {
2259 QualType incompatTy = Context.getObjCIdType();
2260 ImpCastExprToType(lex, incompatTy);
2261 ImpCastExprToType(rex, incompatTy);
2262 return incompatTy;
2263 }
2264 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2265 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002266 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002267 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002268 // In this situation, we assume void* type. No especially good
2269 // reason, but this is what gcc does, and we do have to pick
2270 // to get a consistent AST.
2271 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002272 ImpCastExprToType(lex, incompatTy);
2273 ImpCastExprToType(rex, incompatTy);
2274 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002275 }
2276 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002277 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2278 // differently qualified versions of compatible types, the result type is
2279 // a pointer to an appropriately qualified version of the *composite*
2280 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002281 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002282 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00002283 ImpCastExprToType(lex, compositeType);
2284 ImpCastExprToType(rex, compositeType);
2285 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002286 }
Chris Lattner4b009652007-07-25 00:24:17 +00002287 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002288 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2289 // evaluates to "struct objc_object *" (and is handled above when comparing
2290 // id with statically typed objects).
2291 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2292 // GCC allows qualified id and any Objective-C type to devolve to
2293 // id. Currently localizing to here until clear this should be
2294 // part of ObjCQualifiedIdTypesAreCompatible.
2295 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2296 (lexT->isObjCQualifiedIdType() &&
2297 Context.isObjCObjectPointerType(rexT)) ||
2298 (rexT->isObjCQualifiedIdType() &&
2299 Context.isObjCObjectPointerType(lexT))) {
2300 // FIXME: This is not the correct composite type. This only
2301 // happens to work because id can more or less be used anywhere,
2302 // however this may change the type of method sends.
2303 // FIXME: gcc adds some type-checking of the arguments and emits
2304 // (confusing) incompatible comparison warnings in some
2305 // cases. Investigate.
2306 QualType compositeType = Context.getObjCIdType();
2307 ImpCastExprToType(lex, compositeType);
2308 ImpCastExprToType(rex, compositeType);
2309 return compositeType;
2310 }
2311 }
2312
Steve Naroff3eac7692008-09-10 19:17:48 +00002313 // Selection between block pointer types is ok as long as they are the same.
2314 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2315 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2316 return lexT;
2317
Chris Lattner992ae932008-01-06 22:42:25 +00002318 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00002319 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002320 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002321 return QualType();
2322}
2323
Steve Naroff87d58b42007-09-16 03:34:24 +00002324/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002325/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002326Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2327 SourceLocation ColonLoc,
2328 ExprArg Cond, ExprArg LHS,
2329 ExprArg RHS) {
2330 Expr *CondExpr = (Expr *) Cond.get();
2331 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002332
2333 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2334 // was the condition.
2335 bool isLHSNull = LHSExpr == 0;
2336 if (isLHSNull)
2337 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002338
2339 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002340 RHSExpr, QuestionLoc);
2341 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002342 return ExprError();
2343
2344 Cond.release();
2345 LHS.release();
2346 RHS.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002347 return Owned(new (Context) ConditionalOperator(CondExpr,
2348 isLHSNull ? 0 : LHSExpr,
2349 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002350}
2351
Chris Lattner4b009652007-07-25 00:24:17 +00002352
2353// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2354// being closely modeled after the C99 spec:-). The odd characteristic of this
2355// routine is it effectively iqnores the qualifiers on the top level pointee.
2356// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2357// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00002358Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002359Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2360 QualType lhptee, rhptee;
2361
2362 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002363 lhptee = lhsType->getAsPointerType()->getPointeeType();
2364 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002365
2366 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002367 lhptee = Context.getCanonicalType(lhptee);
2368 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002369
Chris Lattner005ed752008-01-04 18:04:52 +00002370 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002371
2372 // C99 6.5.16.1p1: This following citation is common to constraints
2373 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2374 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00002375 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002376 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002377 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002378
2379 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2380 // incomplete type and the other is a pointer to a qualified or unqualified
2381 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002382 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002383 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002384 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002385
2386 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002387 assert(rhptee->isFunctionType());
2388 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002389 }
2390
2391 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002392 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002393 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002394
2395 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002396 assert(lhptee->isFunctionType());
2397 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002398 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002399
2400 // Check for ObjC interfaces
2401 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2402 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2403 if (LHSIface && RHSIface &&
2404 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2405 return ConvTy;
2406
2407 // ID acts sort of like void* for ObjC interfaces
2408 if (LHSIface && Context.isObjCIdType(rhptee))
2409 return ConvTy;
2410 if (RHSIface && Context.isObjCIdType(lhptee))
2411 return ConvTy;
2412
Chris Lattner4b009652007-07-25 00:24:17 +00002413 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2414 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002415 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2416 rhptee.getUnqualifiedType()))
2417 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002418 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002419}
2420
Steve Naroff3454b6c2008-09-04 15:10:53 +00002421/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2422/// block pointer types are compatible or whether a block and normal pointer
2423/// are compatible. It is more restrict than comparing two function pointer
2424// types.
2425Sema::AssignConvertType
2426Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2427 QualType rhsType) {
2428 QualType lhptee, rhptee;
2429
2430 // get the "pointed to" type (ignoring qualifiers at the top level)
2431 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2432 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2433
2434 // make sure we operate on the canonical type
2435 lhptee = Context.getCanonicalType(lhptee);
2436 rhptee = Context.getCanonicalType(rhptee);
2437
2438 AssignConvertType ConvTy = Compatible;
2439
2440 // For blocks we enforce that qualifiers are identical.
2441 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2442 ConvTy = CompatiblePointerDiscardsQualifiers;
2443
2444 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2445 return IncompatibleBlockPointer;
2446 return ConvTy;
2447}
2448
Chris Lattner4b009652007-07-25 00:24:17 +00002449/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2450/// has code to accommodate several GCC extensions when type checking
2451/// pointers. Here are some objectionable examples that GCC considers warnings:
2452///
2453/// int a, *pint;
2454/// short *pshort;
2455/// struct foo *pfoo;
2456///
2457/// pint = pshort; // warning: assignment from incompatible pointer type
2458/// a = pint; // warning: assignment makes integer from pointer without a cast
2459/// pint = a; // warning: assignment makes pointer from integer without a cast
2460/// pint = pfoo; // warning: assignment from incompatible pointer type
2461///
2462/// As a result, the code for dealing with pointers is more complex than the
2463/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002464///
Chris Lattner005ed752008-01-04 18:04:52 +00002465Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002466Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002467 // Get canonical types. We're not formatting these types, just comparing
2468 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002469 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2470 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002471
2472 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002473 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002474
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002475 // If the left-hand side is a reference type, then we are in a
2476 // (rare!) case where we've allowed the use of references in C,
2477 // e.g., as a parameter type in a built-in function. In this case,
2478 // just make sure that the type referenced is compatible with the
2479 // right-hand side type. The caller is responsible for adjusting
2480 // lhsType so that the resulting expression does not have reference
2481 // type.
2482 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2483 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002484 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002485 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002486 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002487
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002488 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2489 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002490 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002491 // Relax integer conversions like we do for pointers below.
2492 if (rhsType->isIntegerType())
2493 return IntToPointer;
2494 if (lhsType->isIntegerType())
2495 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002496 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002497 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002498
Nate Begemanc5f0f652008-07-14 18:02:46 +00002499 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002500 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002501 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2502 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002503 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002504
Nate Begemanc5f0f652008-07-14 18:02:46 +00002505 // If we are allowing lax vector conversions, and LHS and RHS are both
2506 // vectors, the total size only needs to be the same. This is a bitcast;
2507 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002508 if (getLangOptions().LaxVectorConversions &&
2509 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002510 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002511 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002512 }
2513 return Incompatible;
2514 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002515
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002516 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002517 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002518
Chris Lattner390564e2008-04-07 06:49:41 +00002519 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002520 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002521 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002522
Chris Lattner390564e2008-04-07 06:49:41 +00002523 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002524 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002525
Steve Naroffa982c712008-09-29 18:10:17 +00002526 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002527 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002528 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002529
2530 // Treat block pointers as objects.
2531 if (getLangOptions().ObjC1 &&
2532 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2533 return Compatible;
2534 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002535 return Incompatible;
2536 }
2537
2538 if (isa<BlockPointerType>(lhsType)) {
2539 if (rhsType->isIntegerType())
2540 return IntToPointer;
2541
Steve Naroffa982c712008-09-29 18:10:17 +00002542 // Treat block pointers as objects.
2543 if (getLangOptions().ObjC1 &&
2544 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2545 return Compatible;
2546
Steve Naroff3454b6c2008-09-04 15:10:53 +00002547 if (rhsType->isBlockPointerType())
2548 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2549
2550 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2551 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002552 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002553 }
Chris Lattner1853da22008-01-04 23:18:45 +00002554 return Incompatible;
2555 }
2556
Chris Lattner390564e2008-04-07 06:49:41 +00002557 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002558 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002559 if (lhsType == Context.BoolTy)
2560 return Compatible;
2561
2562 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002563 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002564
Chris Lattner390564e2008-04-07 06:49:41 +00002565 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002566 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002567
2568 if (isa<BlockPointerType>(lhsType) &&
2569 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002570 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002571 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002572 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002573
Chris Lattner1853da22008-01-04 23:18:45 +00002574 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002575 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002576 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002577 }
2578 return Incompatible;
2579}
2580
Chris Lattner005ed752008-01-04 18:04:52 +00002581Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002582Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002583 if (getLangOptions().CPlusPlus) {
2584 if (!lhsType->isRecordType()) {
2585 // C++ 5.17p3: If the left operand is not of class type, the
2586 // expression is implicitly converted (C++ 4) to the
2587 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002588 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2589 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002590 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002591 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002592 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002593 }
2594
2595 // FIXME: Currently, we fall through and treat C++ classes like C
2596 // structures.
2597 }
2598
Steve Naroffcdee22d2007-11-27 17:58:44 +00002599 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2600 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002601 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2602 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002603 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002604 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002605 return Compatible;
2606 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002607
2608 // We don't allow conversion of non-null-pointer constants to integers.
2609 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2610 return IntToBlockPointer;
2611
Chris Lattner5f505bf2007-10-16 02:55:40 +00002612 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002613 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002614 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002615 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002616 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002617 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002618 if (!lhsType->isReferenceType())
2619 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002620
Chris Lattner005ed752008-01-04 18:04:52 +00002621 Sema::AssignConvertType result =
2622 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002623
2624 // C99 6.5.16.1p2: The value of the right operand is converted to the
2625 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002626 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2627 // so that we can use references in built-in functions even in C.
2628 // The getNonReferenceType() call makes sure that the resulting expression
2629 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002630 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002631 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002632 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002633}
2634
Chris Lattner005ed752008-01-04 18:04:52 +00002635Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002636Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2637 return CheckAssignmentConstraints(lhsType, rhsType);
2638}
2639
Chris Lattner1eafdea2008-11-18 01:30:42 +00002640QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002641 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002642 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002643 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002644 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002645}
2646
Chris Lattner1eafdea2008-11-18 01:30:42 +00002647inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002648 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002649 // For conversion purposes, we ignore any qualifiers.
2650 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002651 QualType lhsType =
2652 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2653 QualType rhsType =
2654 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002655
Nate Begemanc5f0f652008-07-14 18:02:46 +00002656 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002657 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002658 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002659
Nate Begemanc5f0f652008-07-14 18:02:46 +00002660 // Handle the case of a vector & extvector type of the same size and element
2661 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00002662 if (getLangOptions().LaxVectorConversions) {
2663 // FIXME: Should we warn here?
2664 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002665 if (const VectorType *RV = rhsType->getAsVectorType())
2666 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00002667 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002668 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00002669 }
2670 }
2671 }
2672
Nate Begemanc5f0f652008-07-14 18:02:46 +00002673 // If the lhs is an extended vector and the rhs is a scalar of the same type
2674 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002675 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002676 QualType eltType = V->getElementType();
2677
2678 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2679 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2680 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002681 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002682 return lhsType;
2683 }
2684 }
2685
Nate Begemanc5f0f652008-07-14 18:02:46 +00002686 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002687 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002688 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002689 QualType eltType = V->getElementType();
2690
2691 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2692 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2693 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002694 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002695 return rhsType;
2696 }
2697 }
2698
Chris Lattner4b009652007-07-25 00:24:17 +00002699 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002700 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002701 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002702 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002703 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00002704}
2705
2706inline QualType Sema::CheckPointerToMemberOperands(
2707 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
2708{
2709 const char *OpSpelling = isIndirect ? "->*" : ".*";
2710 // C++ 5.5p2
2711 // The binary operator .* [p3: ->*] binds its second operand, which shall
2712 // be of type "pointer to member of T" (where T is a completely-defined
2713 // class type) [...]
2714 QualType RType = rex->getType();
2715 const MemberPointerType *MemPtr = RType->getAsMemberPointerType();
2716 if (!MemPtr || MemPtr->getClass()->isIncompleteType()) {
2717 Diag(Loc, diag::err_bad_memptr_rhs)
2718 << OpSpelling << RType << rex->getSourceRange();
2719 return QualType();
2720 }
2721 QualType Class(MemPtr->getClass(), 0);
2722
2723 // C++ 5.5p2
2724 // [...] to its first operand, which shall be of class T or of a class of
2725 // which T is an unambiguous and accessible base class. [p3: a pointer to
2726 // such a class]
2727 QualType LType = lex->getType();
2728 if (isIndirect) {
2729 if (const PointerType *Ptr = LType->getAsPointerType())
2730 LType = Ptr->getPointeeType().getNonReferenceType();
2731 else {
2732 Diag(Loc, diag::err_bad_memptr_lhs)
Sebastian Redl34e58bd2009-02-07 00:41:42 +00002733 << OpSpelling << 1 << LType << lex->getSourceRange();
Sebastian Redl95216a62009-02-07 00:15:38 +00002734 return QualType();
2735 }
2736 }
2737
2738 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
2739 Context.getCanonicalType(LType).getUnqualifiedType()) {
2740 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
2741 /*DetectVirtual=*/false);
2742 // FIXME: Would it be useful to print full ambiguity paths,
2743 // or is that overkill?
2744 if (!IsDerivedFrom(LType, Class, Paths) ||
2745 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
Sebastian Redl34e58bd2009-02-07 00:41:42 +00002746 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Sebastian Redl95216a62009-02-07 00:15:38 +00002747 << (int)isIndirect << lex->getType() << lex->getSourceRange();
2748 return QualType();
2749 }
2750 }
2751
2752 // C++ 5.5p2
2753 // The result is an object or a function of the type specified by the
2754 // second operand.
2755 // The cv qualifiers are the union of those in the pointer and the left side,
2756 // in accordance with 5.5p5 and 5.2.5.
2757 // FIXME: This returns a dereferenced member function pointer as a normal
2758 // function type. However, the only operation valid on such functions is
2759 // calling them. There's also a GCC extension to get a function pointer to
2760 // the thing, which is another complication, because this type - unlike the
2761 // type that is the result of this expression - takes the class as the first
2762 // argument.
2763 // We probably need a "MemberFunctionClosureType" or something like that.
2764 QualType Result = MemPtr->getPointeeType();
2765 if (LType.isConstQualified())
2766 Result.addConst();
2767 if (LType.isVolatileQualified())
2768 Result.addVolatile();
2769 return Result;
2770}
Chris Lattner4b009652007-07-25 00:24:17 +00002771
2772inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002773 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002774{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002775 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002776 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002777
Steve Naroff8f708362007-08-24 19:07:16 +00002778 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002779
Chris Lattner4b009652007-07-25 00:24:17 +00002780 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002781 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002782 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002783}
2784
2785inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002786 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002787{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002788 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2789 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2790 return CheckVectorOperands(Loc, lex, rex);
2791 return InvalidOperands(Loc, lex, rex);
2792 }
Chris Lattner4b009652007-07-25 00:24:17 +00002793
Steve Naroff8f708362007-08-24 19:07:16 +00002794 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002795
Chris Lattner4b009652007-07-25 00:24:17 +00002796 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002797 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002798 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002799}
2800
2801inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002802 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002803{
2804 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002805 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002806
Steve Naroff8f708362007-08-24 19:07:16 +00002807 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002808
Chris Lattner4b009652007-07-25 00:24:17 +00002809 // handle the common case first (both operands are arithmetic).
2810 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002811 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002812
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002813 // Put any potential pointer into PExp
2814 Expr* PExp = lex, *IExp = rex;
2815 if (IExp->getType()->isPointerType())
2816 std::swap(PExp, IExp);
2817
2818 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2819 if (IExp->getType()->isIntegerType()) {
2820 // Check for arithmetic on pointers to incomplete types
2821 if (!PTy->getPointeeType()->isObjectType()) {
2822 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002823 if (getLangOptions().CPlusPlus) {
2824 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2825 << lex->getSourceRange() << rex->getSourceRange();
2826 return QualType();
2827 }
2828
2829 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00002830 Diag(Loc, diag::ext_gnu_void_ptr)
2831 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002832 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002833 if (getLangOptions().CPlusPlus) {
2834 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2835 << lex->getType() << lex->getSourceRange();
2836 return QualType();
2837 }
2838
2839 // GNU extension: arithmetic on pointer to function
2840 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002841 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002842 } else {
2843 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2844 diag::err_typecheck_arithmetic_incomplete_type,
2845 lex->getSourceRange(), SourceRange(),
2846 lex->getType());
2847 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002848 }
2849 }
2850 return PExp->getType();
2851 }
2852 }
2853
Chris Lattner1eafdea2008-11-18 01:30:42 +00002854 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002855}
2856
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002857// C99 6.5.6
2858QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002859 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002860 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002861 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002862
Steve Naroff8f708362007-08-24 19:07:16 +00002863 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002864
Chris Lattnerf6da2912007-12-09 21:53:25 +00002865 // Enforce type constraints: C99 6.5.6p3.
2866
2867 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002868 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002869 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002870
2871 // Either ptr - int or ptr - ptr.
2872 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002873 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002874
Chris Lattnerf6da2912007-12-09 21:53:25 +00002875 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002876 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002877 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002878 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002879 Diag(Loc, diag::ext_gnu_void_ptr)
2880 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00002881 } else if (lpointee->isFunctionType()) {
2882 if (getLangOptions().CPlusPlus) {
2883 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2884 << lex->getType() << lex->getSourceRange();
2885 return QualType();
2886 }
2887
2888 // GNU extension: arithmetic on pointer to function
2889 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2890 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002891 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002892 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002893 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002894 return QualType();
2895 }
2896 }
2897
2898 // The result type of a pointer-int computation is the pointer type.
2899 if (rex->getType()->isIntegerType())
2900 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002901
Chris Lattnerf6da2912007-12-09 21:53:25 +00002902 // Handle pointer-pointer subtractions.
2903 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002904 QualType rpointee = RHSPTy->getPointeeType();
2905
Chris Lattnerf6da2912007-12-09 21:53:25 +00002906 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002907 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002908 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002909 if (rpointee->isVoidType()) {
2910 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002911 Diag(Loc, diag::ext_gnu_void_ptr)
2912 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00002913 } else if (rpointee->isFunctionType()) {
2914 if (getLangOptions().CPlusPlus) {
2915 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2916 << rex->getType() << rex->getSourceRange();
2917 return QualType();
2918 }
2919
2920 // GNU extension: arithmetic on pointer to function
2921 if (!lpointee->isFunctionType())
2922 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2923 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002924 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002925 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002926 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002927 return QualType();
2928 }
2929 }
2930
2931 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002932 if (!Context.typesAreCompatible(
2933 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2934 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002935 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002936 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002937 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002938 return QualType();
2939 }
2940
2941 return Context.getPointerDiffType();
2942 }
2943 }
2944
Chris Lattner1eafdea2008-11-18 01:30:42 +00002945 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002946}
2947
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002948// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002949QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002950 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002951 // C99 6.5.7p2: Each of the operands shall have integer type.
2952 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002953 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002954
Chris Lattner2c8bff72007-12-12 05:47:28 +00002955 // Shifts don't perform usual arithmetic conversions, they just do integer
2956 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002957 if (!isCompAssign)
2958 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002959 UsualUnaryConversions(rex);
2960
2961 // "The type of the result is that of the promoted left operand."
2962 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002963}
2964
Eli Friedman0d9549b2008-08-22 00:56:42 +00002965static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2966 ASTContext& Context) {
2967 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2968 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2969 // ID acts sort of like void* for ObjC interfaces
2970 if (LHSIface && Context.isObjCIdType(RHS))
2971 return true;
2972 if (RHSIface && Context.isObjCIdType(LHS))
2973 return true;
2974 if (!LHSIface || !RHSIface)
2975 return false;
2976 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2977 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2978}
2979
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002980// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002981QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002982 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002983 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002984 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002985
Chris Lattner254f3bc2007-08-26 01:18:55 +00002986 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002987 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2988 UsualArithmeticConversions(lex, rex);
2989 else {
2990 UsualUnaryConversions(lex);
2991 UsualUnaryConversions(rex);
2992 }
Chris Lattner4b009652007-07-25 00:24:17 +00002993 QualType lType = lex->getType();
2994 QualType rType = rex->getType();
2995
Ted Kremenek486509e2007-10-29 17:13:39 +00002996 // For non-floating point types, check for self-comparisons of the form
2997 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2998 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002999 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00003000 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3001 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003002 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003003 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003004 }
3005
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003006 // The result of comparisons is 'bool' in C++, 'int' in C.
3007 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
3008
Chris Lattner254f3bc2007-08-26 01:18:55 +00003009 if (isRelational) {
3010 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003011 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003012 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00003013 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00003014 if (lType->isFloatingType()) {
3015 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003016 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00003017 }
3018
Chris Lattner254f3bc2007-08-26 01:18:55 +00003019 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003020 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003021 }
Chris Lattner4b009652007-07-25 00:24:17 +00003022
Chris Lattner22be8422007-08-26 01:10:14 +00003023 bool LHSIsNull = lex->isNullPointerConstant(Context);
3024 bool RHSIsNull = rex->isNullPointerConstant(Context);
3025
Chris Lattner254f3bc2007-08-26 01:18:55 +00003026 // All of the following pointer related warnings are GCC extensions, except
3027 // when handling null pointer constants. One day, we can consider making them
3028 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00003029 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003030 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003031 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00003032 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003033 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00003034
Steve Naroff3b435622007-11-13 14:57:38 +00003035 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003036 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3037 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00003038 RCanPointeeTy.getUnqualifiedType()) &&
3039 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003040 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003041 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003042 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003043 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003044 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003045 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003046 // Handle block pointer types.
3047 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3048 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3049 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
3050
3051 if (!LHSIsNull && !RHSIsNull &&
3052 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003053 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003054 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003055 }
3056 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003057 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003058 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003059 // Allow block pointers to be compared with null pointer constants.
3060 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3061 (lType->isPointerType() && rType->isBlockPointerType())) {
3062 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003063 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003064 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003065 }
3066 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003067 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003068 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003069
Steve Naroff936c4362008-06-03 14:04:54 +00003070 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003071 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003072 const PointerType *LPT = lType->getAsPointerType();
3073 const PointerType *RPT = rType->getAsPointerType();
3074 bool LPtrToVoid = LPT ?
3075 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
3076 bool RPtrToVoid = RPT ?
3077 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
3078
3079 if (!LPtrToVoid && !RPtrToVoid &&
3080 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003081 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003082 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003083 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003084 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003085 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003086 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003087 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003088 }
Steve Naroff936c4362008-06-03 14:04:54 +00003089 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3090 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003091 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003092 } else {
3093 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003094 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003095 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003096 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003097 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003098 }
Steve Naroff936c4362008-06-03 14:04:54 +00003099 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003100 }
Steve Naroff936c4362008-06-03 14:04:54 +00003101 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
3102 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003103 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003104 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003105 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003106 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003107 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003108 }
Steve Naroff936c4362008-06-03 14:04:54 +00003109 if (lType->isIntegerType() &&
3110 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003111 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003112 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003113 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003114 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003115 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003116 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003117 // Handle block pointers.
3118 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3119 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003120 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003121 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003122 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003123 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003124 }
3125 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3126 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003127 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003128 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003129 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003130 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003131 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003132 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003133}
3134
Nate Begemanc5f0f652008-07-14 18:02:46 +00003135/// CheckVectorCompareOperands - vector comparisons are a clang extension that
3136/// operates on extended vector types. Instead of producing an IntTy result,
3137/// like a scalar comparison, a vector comparison produces a vector of integer
3138/// types.
3139QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003140 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003141 bool isRelational) {
3142 // Check to make sure we're operating on vectors of the same type and width,
3143 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003144 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003145 if (vType.isNull())
3146 return vType;
3147
3148 QualType lType = lex->getType();
3149 QualType rType = rex->getType();
3150
3151 // For non-floating point types, check for self-comparisons of the form
3152 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3153 // often indicate logic errors in the program.
3154 if (!lType->isFloatingType()) {
3155 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3156 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3157 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003158 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003159 }
3160
3161 // Check for comparisons of floating point operands using != and ==.
3162 if (!isRelational && lType->isFloatingType()) {
3163 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003164 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003165 }
3166
3167 // Return the type for the comparison, which is the same as vector type for
3168 // integer vectors, or an integer type of identical size and number of
3169 // elements for floating point vectors.
3170 if (lType->isIntegerType())
3171 return lType;
3172
3173 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003174 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003175 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003176 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003177 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3178 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3179
3180 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3181 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003182 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3183}
3184
Chris Lattner4b009652007-07-25 00:24:17 +00003185inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00003186 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003187{
3188 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003189 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003190
Steve Naroff8f708362007-08-24 19:07:16 +00003191 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00003192
3193 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003194 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003195 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003196}
3197
3198inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00003199 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003200{
3201 UsualUnaryConversions(lex);
3202 UsualUnaryConversions(rex);
3203
Eli Friedmanbea3f842008-05-13 20:16:47 +00003204 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003205 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003206 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003207}
3208
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003209/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3210/// is a read-only property; return true if so. A readonly property expression
3211/// depends on various declarations and thus must be treated specially.
3212///
3213static bool IsReadonlyProperty(Expr *E, Sema &S)
3214{
3215 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3216 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3217 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3218 QualType BaseType = PropExpr->getBase()->getType();
3219 if (const PointerType *PTy = BaseType->getAsPointerType())
3220 if (const ObjCInterfaceType *IFTy =
3221 PTy->getPointeeType()->getAsObjCInterfaceType())
3222 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3223 if (S.isPropertyReadonly(PDecl, IFace))
3224 return true;
3225 }
3226 }
3227 return false;
3228}
3229
Chris Lattner4c2642c2008-11-18 01:22:49 +00003230/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3231/// emit an error and return true. If so, return false.
3232static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003233 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3234 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3235 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003236 if (IsLV == Expr::MLV_Valid)
3237 return false;
3238
3239 unsigned Diag = 0;
3240 bool NeedType = false;
3241 switch (IsLV) { // C99 6.5.16p2
3242 default: assert(0 && "Unknown result from isModifiableLvalue!");
3243 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00003244 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003245 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3246 NeedType = true;
3247 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003248 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003249 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3250 NeedType = true;
3251 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003252 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003253 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3254 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003255 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003256 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3257 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003258 case Expr::MLV_IncompleteType:
3259 case Expr::MLV_IncompleteVoidType:
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003260 return S.DiagnoseIncompleteType(Loc, E->getType(),
3261 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3262 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003263 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003264 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3265 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003266 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003267 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3268 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003269 case Expr::MLV_ReadonlyProperty:
3270 Diag = diag::error_readonly_property_assignment;
3271 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003272 case Expr::MLV_NoSetterProperty:
3273 Diag = diag::error_nosetter_property_assignment;
3274 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003275 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003276
Chris Lattner4c2642c2008-11-18 01:22:49 +00003277 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003278 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003279 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003280 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003281 return true;
3282}
3283
3284
3285
3286// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003287QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3288 SourceLocation Loc,
3289 QualType CompoundType) {
3290 // Verify that LHS is a modifiable lvalue, and emit error if not.
3291 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003292 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003293
3294 QualType LHSType = LHS->getType();
3295 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003296
Chris Lattner005ed752008-01-04 18:04:52 +00003297 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003298 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003299 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003300 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003301 // Special case of NSObject attributes on c-style pointer types.
3302 if (ConvTy == IncompatiblePointer &&
3303 ((Context.isObjCNSObjectType(LHSType) &&
3304 Context.isObjCObjectPointerType(RHSType)) ||
3305 (Context.isObjCNSObjectType(RHSType) &&
3306 Context.isObjCObjectPointerType(LHSType))))
3307 ConvTy = Compatible;
3308
Chris Lattner34c85082008-08-21 18:04:13 +00003309 // If the RHS is a unary plus or minus, check to see if they = and + are
3310 // right next to each other. If so, the user may have typo'd "x =+ 4"
3311 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003312 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003313 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3314 RHSCheck = ICE->getSubExpr();
3315 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3316 if ((UO->getOpcode() == UnaryOperator::Plus ||
3317 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003318 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003319 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003320 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003321 Diag(Loc, diag::warn_not_compound_assign)
3322 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3323 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003324 }
3325 } else {
3326 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003327 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003328 }
Chris Lattner005ed752008-01-04 18:04:52 +00003329
Chris Lattner1eafdea2008-11-18 01:30:42 +00003330 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3331 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003332 return QualType();
3333
Chris Lattner4b009652007-07-25 00:24:17 +00003334 // C99 6.5.16p3: The type of an assignment expression is the type of the
3335 // left operand unless the left operand has qualified type, in which case
3336 // it is the unqualified version of the type of the left operand.
3337 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3338 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003339 // C++ 5.17p1: the type of the assignment expression is that of its left
3340 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003341 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003342}
3343
Chris Lattner1eafdea2008-11-18 01:30:42 +00003344// C99 6.5.17
3345QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3346 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00003347
3348 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003349 DefaultFunctionArrayConversion(RHS);
3350 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003351}
3352
3353/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3354/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003355QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3356 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003357 QualType ResType = Op->getType();
3358 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003359
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003360 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3361 // Decrement of bool is not allowed.
3362 if (!isInc) {
3363 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3364 return QualType();
3365 }
3366 // Increment of bool sets it to true, but is deprecated.
3367 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3368 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003369 // OK!
3370 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3371 // C99 6.5.2.4p2, 6.5.6p2
3372 if (PT->getPointeeType()->isObjectType()) {
3373 // Pointer to object is ok!
3374 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003375 if (getLangOptions().CPlusPlus) {
3376 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3377 << Op->getSourceRange();
3378 return QualType();
3379 }
3380
3381 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003382 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003383 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003384 if (getLangOptions().CPlusPlus) {
3385 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3386 << Op->getType() << Op->getSourceRange();
3387 return QualType();
3388 }
3389
3390 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003391 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003392 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003393 } else {
3394 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3395 diag::err_typecheck_arithmetic_incomplete_type,
3396 Op->getSourceRange(), SourceRange(),
3397 ResType);
3398 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003399 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003400 } else if (ResType->isComplexType()) {
3401 // C99 does not support ++/-- on complex types, we allow as an extension.
3402 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003403 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003404 } else {
3405 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003406 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003407 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003408 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00003409 // At this point, we know we have a real, complex or pointer type.
3410 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003411 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003412 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003413 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003414}
3415
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003416/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003417/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003418/// where the declaration is needed for type checking. We only need to
3419/// handle cases when the expression references a function designator
3420/// or is an lvalue. Here are some examples:
3421/// - &(x) => x
3422/// - &*****f => f for f a function designator.
3423/// - &s.xx => s
3424/// - &s.zz[1].yy -> s, if zz is an array
3425/// - *(x + 1) -> x, if x is an array
3426/// - &"123"[2] -> 0
3427/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003428static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003429 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003430 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003431 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003432 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003433 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003434 // Fields cannot be declared with a 'register' storage class.
3435 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003436 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003437 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003438 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003439 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003440 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003441
Douglas Gregord2baafd2008-10-21 16:13:35 +00003442 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003443 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003444 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003445 return 0;
3446 else
3447 return VD;
3448 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003449 case Stmt::UnaryOperatorClass: {
3450 UnaryOperator *UO = cast<UnaryOperator>(E);
3451
3452 switch(UO->getOpcode()) {
3453 case UnaryOperator::Deref: {
3454 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003455 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3456 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3457 if (!VD || VD->getType()->isPointerType())
3458 return 0;
3459 return VD;
3460 }
3461 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003462 }
3463 case UnaryOperator::Real:
3464 case UnaryOperator::Imag:
3465 case UnaryOperator::Extension:
3466 return getPrimaryDecl(UO->getSubExpr());
3467 default:
3468 return 0;
3469 }
3470 }
3471 case Stmt::BinaryOperatorClass: {
3472 BinaryOperator *BO = cast<BinaryOperator>(E);
3473
3474 // Handle cases involving pointer arithmetic. The result of an
3475 // Assign or AddAssign is not an lvalue so they can be ignored.
3476
3477 // (x + n) or (n + x) => x
3478 if (BO->getOpcode() == BinaryOperator::Add) {
3479 if (BO->getLHS()->getType()->isPointerType()) {
3480 return getPrimaryDecl(BO->getLHS());
3481 } else if (BO->getRHS()->getType()->isPointerType()) {
3482 return getPrimaryDecl(BO->getRHS());
3483 }
3484 }
3485
3486 return 0;
3487 }
Chris Lattner4b009652007-07-25 00:24:17 +00003488 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003489 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003490 case Stmt::ImplicitCastExprClass:
3491 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003492 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003493 default:
3494 return 0;
3495 }
3496}
3497
3498/// CheckAddressOfOperand - The operand of & must be either a function
3499/// designator or an lvalue designating an object. If it is an lvalue, the
3500/// object cannot be declared with storage class register or be a bit field.
3501/// Note: The usual conversions are *not* applied to the operand of the &
3502/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00003503/// In C++, the operand might be an overloaded function name, in which case
3504/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003505QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003506 if (op->isTypeDependent())
3507 return Context.DependentTy;
3508
Steve Naroff9c6c3592008-01-13 17:10:08 +00003509 if (getLangOptions().C99) {
3510 // Implement C99-only parts of addressof rules.
3511 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3512 if (uOp->getOpcode() == UnaryOperator::Deref)
3513 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3514 // (assuming the deref expression is valid).
3515 return uOp->getSubExpr()->getType();
3516 }
3517 // Technically, there should be a check for array subscript
3518 // expressions here, but the result of one is always an lvalue anyway.
3519 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003520 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003521 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003522
Chris Lattner4b009652007-07-25 00:24:17 +00003523 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003524 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3525 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003526 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3527 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003528 return QualType();
3529 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003530 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003531 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3532 if (Field->isBitField()) {
3533 Diag(OpLoc, diag::err_typecheck_address_of)
3534 << "bit-field" << op->getSourceRange();
3535 return QualType();
3536 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003537 }
3538 // Check for Apple extension for accessing vector components.
3539 } else if (isa<ArraySubscriptExpr>(op) &&
3540 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003541 Diag(OpLoc, diag::err_typecheck_address_of)
3542 << "vector" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003543 return QualType();
3544 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00003545 // We have an lvalue with a decl. Make sure the decl is not declared
3546 // with the register storage-class specifier.
3547 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3548 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003549 Diag(OpLoc, diag::err_typecheck_address_of)
3550 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003551 return QualType();
3552 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003553 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003554 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003555 } else if (isa<FieldDecl>(dcl)) {
3556 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00003557 // Could be a pointer to member, though, if there is an explicit
3558 // scope qualifier for the class.
3559 if (isa<QualifiedDeclRefExpr>(op)) {
3560 DeclContext *Ctx = dcl->getDeclContext();
3561 if (Ctx && Ctx->isRecord())
3562 return Context.getMemberPointerType(op->getType(),
3563 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3564 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003565 } else if (isa<FunctionDecl>(dcl)) {
3566 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00003567 // As above.
3568 if (isa<QualifiedDeclRefExpr>(op)) {
3569 DeclContext *Ctx = dcl->getDeclContext();
3570 if (Ctx && Ctx->isRecord())
3571 return Context.getMemberPointerType(op->getType(),
3572 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3573 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003574 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003575 else
Chris Lattner4b009652007-07-25 00:24:17 +00003576 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003577 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00003578
Chris Lattner4b009652007-07-25 00:24:17 +00003579 // If the operand has type "type", the result has type "pointer to type".
3580 return Context.getPointerType(op->getType());
3581}
3582
Chris Lattnerda5c0872008-11-23 09:13:29 +00003583QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3584 UsualUnaryConversions(Op);
3585 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003586
Chris Lattnerda5c0872008-11-23 09:13:29 +00003587 // Note that per both C89 and C99, this is always legal, even if ptype is an
3588 // incomplete type or void. It would be possible to warn about dereferencing
3589 // a void pointer, but it's completely well-defined, and such a warning is
3590 // unlikely to catch any mistakes.
3591 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003592 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00003593
Chris Lattner77d52da2008-11-20 06:06:08 +00003594 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003595 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003596 return QualType();
3597}
3598
3599static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3600 tok::TokenKind Kind) {
3601 BinaryOperator::Opcode Opc;
3602 switch (Kind) {
3603 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00003604 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3605 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003606 case tok::star: Opc = BinaryOperator::Mul; break;
3607 case tok::slash: Opc = BinaryOperator::Div; break;
3608 case tok::percent: Opc = BinaryOperator::Rem; break;
3609 case tok::plus: Opc = BinaryOperator::Add; break;
3610 case tok::minus: Opc = BinaryOperator::Sub; break;
3611 case tok::lessless: Opc = BinaryOperator::Shl; break;
3612 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3613 case tok::lessequal: Opc = BinaryOperator::LE; break;
3614 case tok::less: Opc = BinaryOperator::LT; break;
3615 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3616 case tok::greater: Opc = BinaryOperator::GT; break;
3617 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3618 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3619 case tok::amp: Opc = BinaryOperator::And; break;
3620 case tok::caret: Opc = BinaryOperator::Xor; break;
3621 case tok::pipe: Opc = BinaryOperator::Or; break;
3622 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3623 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3624 case tok::equal: Opc = BinaryOperator::Assign; break;
3625 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3626 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3627 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3628 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3629 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3630 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3631 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3632 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3633 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3634 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3635 case tok::comma: Opc = BinaryOperator::Comma; break;
3636 }
3637 return Opc;
3638}
3639
3640static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3641 tok::TokenKind Kind) {
3642 UnaryOperator::Opcode Opc;
3643 switch (Kind) {
3644 default: assert(0 && "Unknown unary op!");
3645 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3646 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3647 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3648 case tok::star: Opc = UnaryOperator::Deref; break;
3649 case tok::plus: Opc = UnaryOperator::Plus; break;
3650 case tok::minus: Opc = UnaryOperator::Minus; break;
3651 case tok::tilde: Opc = UnaryOperator::Not; break;
3652 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003653 case tok::kw___real: Opc = UnaryOperator::Real; break;
3654 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3655 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3656 }
3657 return Opc;
3658}
3659
Douglas Gregord7f915e2008-11-06 23:29:22 +00003660/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3661/// operator @p Opc at location @c TokLoc. This routine only supports
3662/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003663Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3664 unsigned Op,
3665 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003666 QualType ResultTy; // Result type of the binary operator.
3667 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3668 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3669
3670 switch (Opc) {
3671 default:
3672 assert(0 && "Unknown binary expr!");
3673 case BinaryOperator::Assign:
3674 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3675 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003676 case BinaryOperator::PtrMemD:
3677 case BinaryOperator::PtrMemI:
3678 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3679 Opc == BinaryOperator::PtrMemI);
3680 break;
3681 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003682 case BinaryOperator::Div:
3683 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3684 break;
3685 case BinaryOperator::Rem:
3686 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3687 break;
3688 case BinaryOperator::Add:
3689 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3690 break;
3691 case BinaryOperator::Sub:
3692 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3693 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003694 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003695 case BinaryOperator::Shr:
3696 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3697 break;
3698 case BinaryOperator::LE:
3699 case BinaryOperator::LT:
3700 case BinaryOperator::GE:
3701 case BinaryOperator::GT:
3702 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3703 break;
3704 case BinaryOperator::EQ:
3705 case BinaryOperator::NE:
3706 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3707 break;
3708 case BinaryOperator::And:
3709 case BinaryOperator::Xor:
3710 case BinaryOperator::Or:
3711 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3712 break;
3713 case BinaryOperator::LAnd:
3714 case BinaryOperator::LOr:
3715 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3716 break;
3717 case BinaryOperator::MulAssign:
3718 case BinaryOperator::DivAssign:
3719 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3720 if (!CompTy.isNull())
3721 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3722 break;
3723 case BinaryOperator::RemAssign:
3724 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3725 if (!CompTy.isNull())
3726 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3727 break;
3728 case BinaryOperator::AddAssign:
3729 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3730 if (!CompTy.isNull())
3731 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3732 break;
3733 case BinaryOperator::SubAssign:
3734 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3735 if (!CompTy.isNull())
3736 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3737 break;
3738 case BinaryOperator::ShlAssign:
3739 case BinaryOperator::ShrAssign:
3740 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3741 if (!CompTy.isNull())
3742 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3743 break;
3744 case BinaryOperator::AndAssign:
3745 case BinaryOperator::XorAssign:
3746 case BinaryOperator::OrAssign:
3747 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3748 if (!CompTy.isNull())
3749 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3750 break;
3751 case BinaryOperator::Comma:
3752 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3753 break;
3754 }
3755 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003756 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00003757 if (CompTy.isNull())
3758 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3759 else
3760 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Steve Naroff8b9a98d2009-01-20 21:06:31 +00003761 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003762}
3763
Chris Lattner4b009652007-07-25 00:24:17 +00003764// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003765Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3766 tok::TokenKind Kind,
3767 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003768 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003769 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003770
Steve Naroff87d58b42007-09-16 03:34:24 +00003771 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3772 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003773
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003774 // If either expression is type-dependent, just build the AST.
3775 // FIXME: We'll need to perform some caching of the result of name
3776 // lookup for operator+.
3777 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff774e4152009-01-21 00:14:39 +00003778 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3779 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003780 Context.DependentTy,
3781 Context.DependentTy, TokLoc));
Steve Naroff774e4152009-01-21 00:14:39 +00003782 else
Sebastian Redl95216a62009-02-07 00:15:38 +00003783 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc,
3784 Context.DependentTy, TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003785 }
3786
Sebastian Redl95216a62009-02-07 00:15:38 +00003787 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD &&
Douglas Gregord7f915e2008-11-06 23:29:22 +00003788 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3789 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003790 // If this is one of the assignment operators, we only perform
3791 // overload resolution if the left-hand side is a class or
3792 // enumeration type (C++ [expr.ass]p3).
3793 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3794 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3795 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3796 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003797
Douglas Gregord7f915e2008-11-06 23:29:22 +00003798 // Determine which overloaded operator we're dealing with.
3799 static const OverloadedOperatorKind OverOps[] = {
Sebastian Redl95216a62009-02-07 00:15:38 +00003800 // Overloading .* is not possible.
3801 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar,
Douglas Gregord7f915e2008-11-06 23:29:22 +00003802 OO_Star, OO_Slash, OO_Percent,
3803 OO_Plus, OO_Minus,
3804 OO_LessLess, OO_GreaterGreater,
3805 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3806 OO_EqualEqual, OO_ExclaimEqual,
3807 OO_Amp,
3808 OO_Caret,
3809 OO_Pipe,
3810 OO_AmpAmp,
3811 OO_PipePipe,
3812 OO_Equal, OO_StarEqual,
3813 OO_SlashEqual, OO_PercentEqual,
3814 OO_PlusEqual, OO_MinusEqual,
3815 OO_LessLessEqual, OO_GreaterGreaterEqual,
3816 OO_AmpEqual, OO_CaretEqual,
3817 OO_PipeEqual,
3818 OO_Comma
3819 };
3820 OverloadedOperatorKind OverOp = OverOps[Opc];
3821
Douglas Gregor5ed15042008-11-18 23:14:02 +00003822 // Add the appropriate overloaded operators (C++ [over.match.oper])
3823 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003824 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003825 Expr *Args[2] = { lhs, rhs };
Douglas Gregor48a87322009-02-04 16:44:47 +00003826 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3827 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003828
3829 // Perform overload resolution.
3830 OverloadCandidateSet::iterator Best;
3831 switch (BestViableFunction(CandidateSet, Best)) {
3832 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003833 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003834 FunctionDecl *FnDecl = Best->Function;
3835
Douglas Gregor70d26122008-11-12 17:17:38 +00003836 if (FnDecl) {
3837 // We matched an overloaded operator. Build a call to that
3838 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003839
Douglas Gregor70d26122008-11-12 17:17:38 +00003840 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003841 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3842 if (PerformObjectArgumentInitialization(lhs, Method) ||
3843 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3844 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003845 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003846 } else {
3847 // Convert the arguments.
3848 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3849 "passing") ||
3850 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3851 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003852 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003853 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003854
Douglas Gregor70d26122008-11-12 17:17:38 +00003855 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003856 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003857 = FnDecl->getType()->getAsFunctionType()->getResultType();
3858 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003859
Douglas Gregor70d26122008-11-12 17:17:38 +00003860 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003861 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3862 SourceLocation());
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003863 UsualUnaryConversions(FnExpr);
3864
Steve Naroff774e4152009-01-21 00:14:39 +00003865 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, Args, 2,
3866 ResultTy, TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003867 } else {
3868 // We matched a built-in operator. Convert the arguments, then
3869 // break out so that we will build the appropriate built-in
3870 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003871 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3872 Best->Conversions[0], "passing") ||
3873 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3874 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003875 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003876
3877 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003878 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003879 }
3880
3881 case OR_No_Viable_Function:
3882 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003883 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003884 break;
3885
3886 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003887 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3888 << BinaryOperator::getOpcodeStr(Opc)
3889 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003890 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003891 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003892 }
3893
Douglas Gregor70d26122008-11-12 17:17:38 +00003894 // Either we found no viable overloaded operator or we matched a
3895 // built-in operator. In either case, fall through to trying to
3896 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003897 }
3898
Douglas Gregord7f915e2008-11-06 23:29:22 +00003899 // Build a built-in binary operation.
3900 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003901}
3902
3903// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00003904Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3905 tok::TokenKind Op, ExprArg input) {
3906 // FIXME: Input is modified later, but smart pointer not reassigned.
3907 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00003908 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003909
3910 if (getLangOptions().CPlusPlus &&
3911 (Input->getType()->isRecordType()
3912 || Input->getType()->isEnumeralType())) {
3913 // Determine which overloaded operator we're dealing with.
3914 static const OverloadedOperatorKind OverOps[] = {
3915 OO_None, OO_None,
3916 OO_PlusPlus, OO_MinusMinus,
3917 OO_Amp, OO_Star,
3918 OO_Plus, OO_Minus,
3919 OO_Tilde, OO_Exclaim,
3920 OO_None, OO_None,
3921 OO_None,
3922 OO_None
3923 };
3924 OverloadedOperatorKind OverOp = OverOps[Opc];
3925
3926 // Add the appropriate overloaded operators (C++ [over.match.oper])
3927 // to the candidate set.
3928 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00003929 if (OverOp != OO_None &&
3930 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
3931 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003932
3933 // Perform overload resolution.
3934 OverloadCandidateSet::iterator Best;
3935 switch (BestViableFunction(CandidateSet, Best)) {
3936 case OR_Success: {
3937 // We found a built-in operator or an overloaded operator.
3938 FunctionDecl *FnDecl = Best->Function;
3939
3940 if (FnDecl) {
3941 // We matched an overloaded operator. Build a call to that
3942 // operator.
3943
3944 // Convert the arguments.
3945 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3946 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00003947 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003948 } else {
3949 // Convert the arguments.
3950 if (PerformCopyInitialization(Input,
3951 FnDecl->getParamDecl(0)->getType(),
3952 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003953 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003954 }
3955
3956 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00003957 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003958 = FnDecl->getType()->getAsFunctionType()->getResultType();
3959 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00003960
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003961 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003962 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3963 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003964 UsualUnaryConversions(FnExpr);
3965
Sebastian Redl8b769972009-01-19 00:08:26 +00003966 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00003967 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, &Input, 1,
3968 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003969 } else {
3970 // We matched a built-in operator. Convert the arguments, then
3971 // break out so that we will build the appropriate built-in
3972 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003973 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3974 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003975 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003976
3977 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00003978 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003979 }
3980
3981 case OR_No_Viable_Function:
3982 // No viable function; fall through to handling this as a
3983 // built-in operator, which will produce an error message for us.
3984 break;
3985
3986 case OR_Ambiguous:
3987 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3988 << UnaryOperator::getOpcodeStr(Opc)
3989 << Input->getSourceRange();
3990 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00003991 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003992 }
3993
3994 // Either we found no viable overloaded operator or we matched a
3995 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00003996 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003997 }
3998
Chris Lattner4b009652007-07-25 00:24:17 +00003999 QualType resultType;
4000 switch (Opc) {
4001 default:
4002 assert(0 && "Unimplemented unary expr!");
4003 case UnaryOperator::PreInc:
4004 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004005 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4006 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00004007 break;
4008 case UnaryOperator::AddrOf:
4009 resultType = CheckAddressOfOperand(Input, OpLoc);
4010 break;
4011 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00004012 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00004013 resultType = CheckIndirectionOperand(Input, OpLoc);
4014 break;
4015 case UnaryOperator::Plus:
4016 case UnaryOperator::Minus:
4017 UsualUnaryConversions(Input);
4018 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004019 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4020 break;
4021 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4022 resultType->isEnumeralType())
4023 break;
4024 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4025 Opc == UnaryOperator::Plus &&
4026 resultType->isPointerType())
4027 break;
4028
Sebastian Redl8b769972009-01-19 00:08:26 +00004029 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4030 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004031 case UnaryOperator::Not: // bitwise complement
4032 UsualUnaryConversions(Input);
4033 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00004034 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4035 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4036 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00004037 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004038 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004039 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00004040 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4041 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004042 break;
4043 case UnaryOperator::LNot: // logical negation
4044 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4045 DefaultFunctionArrayConversion(Input);
4046 resultType = Input->getType();
4047 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004048 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4049 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004050 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004051 // In C++, it's bool. C++ 5.3.1p8
4052 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004053 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004054 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004055 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00004056 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00004057 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004058 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004059 resultType = Input->getType();
4060 break;
4061 }
4062 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004063 return ExprError();
4064 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004065 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004066}
4067
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004068/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4069Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00004070 SourceLocation LabLoc,
4071 IdentifierInfo *LabelII) {
4072 // Look up the record for this label identifier.
4073 LabelStmt *&LabelDecl = LabelMap[LabelII];
4074
Daniel Dunbar879788d2008-08-04 16:51:22 +00004075 // If we haven't seen this label yet, create a forward reference. It
4076 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00004077 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004078 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00004079
4080 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff774e4152009-01-21 00:14:39 +00004081 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4082 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00004083}
4084
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004085Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00004086 SourceLocation RPLoc) { // "({..})"
4087 Stmt *SubStmt = static_cast<Stmt*>(substmt);
4088 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4089 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4090
Eli Friedmanbc941e12009-01-24 23:09:00 +00004091 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4092 if (isFileScope) {
4093 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4094 }
4095
Chris Lattner4b009652007-07-25 00:24:17 +00004096 // FIXME: there are a variety of strange constraints to enforce here, for
4097 // example, it is not possible to goto into a stmt expression apparently.
4098 // More semantic analysis is needed.
4099
4100 // FIXME: the last statement in the compount stmt has its value used. We
4101 // should not warn about it being unused.
4102
4103 // If there are sub stmts in the compound stmt, take the type of the last one
4104 // as the type of the stmtexpr.
4105 QualType Ty = Context.VoidTy;
4106
Chris Lattner200964f2008-07-26 19:51:01 +00004107 if (!Compound->body_empty()) {
4108 Stmt *LastStmt = Compound->body_back();
4109 // If LastStmt is a label, skip down through into the body.
4110 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4111 LastStmt = Label->getSubStmt();
4112
4113 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004114 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004115 }
Chris Lattner4b009652007-07-25 00:24:17 +00004116
Steve Naroff774e4152009-01-21 00:14:39 +00004117 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00004118}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004119
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004120Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4121 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004122 SourceLocation TypeLoc,
4123 TypeTy *argty,
4124 OffsetOfComponent *CompPtr,
4125 unsigned NumComponents,
4126 SourceLocation RPLoc) {
4127 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4128 assert(!ArgTy.isNull() && "Missing type argument!");
4129
4130 // We must have at least one component that refers to the type, and the first
4131 // one is known to be a field designator. Verify that the ArgTy represents
4132 // a struct/union/class.
4133 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00004134 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004135
4136 // Otherwise, create a compound literal expression as the base, and
4137 // iteratively process the offsetof designators.
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004138 InitListExpr *IList =
Douglas Gregorf603b472009-01-28 21:54:33 +00004139 new (Context) InitListExpr(SourceLocation(), 0, 0, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004140 IList->setType(ArgTy);
4141 Expr *Res =
4142 new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, IList, false);
4143
Chris Lattnerb37522e2007-08-31 21:49:13 +00004144 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4145 // GCC extension, diagnose them.
4146 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004147 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4148 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00004149
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004150 for (unsigned i = 0; i != NumComponents; ++i) {
4151 const OffsetOfComponent &OC = CompPtr[i];
4152 if (OC.isBrackets) {
4153 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00004154 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004155 if (!AT) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004156 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004157 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004158 }
4159
Chris Lattner2af6a802007-08-30 17:59:59 +00004160 // FIXME: C++: Verify that operator[] isn't overloaded.
4161
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004162 // C99 6.5.2.1p1
4163 Expr *Idx = static_cast<Expr*>(OC.U.E);
4164 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00004165 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4166 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004167
Steve Naroff774e4152009-01-21 00:14:39 +00004168 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4169 OC.LocEnd);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004170 continue;
4171 }
4172
4173 const RecordType *RC = Res->getType()->getAsRecordType();
4174 if (!RC) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004175 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004176 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004177 }
4178
4179 // Get the decl corresponding to this.
4180 RecordDecl *RD = RC->getDecl();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004181 FieldDecl *MemberDecl
Douglas Gregor52ae30c2009-01-30 01:04:22 +00004182 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4183 LookupMemberName)
4184 .getAsDecl());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004185 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00004186 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4187 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00004188
4189 // FIXME: C++: Verify that MemberDecl isn't a static field.
4190 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00004191 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4192 // matter here.
Steve Naroff774e4152009-01-21 00:14:39 +00004193 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4194 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004195 }
4196
Steve Naroff774e4152009-01-21 00:14:39 +00004197 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4198 Context.getSizeType(), BuiltinLoc);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004199}
4200
4201
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004202Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00004203 TypeTy *arg1, TypeTy *arg2,
4204 SourceLocation RPLoc) {
4205 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4206 QualType argT2 = QualType::getFromOpaquePtr(arg2);
4207
4208 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4209
Steve Naroff774e4152009-01-21 00:14:39 +00004210 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
4211 argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00004212}
4213
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004214Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00004215 ExprTy *expr1, ExprTy *expr2,
4216 SourceLocation RPLoc) {
4217 Expr *CondExpr = static_cast<Expr*>(cond);
4218 Expr *LHSExpr = static_cast<Expr*>(expr1);
4219 Expr *RHSExpr = static_cast<Expr*>(expr2);
4220
4221 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4222
4223 // The conditional expression is required to be a constant expression.
4224 llvm::APSInt condEval(32);
4225 SourceLocation ExpLoc;
4226 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004227 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4228 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00004229
4230 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4231 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
4232 RHSExpr->getType();
Steve Naroff774e4152009-01-21 00:14:39 +00004233 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4234 resType, RPLoc);
Steve Naroff93c53012007-08-03 21:21:27 +00004235}
4236
Steve Naroff52a81c02008-09-03 18:15:37 +00004237//===----------------------------------------------------------------------===//
4238// Clang Extensions.
4239//===----------------------------------------------------------------------===//
4240
4241/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004242void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004243 // Analyze block parameters.
4244 BlockSemaInfo *BSI = new BlockSemaInfo();
4245
4246 // Add BSI to CurBlock.
4247 BSI->PrevBlockInfo = CurBlock;
4248 CurBlock = BSI;
4249
4250 BSI->ReturnType = 0;
4251 BSI->TheScope = BlockScope;
4252
Steve Naroff52059382008-10-10 01:28:17 +00004253 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004254 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004255}
4256
Mike Stumpc1fddff2009-02-04 22:31:32 +00004257void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4258 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4259
4260 if (ParamInfo.getNumTypeObjects() == 0
4261 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4262 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4263
4264 // The type is entirely optional as well, if none, use DependentTy.
4265 if (T.isNull())
4266 T = Context.DependentTy;
4267
4268 // The parameter list is optional, if there was none, assume ().
4269 if (!T->isFunctionType())
4270 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4271
4272 CurBlock->hasPrototype = true;
4273 CurBlock->isVariadic = false;
4274 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4275 .getTypePtr();
4276
4277 if (!RetTy->isDependentType())
4278 CurBlock->ReturnType = RetTy;
4279 return;
4280 }
4281
Steve Naroff52a81c02008-09-03 18:15:37 +00004282 // Analyze arguments to block.
4283 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4284 "Not a function declarator!");
4285 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004286
Steve Naroff52059382008-10-10 01:28:17 +00004287 CurBlock->hasPrototype = FTI.hasPrototype;
4288 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00004289
4290 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4291 // no arguments, not a function that takes a single void argument.
4292 if (FTI.hasPrototype &&
4293 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4294 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4295 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4296 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004297 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004298 } else if (FTI.hasPrototype) {
4299 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004300 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4301 CurBlock->isVariadic = FTI.isVariadic;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004302 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4303
4304 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4305 .getTypePtr();
4306
4307 if (!RetTy->isDependentType())
4308 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00004309 }
Steve Naroff52059382008-10-10 01:28:17 +00004310 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4311
4312 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4313 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4314 // If this has an identifier, add it to the scope stack.
4315 if ((*AI)->getIdentifier())
4316 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004317}
4318
4319/// ActOnBlockError - If there is an error parsing a block, this callback
4320/// is invoked to pop the information about the block from the action impl.
4321void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4322 // Ensure that CurBlock is deleted.
4323 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4324
4325 // Pop off CurBlock, handle nested blocks.
4326 CurBlock = CurBlock->PrevBlockInfo;
4327
4328 // FIXME: Delete the ParmVarDecl objects as well???
4329
4330}
4331
4332/// ActOnBlockStmtExpr - This is called when the body of a block statement
4333/// literal was successfully completed. ^(int x){...}
4334Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4335 Scope *CurScope) {
4336 // Ensure that CurBlock is deleted.
4337 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Ted Kremenek0c97e042009-02-07 01:47:29 +00004338 ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body));
Steve Naroff52a81c02008-09-03 18:15:37 +00004339
Steve Naroff52059382008-10-10 01:28:17 +00004340 PopDeclContext();
4341
Steve Naroff52a81c02008-09-03 18:15:37 +00004342 // Pop off CurBlock, handle nested blocks.
4343 CurBlock = CurBlock->PrevBlockInfo;
4344
4345 QualType RetTy = Context.VoidTy;
4346 if (BSI->ReturnType)
4347 RetTy = QualType(BSI->ReturnType, 0);
4348
4349 llvm::SmallVector<QualType, 8> ArgTypes;
4350 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4351 ArgTypes.push_back(BSI->Params[i]->getType());
4352
4353 QualType BlockTy;
4354 if (!BSI->hasPrototype)
4355 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4356 else
4357 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004358 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00004359
4360 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00004361
Steve Naroff95029d92008-10-08 18:44:00 +00004362 BSI->TheDecl->setBody(Body.take());
Steve Naroff774e4152009-01-21 00:14:39 +00004363 return new (Context) BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004364}
4365
Nate Begemanbd881ef2008-01-30 20:50:20 +00004366/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004367/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00004368/// The number of arguments has already been validated to match the number of
4369/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004370static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4371 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004372 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00004373 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004374 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4375 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00004376
4377 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004378 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00004379 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004380 return true;
4381}
4382
4383Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4384 SourceLocation *CommaLocs,
4385 SourceLocation BuiltinLoc,
4386 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004387 // __builtin_overload requires at least 2 arguments
4388 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004389 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4390 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004391
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004392 // The first argument is required to be a constant expression. It tells us
4393 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00004394 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004395 Expr *NParamsExpr = Args[0];
4396 llvm::APSInt constEval(32);
4397 SourceLocation ExpLoc;
4398 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004399 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4400 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004401
4402 // Verify that the number of parameters is > 0
4403 unsigned NumParams = constEval.getZExtValue();
4404 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004405 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4406 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004407 // Verify that we have at least 1 + NumParams arguments to the builtin.
4408 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004409 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4410 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004411
4412 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00004413 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00004414 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004415 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4416 // UsualUnaryConversions will convert the function DeclRefExpr into a
4417 // pointer to function.
4418 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004419 const FunctionTypeProto *FnType = 0;
4420 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4421 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004422
4423 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4424 // parameters, and the number of parameters must match the value passed to
4425 // the builtin.
4426 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004427 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4428 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004429
4430 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00004431 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004432 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004433 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004434 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004435 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4436 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00004437 // Remember our match, and continue processing the remaining arguments
4438 // to catch any errors.
Steve Naroff774e4152009-01-21 00:14:39 +00004439 OE = new (Context) OverloadExpr(Args, NumArgs, i,
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004440 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00004441 BuiltinLoc, RParenLoc);
4442 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004443 }
Nate Begemanc6078c92008-01-31 05:38:29 +00004444 // Return the newly created OverloadExpr node, if we succeded in matching
4445 // exactly one of the candidate functions.
4446 if (OE)
4447 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004448
4449 // If we didn't find a matching function Expr in the __builtin_overload list
4450 // the return an error.
4451 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00004452 for (unsigned i = 0; i != NumParams; ++i) {
4453 if (i != 0) typeNames += ", ";
4454 typeNames += Args[i+1]->getType().getAsString();
4455 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004456
Chris Lattner77d52da2008-11-20 06:06:08 +00004457 return Diag(BuiltinLoc, diag::err_overload_no_match)
4458 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004459}
4460
Anders Carlsson36760332007-10-15 20:28:48 +00004461Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4462 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004463 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004464 Expr *E = static_cast<Expr*>(expr);
4465 QualType T = QualType::getFromOpaquePtr(type);
4466
4467 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004468
4469 // Get the va_list type
4470 QualType VaListType = Context.getBuiltinVaListType();
4471 // Deal with implicit array decay; for example, on x86-64,
4472 // va_list is an array, but it's supposed to decay to
4473 // a pointer for va_arg.
4474 if (VaListType->isArrayType())
4475 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004476 // Make sure the input expression also decays appropriately.
4477 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004478
4479 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004480 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004481 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004482 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00004483
4484 // FIXME: Warn if a non-POD type is passed in.
4485
Steve Naroff774e4152009-01-21 00:14:39 +00004486 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004487}
4488
Douglas Gregorad4b3792008-11-29 04:51:27 +00004489Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4490 // The type of __null will be int or long, depending on the size of
4491 // pointers on the target.
4492 QualType Ty;
4493 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4494 Ty = Context.IntTy;
4495 else
4496 Ty = Context.LongTy;
4497
Steve Naroff774e4152009-01-21 00:14:39 +00004498 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregorad4b3792008-11-29 04:51:27 +00004499}
4500
Chris Lattner005ed752008-01-04 18:04:52 +00004501bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4502 SourceLocation Loc,
4503 QualType DstType, QualType SrcType,
4504 Expr *SrcExpr, const char *Flavor) {
4505 // Decode the result (notice that AST's are still created for extensions).
4506 bool isInvalid = false;
4507 unsigned DiagKind;
4508 switch (ConvTy) {
4509 default: assert(0 && "Unknown conversion type");
4510 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004511 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004512 DiagKind = diag::ext_typecheck_convert_pointer_int;
4513 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004514 case IntToPointer:
4515 DiagKind = diag::ext_typecheck_convert_int_pointer;
4516 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004517 case IncompatiblePointer:
4518 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4519 break;
4520 case FunctionVoidPointer:
4521 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4522 break;
4523 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004524 // If the qualifiers lost were because we were applying the
4525 // (deprecated) C++ conversion from a string literal to a char*
4526 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4527 // Ideally, this check would be performed in
4528 // CheckPointerTypesForAssignment. However, that would require a
4529 // bit of refactoring (so that the second argument is an
4530 // expression, rather than a type), which should be done as part
4531 // of a larger effort to fix CheckPointerTypesForAssignment for
4532 // C++ semantics.
4533 if (getLangOptions().CPlusPlus &&
4534 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4535 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004536 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4537 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004538 case IntToBlockPointer:
4539 DiagKind = diag::err_int_to_block_pointer;
4540 break;
4541 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004542 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004543 break;
Steve Naroff19608432008-10-14 22:18:38 +00004544 case IncompatibleObjCQualifiedId:
4545 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4546 // it can give a more specific diagnostic.
4547 DiagKind = diag::warn_incompatible_qualified_id;
4548 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004549 case IncompatibleVectors:
4550 DiagKind = diag::warn_incompatible_vectors;
4551 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004552 case Incompatible:
4553 DiagKind = diag::err_typecheck_convert_incompatible;
4554 isInvalid = true;
4555 break;
4556 }
4557
Chris Lattner271d4c22008-11-24 05:29:24 +00004558 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4559 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004560 return isInvalid;
4561}
Anders Carlssond5201b92008-11-30 19:50:32 +00004562
4563bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4564{
4565 Expr::EvalResult EvalResult;
4566
4567 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4568 EvalResult.HasSideEffects) {
4569 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4570
4571 if (EvalResult.Diag) {
4572 // We only show the note if it's not the usual "invalid subexpression"
4573 // or if it's actually in a subexpression.
4574 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4575 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4576 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4577 }
4578
4579 return true;
4580 }
4581
4582 if (EvalResult.Diag) {
4583 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4584 E->getSourceRange();
4585
4586 // Print the reason it's not a constant.
4587 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4588 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4589 }
4590
4591 if (Result)
4592 *Result = EvalResult.Val.getInt();
4593 return false;
4594}