blob: 24f7965b63ccf8f872c1df6a489deeabef90f3b2 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
21#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000023#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000024#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000025#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000026using namespace clang;
27
Chris Lattner299b8842008-07-25 21:10:04 +000028//===----------------------------------------------------------------------===//
29// Standard Promotions and Conversions
30//===----------------------------------------------------------------------===//
31
Chris Lattner299b8842008-07-25 21:10:04 +000032/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
33void Sema::DefaultFunctionArrayConversion(Expr *&E) {
34 QualType Ty = E->getType();
35 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
36
Chris Lattner299b8842008-07-25 21:10:04 +000037 if (Ty->isFunctionType())
38 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +000039 else if (Ty->isArrayType()) {
40 // In C90 mode, arrays only promote to pointers if the array expression is
41 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
42 // type 'array of type' is converted to an expression that has type 'pointer
43 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
44 // that has type 'array of type' ...". The relevant change is "an lvalue"
45 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +000046 //
47 // C++ 4.2p1:
48 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
49 // T" can be converted to an rvalue of type "pointer to T".
50 //
51 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
52 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +000053 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
54 }
Chris Lattner299b8842008-07-25 21:10:04 +000055}
56
57/// UsualUnaryConversions - Performs various conversions that are common to most
58/// operators (C99 6.3). The conversions of array and function types are
59/// sometimes surpressed. For example, the array->pointer conversion doesn't
60/// apply if the array is an argument to the sizeof or address (&) operators.
61/// In these instances, this routine should *not* be called.
62Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
63 QualType Ty = Expr->getType();
64 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
65
Chris Lattner299b8842008-07-25 21:10:04 +000066 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
67 ImpCastExprToType(Expr, Context.IntTy);
68 else
69 DefaultFunctionArrayConversion(Expr);
70
71 return Expr;
72}
73
Chris Lattner9305c3d2008-07-25 22:25:12 +000074/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
75/// do not have a prototype. Arguments that have type float are promoted to
76/// double. All other argument types are converted by UsualUnaryConversions().
77void Sema::DefaultArgumentPromotion(Expr *&Expr) {
78 QualType Ty = Expr->getType();
79 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
80
81 // If this is a 'float' (CVR qualified or typedef) promote to double.
82 if (const BuiltinType *BT = Ty->getAsBuiltinType())
83 if (BT->getKind() == BuiltinType::Float)
84 return ImpCastExprToType(Expr, Context.DoubleTy);
85
86 UsualUnaryConversions(Expr);
87}
88
Anders Carlsson4b8e38c2009-01-16 16:48:51 +000089// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
90// will warn if the resulting type is not a POD type.
91void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT)
92
93{
94 DefaultArgumentPromotion(Expr);
95
96 if (!Expr->getType()->isPODType()) {
97 Diag(Expr->getLocStart(),
98 diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
99 Expr->getType() << CT;
100 }
101}
102
103
Chris Lattner299b8842008-07-25 21:10:04 +0000104/// UsualArithmeticConversions - Performs various conversions that are common to
105/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
106/// routine returns the first non-arithmetic type found. The client is
107/// responsible for emitting appropriate error diagnostics.
108/// FIXME: verify the conversion rules for "complex int" are consistent with
109/// GCC.
110QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
111 bool isCompAssign) {
112 if (!isCompAssign) {
113 UsualUnaryConversions(lhsExpr);
114 UsualUnaryConversions(rhsExpr);
115 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000116
Chris Lattner299b8842008-07-25 21:10:04 +0000117 // For conversion purposes, we ignore any qualifiers.
118 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000119 QualType lhs =
120 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
121 QualType rhs =
122 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000123
124 // If both types are identical, no conversion is needed.
125 if (lhs == rhs)
126 return lhs;
127
128 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
129 // The caller can deal with this (e.g. pointer + int).
130 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
131 return lhs;
132
133 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
134 if (!isCompAssign) {
135 ImpCastExprToType(lhsExpr, destType);
136 ImpCastExprToType(rhsExpr, destType);
137 }
138 return destType;
139}
140
141QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
142 // Perform the usual unary conversions. We do this early so that
143 // integral promotions to "int" can allow us to exit early, in the
144 // lhs == rhs check. Also, for conversion purposes, we ignore any
145 // qualifiers. For example, "const float" and "float" are
146 // equivalent.
Douglas Gregor3d4492e2008-11-13 20:12:29 +0000147 if (lhs->isPromotableIntegerType()) lhs = Context.IntTy;
148 else lhs = lhs.getUnqualifiedType();
149 if (rhs->isPromotableIntegerType()) rhs = Context.IntTy;
150 else rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000151
Chris Lattner299b8842008-07-25 21:10:04 +0000152 // If both types are identical, no conversion is needed.
153 if (lhs == rhs)
154 return lhs;
155
156 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
157 // The caller can deal with this (e.g. pointer + int).
158 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
159 return lhs;
160
161 // At this point, we have two different arithmetic types.
162
163 // Handle complex types first (C99 6.3.1.8p1).
164 if (lhs->isComplexType() || rhs->isComplexType()) {
165 // if we have an integer operand, the result is the complex type.
166 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
167 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000168 return lhs;
169 }
170 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
171 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000172 return rhs;
173 }
174 // This handles complex/complex, complex/float, or float/complex.
175 // When both operands are complex, the shorter operand is converted to the
176 // type of the longer, and that is the type of the result. This corresponds
177 // to what is done when combining two real floating-point operands.
178 // The fun begins when size promotion occur across type domains.
179 // From H&S 6.3.4: When one operand is complex and the other is a real
180 // floating-point type, the less precise type is converted, within it's
181 // real or complex domain, to the precision of the other type. For example,
182 // when combining a "long double" with a "double _Complex", the
183 // "double _Complex" is promoted to "long double _Complex".
184 int result = Context.getFloatingTypeOrder(lhs, rhs);
185
186 if (result > 0) { // The left side is bigger, convert rhs.
187 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000188 } else if (result < 0) { // The right side is bigger, convert lhs.
189 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000190 }
191 // At this point, lhs and rhs have the same rank/size. Now, make sure the
192 // domains match. This is a requirement for our implementation, C99
193 // does not require this promotion.
194 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
195 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000196 return rhs;
197 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000198 return lhs;
199 }
200 }
201 return lhs; // The domain/size match exactly.
202 }
203 // Now handle "real" floating types (i.e. float, double, long double).
204 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
205 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000206 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000207 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000208 return lhs;
209 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000210 if (rhs->isComplexIntegerType()) {
211 // convert rhs to the complex floating point type.
212 return Context.getComplexType(lhs);
213 }
214 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000215 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000216 return rhs;
217 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000218 if (lhs->isComplexIntegerType()) {
219 // convert lhs to the complex floating point type.
220 return Context.getComplexType(rhs);
221 }
Chris Lattner299b8842008-07-25 21:10:04 +0000222 // We have two real floating types, float/complex combos were handled above.
223 // Convert the smaller operand to the bigger result.
224 int result = Context.getFloatingTypeOrder(lhs, rhs);
225
226 if (result > 0) { // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000227 return lhs;
228 }
229 if (result < 0) { // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000230 return rhs;
231 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000232 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
Chris Lattner299b8842008-07-25 21:10:04 +0000233 }
234 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
235 // Handle GCC complex int extension.
236 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
237 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
238
239 if (lhsComplexInt && rhsComplexInt) {
240 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
241 rhsComplexInt->getElementType()) >= 0) {
242 // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000243 return lhs;
244 }
Chris Lattner299b8842008-07-25 21:10:04 +0000245 return rhs;
246 } else if (lhsComplexInt && rhs->isIntegerType()) {
247 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000248 return lhs;
249 } else if (rhsComplexInt && lhs->isIntegerType()) {
250 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000251 return rhs;
252 }
253 }
254 // Finally, we have two differing integer types.
255 // The rules for this case are in C99 6.3.1.8
256 int compare = Context.getIntegerTypeOrder(lhs, rhs);
257 bool lhsSigned = lhs->isSignedIntegerType(),
258 rhsSigned = rhs->isSignedIntegerType();
259 QualType destType;
260 if (lhsSigned == rhsSigned) {
261 // Same signedness; use the higher-ranked type
262 destType = compare >= 0 ? lhs : rhs;
263 } else if (compare != (lhsSigned ? 1 : -1)) {
264 // The unsigned type has greater than or equal rank to the
265 // signed type, so use the unsigned type
266 destType = lhsSigned ? rhs : lhs;
267 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
268 // The two types are different widths; if we are here, that
269 // means the signed type is larger than the unsigned type, so
270 // use the signed type.
271 destType = lhsSigned ? lhs : rhs;
272 } else {
273 // The signed type is higher-ranked than the unsigned type,
274 // but isn't actually any bigger (like unsigned int and long
275 // on most 32-bit systems). Use the unsigned type corresponding
276 // to the signed type.
277 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
278 }
Chris Lattner299b8842008-07-25 21:10:04 +0000279 return destType;
280}
281
282//===----------------------------------------------------------------------===//
283// Semantic Analysis for various Expression Types
284//===----------------------------------------------------------------------===//
285
286
Steve Naroff87d58b42007-09-16 03:34:24 +0000287/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000288/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
289/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
290/// multiple tokens. However, the common case is that StringToks points to one
291/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000292///
293Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000294Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000295 assert(NumStringToks && "Must have at least one string!");
296
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000297 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000298 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000299 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000300
301 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
302 for (unsigned i = 0; i != NumStringToks; ++i)
303 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000304
Chris Lattnera6dcce32008-02-11 00:02:17 +0000305 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000306 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000307 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000308
309 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
310 if (getLangOptions().CPlusPlus)
311 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000312
Chris Lattnera6dcce32008-02-11 00:02:17 +0000313 // Get an array type for the string, according to C99 6.4.5. This includes
314 // the nul terminator character as well as the string length for pascal
315 // strings.
316 StrTy = Context.getConstantArrayType(StrTy,
317 llvm::APInt(32, Literal.GetStringLength()+1),
318 ArrayType::Normal, 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000319
Chris Lattner4b009652007-07-25 00:24:17 +0000320 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Steve Naroff774e4152009-01-21 00:14:39 +0000321 return Owned(new (Context) StringLiteral(Literal.GetString(),
322 Literal.GetStringLength(),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000323 Literal.AnyWide, StrTy,
324 StringToks[0].getLocation(),
325 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000326}
327
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000328/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
329/// CurBlock to VD should cause it to be snapshotted (as we do for auto
330/// variables defined outside the block) or false if this is not needed (e.g.
331/// for values inside the block or for globals).
332///
333/// FIXME: This will create BlockDeclRefExprs for global variables,
334/// function references, etc which is suboptimal :) and breaks
335/// things like "integer constant expression" tests.
336static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
337 ValueDecl *VD) {
338 // If the value is defined inside the block, we couldn't snapshot it even if
339 // we wanted to.
340 if (CurBlock->TheDecl == VD->getDeclContext())
341 return false;
342
343 // If this is an enum constant or function, it is constant, don't snapshot.
344 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
345 return false;
346
347 // If this is a reference to an extern, static, or global variable, no need to
348 // snapshot it.
349 // FIXME: What about 'const' variables in C++?
350 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
351 return Var->hasLocalStorage();
352
353 return true;
354}
355
356
357
Steve Naroff0acc9c92007-09-15 18:49:24 +0000358/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000359/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000360/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000361/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000362/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000363Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
364 IdentifierInfo &II,
365 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000366 const CXXScopeSpec *SS,
367 bool isAddressOfOperand) {
368 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
369 /*ForceResolution*/false, isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000370}
371
Douglas Gregor566782a2009-01-06 05:10:23 +0000372/// BuildDeclRefExpr - Build either a DeclRefExpr or a
373/// QualifiedDeclRefExpr based on whether or not SS is a
374/// nested-name-specifier.
Sebastian Redl0c9da212009-02-03 20:19:35 +0000375DeclRefExpr *
376Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
377 bool TypeDependent, bool ValueDependent,
378 const CXXScopeSpec *SS) {
Steve Naroff774e4152009-01-21 00:14:39 +0000379 if (SS && !SS->isEmpty())
380 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000381 ValueDependent, SS->getRange().getBegin());
Steve Naroff774e4152009-01-21 00:14:39 +0000382 else
383 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000384}
385
Douglas Gregor723d3332009-01-07 00:43:41 +0000386/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
387/// variable corresponding to the anonymous union or struct whose type
388/// is Record.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000389static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000390 assert(Record->isAnonymousStructOrUnion() &&
391 "Record must be an anonymous struct or union!");
392
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000393 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000394 // be an O(1) operation rather than a slow walk through DeclContext's
395 // vector (which itself will be eliminated). DeclGroups might make
396 // this even better.
397 DeclContext *Ctx = Record->getDeclContext();
398 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
399 DEnd = Ctx->decls_end();
400 D != DEnd; ++D) {
401 if (*D == Record) {
402 // The object for the anonymous struct/union directly
403 // follows its type in the list of declarations.
404 ++D;
405 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000406 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000407 return *D;
408 }
409 }
410
411 assert(false && "Missing object for anonymous record");
412 return 0;
413}
414
Sebastian Redlcd883f72009-01-18 18:53:16 +0000415Sema::OwningExprResult
Douglas Gregor723d3332009-01-07 00:43:41 +0000416Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
417 FieldDecl *Field,
418 Expr *BaseObjectExpr,
419 SourceLocation OpLoc) {
420 assert(Field->getDeclContext()->isRecord() &&
421 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
422 && "Field must be stored inside an anonymous struct or union");
423
424 // Construct the sequence of field member references
425 // we'll have to perform to get to the field in the anonymous
426 // union/struct. The list of members is built from the field
427 // outward, so traverse it backwards to go from an object in
428 // the current context to the field we found.
429 llvm::SmallVector<FieldDecl *, 4> AnonFields;
430 AnonFields.push_back(Field);
431 VarDecl *BaseObject = 0;
432 DeclContext *Ctx = Field->getDeclContext();
433 do {
434 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000435 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000436 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
437 AnonFields.push_back(AnonField);
438 else {
439 BaseObject = cast<VarDecl>(AnonObject);
440 break;
441 }
442 Ctx = Ctx->getParent();
443 } while (Ctx->isRecord() &&
444 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
445
446 // Build the expression that refers to the base object, from
447 // which we will build a sequence of member references to each
448 // of the anonymous union objects and, eventually, the field we
449 // found via name lookup.
450 bool BaseObjectIsPointer = false;
451 unsigned ExtraQuals = 0;
452 if (BaseObject) {
453 // BaseObject is an anonymous struct/union variable (and is,
454 // therefore, not part of another non-anonymous record).
455 delete BaseObjectExpr;
456
Steve Naroff774e4152009-01-21 00:14:39 +0000457 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000458 SourceLocation());
459 ExtraQuals
460 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
461 } else if (BaseObjectExpr) {
462 // The caller provided the base object expression. Determine
463 // whether its a pointer and whether it adds any qualifiers to the
464 // anonymous struct/union fields we're looking into.
465 QualType ObjectType = BaseObjectExpr->getType();
466 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
467 BaseObjectIsPointer = true;
468 ObjectType = ObjectPtr->getPointeeType();
469 }
470 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
471 } else {
472 // We've found a member of an anonymous struct/union that is
473 // inside a non-anonymous struct/union, so in a well-formed
474 // program our base object expression is "this".
475 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
476 if (!MD->isStatic()) {
477 QualType AnonFieldType
478 = Context.getTagDeclType(
479 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
480 QualType ThisType = Context.getTagDeclType(MD->getParent());
481 if ((Context.getCanonicalType(AnonFieldType)
482 == Context.getCanonicalType(ThisType)) ||
483 IsDerivedFrom(ThisType, AnonFieldType)) {
484 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000485 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000486 MD->getThisType(Context));
487 BaseObjectIsPointer = true;
488 }
489 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000490 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
491 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000492 }
493 ExtraQuals = MD->getTypeQualifiers();
494 }
495
496 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000497 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
498 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000499 }
500
501 // Build the implicit member references to the field of the
502 // anonymous struct/union.
503 Expr *Result = BaseObjectExpr;
504 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
505 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
506 FI != FIEnd; ++FI) {
507 QualType MemberType = (*FI)->getType();
508 if (!(*FI)->isMutable()) {
509 unsigned combinedQualifiers
510 = MemberType.getCVRQualifiers() | ExtraQuals;
511 MemberType = MemberType.getQualifiedType(combinedQualifiers);
512 }
Steve Naroff774e4152009-01-21 00:14:39 +0000513 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
514 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000515 BaseObjectIsPointer = false;
516 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
517 OpLoc = SourceLocation();
518 }
519
Sebastian Redlcd883f72009-01-18 18:53:16 +0000520 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000521}
522
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000523/// ActOnDeclarationNameExpr - The parser has read some kind of name
524/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
525/// performs lookup on that name and returns an expression that refers
526/// to that name. This routine isn't directly called from the parser,
527/// because the parser doesn't know about DeclarationName. Rather,
528/// this routine is called by ActOnIdentifierExpr,
529/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
530/// which form the DeclarationName from the corresponding syntactic
531/// forms.
532///
533/// HasTrailingLParen indicates whether this identifier is used in a
534/// function call context. LookupCtx is only used for a C++
535/// qualified-id (foo::bar) to indicate the class or namespace that
536/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000537///
538/// If ForceResolution is true, then we will attempt to resolve the
539/// name even if it looks like a dependent name. This option is off by
540/// default.
Sebastian Redl0c9da212009-02-03 20:19:35 +0000541///
542/// isAddressOfOperand means that this expression is the direct operand
543/// of an address-of operator. This matters because this is the only
544/// situation where a qualified name referencing a non-static member may
545/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000546Sema::OwningExprResult
547Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
548 DeclarationName Name, bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000549 const CXXScopeSpec *SS, bool ForceResolution,
550 bool isAddressOfOperand) {
Douglas Gregora133e262008-12-06 00:22:45 +0000551 if (S->getTemplateParamParent() && Name.getAsIdentifierInfo() &&
552 HasTrailingLParen && !SS && !ForceResolution) {
553 // We've seen something of the form
554 // identifier(
555 // and we are in a template, so it is likely that 's' is a
556 // dependent name. However, we won't know until we've parsed all
557 // of the call arguments. So, build a CXXDependentNameExpr node
558 // to represent this name. Then, if it turns out that none of the
559 // arguments are type-dependent, we'll force the resolution of the
560 // dependent name at that point.
Steve Naroff774e4152009-01-21 00:14:39 +0000561 return Owned(new (Context) CXXDependentNameExpr(Name.getAsIdentifierInfo(),
562 Context.DependentTy, Loc));
Douglas Gregora133e262008-12-06 00:22:45 +0000563 }
564
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000565 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000566 if (SS && SS->isInvalid())
567 return ExprError();
568 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000569
Sebastian Redl0c9da212009-02-03 20:19:35 +0000570 Decl *D = 0;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000571 if (Lookup.isAmbiguous()) {
572 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
573 SS && SS->isSet() ? SS->getRange()
574 : SourceRange());
575 return ExprError();
576 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000577 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000578
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000579 // If this reference is in an Objective-C method, then ivar lookup happens as
580 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000581 IdentifierInfo *II = Name.getAsIdentifierInfo();
582 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000583 // There are two cases to handle here. 1) scoped lookup could have failed,
584 // in which case we should look for an ivar. 2) scoped lookup could have
585 // found a decl, but that decl is outside the current method (i.e. a global
586 // variable). In these two cases, we do a lookup for an ivar with this
587 // name, if the lookup suceeds, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000588 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000589 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000590 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000591 // FIXME: This should use a new expr for a direct reference, don't turn
592 // this into Self->ivar, just return a BareIVarExpr or something.
593 IdentifierInfo &II = Context.Idents.get("self");
Sebastian Redlcd883f72009-01-18 18:53:16 +0000594 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Steve Naroff774e4152009-01-21 00:14:39 +0000595 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
596 Loc, static_cast<Expr*>(SelfExpr.release()),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000597 true, true);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000598 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000599 return Owned(MRef);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000600 }
601 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000602 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000603 if (D == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000604 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000605 getCurMethodDecl()->getClassInterface()));
Steve Naroff774e4152009-01-21 00:14:39 +0000606 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000607 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000608 }
Chris Lattner4b009652007-07-25 00:24:17 +0000609 if (D == 0) {
610 // Otherwise, this could be an implicitly declared function reference (legal
611 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000612 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000613 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000614 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000615 else {
616 // If this name wasn't predeclared and if this is not a function call,
617 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000618 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000619 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
620 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000621 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
622 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000623 return ExprError(Diag(Loc, diag::err_undeclared_use)
624 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000625 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000626 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000627 }
628 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000629
Sebastian Redl0c9da212009-02-03 20:19:35 +0000630 // If this is an expression of the form &Class::member, don't build an
631 // implicit member ref, because we want a pointer to the member in general,
632 // not any specific instance's member.
633 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
634 NamedDecl *ND = dyn_cast<NamedDecl>(D);
635 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
636 if (ND && isa<CXXRecordDecl>(DC)) {
637 QualType DType;
638 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
639 DType = FD->getType().getNonReferenceType();
640 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
641 DType = Method->getType();
642 } else if (isa<OverloadedFunctionDecl>(D)) {
643 DType = Context.OverloadTy;
644 }
645 // Could be an inner type. That's diagnosed below, so ignore it here.
646 if (!DType.isNull()) {
647 // The pointer is type- and value-dependent if it points into something
648 // dependent.
649 bool Dependent = false;
650 for (; DC; DC = DC->getParent()) {
651 // FIXME: could stop early at namespace scope.
652 if (DC->isRecord()) {
653 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
654 if (Context.getTypeDeclType(Record)->isDependentType()) {
655 Dependent = true;
656 break;
657 }
658 }
659 }
660 return Owned(BuildDeclRefExpr(ND, DType, Loc, Dependent, Dependent,SS));
661 }
662 }
663 }
664
Douglas Gregor723d3332009-01-07 00:43:41 +0000665 // We may have found a field within an anonymous union or struct
666 // (C++ [class.union]).
667 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
668 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
669 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000670
Douglas Gregor3257fb52008-12-22 05:46:06 +0000671 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
672 if (!MD->isStatic()) {
673 // C++ [class.mfct.nonstatic]p2:
674 // [...] if name lookup (3.4.1) resolves the name in the
675 // id-expression to a nonstatic nontype member of class X or of
676 // a base class of X, the id-expression is transformed into a
677 // class member access expression (5.2.5) using (*this) (9.3.2)
678 // as the postfix-expression to the left of the '.' operator.
679 DeclContext *Ctx = 0;
680 QualType MemberType;
681 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
682 Ctx = FD->getDeclContext();
683 MemberType = FD->getType();
684
685 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
686 MemberType = RefType->getPointeeType();
687 else if (!FD->isMutable()) {
688 unsigned combinedQualifiers
689 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
690 MemberType = MemberType.getQualifiedType(combinedQualifiers);
691 }
692 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
693 if (!Method->isStatic()) {
694 Ctx = Method->getParent();
695 MemberType = Method->getType();
696 }
697 } else if (OverloadedFunctionDecl *Ovl
698 = dyn_cast<OverloadedFunctionDecl>(D)) {
699 for (OverloadedFunctionDecl::function_iterator
700 Func = Ovl->function_begin(),
701 FuncEnd = Ovl->function_end();
702 Func != FuncEnd; ++Func) {
703 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
704 if (!DMethod->isStatic()) {
705 Ctx = Ovl->getDeclContext();
706 MemberType = Context.OverloadTy;
707 break;
708 }
709 }
710 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000711
712 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000713 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
714 QualType ThisType = Context.getTagDeclType(MD->getParent());
715 if ((Context.getCanonicalType(CtxType)
716 == Context.getCanonicalType(ThisType)) ||
717 IsDerivedFrom(ThisType, CtxType)) {
718 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000719 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor3257fb52008-12-22 05:46:06 +0000720 MD->getThisType(Context));
Steve Naroff774e4152009-01-21 00:14:39 +0000721 return Owned(new (Context) MemberExpr(This, true, cast<NamedDecl>(D),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000722 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000723 }
724 }
725 }
726 }
727
Douglas Gregor8acb7272008-12-11 16:49:14 +0000728 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000729 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
730 if (MD->isStatic())
731 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000732 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
733 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000734 }
735
Douglas Gregor3257fb52008-12-22 05:46:06 +0000736 // Any other ways we could have found the field in a well-formed
737 // program would have been turned into implicit member expressions
738 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000739 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
740 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000741 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000742
Chris Lattner4b009652007-07-25 00:24:17 +0000743 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000744 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000745 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000746 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000747 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000748 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000749
Steve Naroffd6163f32008-09-05 22:11:13 +0000750 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000751 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000752 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
753 false, false, SS));
Douglas Gregord2baafd2008-10-21 16:13:35 +0000754
Steve Naroffd6163f32008-09-05 22:11:13 +0000755 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000756
Steve Naroffd6163f32008-09-05 22:11:13 +0000757 // check if referencing an identifier with __attribute__((deprecated)).
758 if (VD->getAttr<DeprecatedAttr>())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000759 ExprError(Diag(Loc, diag::warn_deprecated) << VD->getDeclName());
760
Douglas Gregor48840c72008-12-10 23:01:14 +0000761 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
762 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
763 Scope *CheckS = S;
764 while (CheckS) {
765 if (CheckS->isWithinElse() &&
766 CheckS->getControlParent()->isDeclScope(Var)) {
767 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000768 ExprError(Diag(Loc, diag::warn_value_always_false)
769 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000770 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000771 ExprError(Diag(Loc, diag::warn_value_always_zero)
772 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000773 break;
774 }
775
776 // Move up one more control parent to check again.
777 CheckS = CheckS->getControlParent();
778 if (CheckS)
779 CheckS = CheckS->getParent();
780 }
781 }
782 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000783
784 // Only create DeclRefExpr's for valid Decl's.
785 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000786 return ExprError();
787
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000788 // If the identifier reference is inside a block, and it refers to a value
789 // that is outside the block, create a BlockDeclRefExpr instead of a
790 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
791 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000792 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000793 // We do not do this for things like enum constants, global variables, etc,
794 // as they do not get snapshotted.
795 //
796 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000797 // The BlocksAttr indicates the variable is bound by-reference.
798 if (VD->getAttr<BlocksAttr>())
Steve Naroff774e4152009-01-21 00:14:39 +0000799 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000800 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000801
Steve Naroff52059382008-10-10 01:28:17 +0000802 // Variable will be bound by-copy, make it const within the closure.
803 VD->getType().addConst();
Steve Naroff774e4152009-01-21 00:14:39 +0000804 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000805 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000806 }
807 // If this reference is not in a block or if the referenced variable is
808 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000809
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000810 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000811 bool ValueDependent = false;
812 if (getLangOptions().CPlusPlus) {
813 // C++ [temp.dep.expr]p3:
814 // An id-expression is type-dependent if it contains:
815 // - an identifier that was declared with a dependent type,
816 if (VD->getType()->isDependentType())
817 TypeDependent = true;
818 // - FIXME: a template-id that is dependent,
819 // - a conversion-function-id that specifies a dependent type,
820 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
821 Name.getCXXNameType()->isDependentType())
822 TypeDependent = true;
823 // - a nested-name-specifier that contains a class-name that
824 // names a dependent type.
825 else if (SS && !SS->isEmpty()) {
826 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
827 DC; DC = DC->getParent()) {
828 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000829 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000830 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
831 if (Context.getTypeDeclType(Record)->isDependentType()) {
832 TypeDependent = true;
833 break;
834 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000835 }
836 }
837 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000838
Douglas Gregora5d84612008-12-10 20:57:37 +0000839 // C++ [temp.dep.constexpr]p2:
840 //
841 // An identifier is value-dependent if it is:
842 // - a name declared with a dependent type,
843 if (TypeDependent)
844 ValueDependent = true;
845 // - the name of a non-type template parameter,
846 else if (isa<NonTypeTemplateParmDecl>(VD))
847 ValueDependent = true;
848 // - a constant with integral or enumeration type and is
849 // initialized with an expression that is value-dependent
850 // (FIXME!).
851 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000852
Sebastian Redlcd883f72009-01-18 18:53:16 +0000853 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
854 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000855}
856
Sebastian Redlcd883f72009-01-18 18:53:16 +0000857Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
858 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000859 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000860
Chris Lattner4b009652007-07-25 00:24:17 +0000861 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000862 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000863 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
864 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
865 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000866 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000867
Chris Lattner7e637512008-01-12 08:14:25 +0000868 // Pre-defined identifiers are of type char[x], where x is the length of the
869 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000870 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000871 if (FunctionDecl *FD = getCurFunctionDecl())
872 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000873 else if (ObjCMethodDecl *MD = getCurMethodDecl())
874 Length = MD->getSynthesizedMethodSize();
875 else {
876 Diag(Loc, diag::ext_predef_outside_function);
877 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
878 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
879 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000880
881
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000882 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000883 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000884 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +0000885 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +0000886}
887
Sebastian Redlcd883f72009-01-18 18:53:16 +0000888Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000889 llvm::SmallString<16> CharBuffer;
890 CharBuffer.resize(Tok.getLength());
891 const char *ThisTokBegin = &CharBuffer[0];
892 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000893
Chris Lattner4b009652007-07-25 00:24:17 +0000894 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
895 Tok.getLocation(), PP);
896 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000897 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +0000898
899 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
900
Sebastian Redl75324932009-01-20 22:23:13 +0000901 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
902 Literal.isWide(),
903 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000904}
905
Sebastian Redlcd883f72009-01-18 18:53:16 +0000906Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
907 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +0000908 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
909 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +0000910 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +0000911 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +0000912 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +0000913 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000914 }
Ted Kremenekdbde2282009-01-13 23:19:12 +0000915
Chris Lattner4b009652007-07-25 00:24:17 +0000916 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000917 // Add padding so that NumericLiteralParser can overread by one character.
918 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000919 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +0000920
Chris Lattner4b009652007-07-25 00:24:17 +0000921 // Get the spelling of the token, which eliminates trigraphs, etc.
922 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000923
Chris Lattner4b009652007-07-25 00:24:17 +0000924 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
925 Tok.getLocation(), PP);
926 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000927 return ExprError();
928
Chris Lattner1de66eb2007-08-26 03:42:43 +0000929 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000930
Chris Lattner1de66eb2007-08-26 03:42:43 +0000931 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000932 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000933 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000934 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000935 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000936 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000937 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000938 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000939
940 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
941
Ted Kremenekddedbe22007-11-29 00:56:49 +0000942 // isExact will be set by GetFloatValue().
943 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +0000944 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
945 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +0000946
Chris Lattner1de66eb2007-08-26 03:42:43 +0000947 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000948 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +0000949 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000950 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000951
Neil Booth7421e9c2007-08-29 22:00:19 +0000952 // long long is a C99 feature.
953 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000954 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000955 Diag(Tok.getLocation(), diag::ext_longlong);
956
Chris Lattner4b009652007-07-25 00:24:17 +0000957 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000958 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000959
Chris Lattner4b009652007-07-25 00:24:17 +0000960 if (Literal.GetIntegerValue(ResultVal)) {
961 // If this value didn't fit into uintmax_t, warn and force to ull.
962 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000963 Ty = Context.UnsignedLongLongTy;
964 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000965 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000966 } else {
967 // If this value fits into a ULL, try to figure out what else it fits into
968 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000969
Chris Lattner4b009652007-07-25 00:24:17 +0000970 // Octal, Hexadecimal, and integers with a U suffix are allowed to
971 // be an unsigned int.
972 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
973
974 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000975 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000976 if (!Literal.isLong && !Literal.isLongLong) {
977 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000978 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000979
Chris Lattner4b009652007-07-25 00:24:17 +0000980 // Does it fit in a unsigned int?
981 if (ResultVal.isIntN(IntSize)) {
982 // Does it fit in a signed int?
983 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000984 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000985 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000986 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000987 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000988 }
Chris Lattner4b009652007-07-25 00:24:17 +0000989 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000990
Chris Lattner4b009652007-07-25 00:24:17 +0000991 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000992 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000993 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000994
Chris Lattner4b009652007-07-25 00:24:17 +0000995 // Does it fit in a unsigned long?
996 if (ResultVal.isIntN(LongSize)) {
997 // Does it fit in a signed long?
998 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000999 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001000 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001001 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001002 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001003 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001004 }
1005
Chris Lattner4b009652007-07-25 00:24:17 +00001006 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001007 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001008 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001009
Chris Lattner4b009652007-07-25 00:24:17 +00001010 // Does it fit in a unsigned long long?
1011 if (ResultVal.isIntN(LongLongSize)) {
1012 // Does it fit in a signed long long?
1013 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001014 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001015 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001016 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001017 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001018 }
1019 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001020
Chris Lattner4b009652007-07-25 00:24:17 +00001021 // If we still couldn't decide a type, we probably have something that
1022 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001023 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001024 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001025 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001026 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001027 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001028
Chris Lattnere4068872008-05-09 05:59:00 +00001029 if (ResultVal.getBitWidth() != Width)
1030 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001031 }
Sebastian Redl75324932009-01-20 22:23:13 +00001032 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001033 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001034
Chris Lattner1de66eb2007-08-26 03:42:43 +00001035 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1036 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001037 Res = new (Context) ImaginaryLiteral(Res,
1038 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001039
1040 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001041}
1042
Sebastian Redlcd883f72009-01-18 18:53:16 +00001043Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1044 SourceLocation R, ExprArg Val) {
1045 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001046 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001047 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001048}
1049
1050/// The UsualUnaryConversions() function is *not* called by this routine.
1051/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001052bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1053 SourceLocation OpLoc,
1054 const SourceRange &ExprRange,
1055 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +00001056 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001057 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001058 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001059 if (isSizeof)
1060 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1061 return false;
1062 }
1063
1064 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001065 Diag(OpLoc, diag::ext_sizeof_void_type)
1066 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001067 return false;
1068 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001069
Chris Lattner159fe082009-01-24 19:46:37 +00001070 return DiagnoseIncompleteType(OpLoc, exprType,
1071 isSizeof ? diag::err_sizeof_incomplete_type :
1072 diag::err_alignof_incomplete_type,
1073 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001074}
1075
Chris Lattner8d9f7962009-01-24 20:17:12 +00001076bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1077 const SourceRange &ExprRange) {
1078 E = E->IgnoreParens();
1079
1080 // alignof decl is always ok.
1081 if (isa<DeclRefExpr>(E))
1082 return false;
1083
1084 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1085 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1086 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001087 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001088 return true;
1089 }
1090 // Other fields are ok.
1091 return false;
1092 }
1093 }
1094 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1095}
1096
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001097/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1098/// the same for @c alignof and @c __alignof
1099/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001100Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001101Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1102 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001103 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001104 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001105
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001106 QualType ArgTy;
1107 SourceRange Range;
1108 if (isType) {
1109 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1110 Range = ArgRange;
Chris Lattnera78909b2009-01-24 19:49:13 +00001111
1112 // Verify that the operand is valid.
1113 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1114 return ExprError();
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001115 } else {
1116 // Get the end location.
1117 Expr *ArgEx = (Expr *)TyOrEx;
1118 Range = ArgEx->getSourceRange();
1119 ArgTy = ArgEx->getType();
Chris Lattnera78909b2009-01-24 19:49:13 +00001120
1121 // Verify that the operand is valid.
Chris Lattner8d9f7962009-01-24 20:17:12 +00001122 bool isInvalid;
Chris Lattner364a42d2009-01-24 21:29:22 +00001123 if (!isSizeof) {
Chris Lattner8d9f7962009-01-24 20:17:12 +00001124 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattner364a42d2009-01-24 21:29:22 +00001125 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1126 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1127 isInvalid = true;
1128 } else {
1129 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1130 }
Chris Lattner8d9f7962009-01-24 20:17:12 +00001131
1132 if (isInvalid) {
Chris Lattnera78909b2009-01-24 19:49:13 +00001133 DeleteExpr(ArgEx);
1134 return ExprError();
1135 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001136 }
1137
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001138 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff774e4152009-01-21 00:14:39 +00001139 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner159fe082009-01-24 19:46:37 +00001140 Context.getSizeType(), OpLoc,
1141 Range.getEnd()));
Chris Lattner4b009652007-07-25 00:24:17 +00001142}
1143
Chris Lattner5110ad52007-08-24 21:41:10 +00001144QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +00001145 DefaultFunctionArrayConversion(V);
1146
Chris Lattnera16e42d2007-08-26 05:39:26 +00001147 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001148 if (const ComplexType *CT = V->getType()->getAsComplexType())
1149 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001150
1151 // Otherwise they pass through real integer and floating point types here.
1152 if (V->getType()->isArithmeticType())
1153 return V->getType();
1154
1155 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +00001156 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001157 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001158}
1159
1160
Chris Lattner4b009652007-07-25 00:24:17 +00001161
Sebastian Redl8b769972009-01-19 00:08:26 +00001162Action::OwningExprResult
1163Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1164 tok::TokenKind Kind, ExprArg Input) {
1165 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001166
Chris Lattner4b009652007-07-25 00:24:17 +00001167 UnaryOperator::Opcode Opc;
1168 switch (Kind) {
1169 default: assert(0 && "Unknown unary op!");
1170 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1171 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1172 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001173
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001174 if (getLangOptions().CPlusPlus &&
1175 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1176 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001177 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001178 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1179
1180 // C++ [over.inc]p1:
1181 //
1182 // [...] If the function is a member function with one
1183 // parameter (which shall be of type int) or a non-member
1184 // function with two parameters (the second of which shall be
1185 // of type int), it defines the postfix increment operator ++
1186 // for objects of that type. When the postfix increment is
1187 // called as a result of using the ++ operator, the int
1188 // argument will have value zero.
1189 Expr *Args[2] = {
1190 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001191 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1192 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001193 };
1194
1195 // Build the candidate set for overloading
1196 OverloadCandidateSet CandidateSet;
1197 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
1198
1199 // Perform overload resolution.
1200 OverloadCandidateSet::iterator Best;
1201 switch (BestViableFunction(CandidateSet, Best)) {
1202 case OR_Success: {
1203 // We found a built-in operator or an overloaded operator.
1204 FunctionDecl *FnDecl = Best->Function;
1205
1206 if (FnDecl) {
1207 // We matched an overloaded operator. Build a call to that
1208 // operator.
1209
1210 // Convert the arguments.
1211 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1212 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001213 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001214 } else {
1215 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001216 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001217 FnDecl->getParamDecl(0)->getType(),
1218 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001219 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001220 }
1221
1222 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001223 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001224 = FnDecl->getType()->getAsFunctionType()->getResultType();
1225 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001226
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001227 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001228 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001229 SourceLocation());
1230 UsualUnaryConversions(FnExpr);
1231
Sebastian Redl8b769972009-01-19 00:08:26 +00001232 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001233 return Owned(new (Context)CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy,
Steve Naroffe5f128a2009-01-20 19:53:53 +00001234 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001235 } else {
1236 // We matched a built-in operator. Convert the arguments, then
1237 // break out so that we will build the appropriate built-in
1238 // operator node.
1239 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1240 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001241 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001242
1243 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001244 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001245 }
1246
1247 case OR_No_Viable_Function:
1248 // No viable function; fall through to handling this as a
1249 // built-in operator, which will produce an error message for us.
1250 break;
1251
1252 case OR_Ambiguous:
1253 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1254 << UnaryOperator::getOpcodeStr(Opc)
1255 << Arg->getSourceRange();
1256 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001257 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001258 }
1259
1260 // Either we found no viable overloaded operator or we matched a
1261 // built-in operator. In either case, fall through to trying to
1262 // build a built-in operation.
1263 }
1264
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001265 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1266 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001267 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001268 return ExprError();
1269 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001270 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001271}
1272
Sebastian Redl8b769972009-01-19 00:08:26 +00001273Action::OwningExprResult
1274Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1275 ExprArg Idx, SourceLocation RLoc) {
1276 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1277 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001278
Douglas Gregor80723c52008-11-19 17:17:41 +00001279 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001280 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001281 LHSExp->getType()->isEnumeralType() ||
1282 RHSExp->getType()->isRecordType() ||
1283 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001284 // Add the appropriate overloaded operators (C++ [over.match.oper])
1285 // to the candidate set.
1286 OverloadCandidateSet CandidateSet;
1287 Expr *Args[2] = { LHSExp, RHSExp };
1288 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
Sebastian Redl8b769972009-01-19 00:08:26 +00001289
Douglas Gregor80723c52008-11-19 17:17:41 +00001290 // Perform overload resolution.
1291 OverloadCandidateSet::iterator Best;
1292 switch (BestViableFunction(CandidateSet, Best)) {
1293 case OR_Success: {
1294 // We found a built-in operator or an overloaded operator.
1295 FunctionDecl *FnDecl = Best->Function;
1296
1297 if (FnDecl) {
1298 // We matched an overloaded operator. Build a call to that
1299 // operator.
1300
1301 // Convert the arguments.
1302 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1303 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1304 PerformCopyInitialization(RHSExp,
1305 FnDecl->getParamDecl(0)->getType(),
1306 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001307 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001308 } else {
1309 // Convert the arguments.
1310 if (PerformCopyInitialization(LHSExp,
1311 FnDecl->getParamDecl(0)->getType(),
1312 "passing") ||
1313 PerformCopyInitialization(RHSExp,
1314 FnDecl->getParamDecl(1)->getType(),
1315 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001316 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001317 }
1318
1319 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001320 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001321 = FnDecl->getType()->getAsFunctionType()->getResultType();
1322 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001323
Douglas Gregor80723c52008-11-19 17:17:41 +00001324 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001325 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor80723c52008-11-19 17:17:41 +00001326 SourceLocation());
1327 UsualUnaryConversions(FnExpr);
1328
Sebastian Redl8b769972009-01-19 00:08:26 +00001329 Base.release();
1330 Idx.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001331 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, Args, 2,
1332 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001333 } else {
1334 // We matched a built-in operator. Convert the arguments, then
1335 // break out so that we will build the appropriate built-in
1336 // operator node.
1337 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1338 "passing") ||
1339 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1340 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001341 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001342
1343 break;
1344 }
1345 }
1346
1347 case OR_No_Viable_Function:
1348 // No viable function; fall through to handling this as a
1349 // built-in operator, which will produce an error message for us.
1350 break;
1351
1352 case OR_Ambiguous:
1353 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1354 << "[]"
1355 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1356 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001357 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001358 }
1359
1360 // Either we found no viable overloaded operator or we matched a
1361 // built-in operator. In either case, fall through to trying to
1362 // build a built-in operation.
1363 }
1364
Chris Lattner4b009652007-07-25 00:24:17 +00001365 // Perform default conversions.
1366 DefaultFunctionArrayConversion(LHSExp);
1367 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001368
Chris Lattner4b009652007-07-25 00:24:17 +00001369 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1370
1371 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001372 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001373 // in the subscript position. As a result, we need to derive the array base
1374 // and index from the expression types.
1375 Expr *BaseExpr, *IndexExpr;
1376 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001377 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001378 BaseExpr = LHSExp;
1379 IndexExpr = RHSExp;
1380 // FIXME: need to deal with const...
1381 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001382 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001383 // Handle the uncommon case of "123[Ptr]".
1384 BaseExpr = RHSExp;
1385 IndexExpr = LHSExp;
1386 // FIXME: need to deal with const...
1387 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001388 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1389 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001390 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001391
Chris Lattner4b009652007-07-25 00:24:17 +00001392 // FIXME: need to deal with const...
1393 ResultType = VTy->getElementType();
1394 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001395 return ExprError(Diag(LHSExp->getLocStart(),
1396 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1397 }
Chris Lattner4b009652007-07-25 00:24:17 +00001398 // C99 6.5.2.1p1
1399 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001400 return ExprError(Diag(IndexExpr->getLocStart(),
1401 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001402
1403 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1404 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001405 // void (*)(int)) and pointers to incomplete types. Functions are not
1406 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001407 if (!ResultType->isObjectType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001408 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001409 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001410 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001411
Sebastian Redl8b769972009-01-19 00:08:26 +00001412 Base.release();
1413 Idx.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001414 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1415 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001416}
1417
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001418QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001419CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001420 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001421 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001422
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001423 // The vector accessor can't exceed the number of elements.
1424 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001425
1426 // This flag determines whether or not the component is one of the four
1427 // special names that indicate a subset of exactly half the elements are
1428 // to be selected.
1429 bool HalvingSwizzle = false;
1430
1431 // This flag determines whether or not CompName has an 's' char prefix,
1432 // indicating that it is a string of hex values to be used as vector indices.
1433 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001434
1435 // Check that we've found one of the special components, or that the component
1436 // names must come from the same set.
1437 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001438 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1439 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001440 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001441 do
1442 compStr++;
1443 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001444 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001445 do
1446 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001447 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001448 }
Nate Begeman1486b502009-01-18 01:47:54 +00001449
1450 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001451 // We didn't get to the end of the string. This means the component names
1452 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001453 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1454 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001455 return QualType();
1456 }
Nate Begeman1486b502009-01-18 01:47:54 +00001457
1458 // Ensure no component accessor exceeds the width of the vector type it
1459 // operates on.
1460 if (!HalvingSwizzle) {
1461 compStr = CompName.getName();
1462
1463 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001464 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001465
1466 while (*compStr) {
1467 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1468 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1469 << baseType << SourceRange(CompLoc);
1470 return QualType();
1471 }
1472 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001473 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001474
Nate Begeman1486b502009-01-18 01:47:54 +00001475 // If this is a halving swizzle, verify that the base type has an even
1476 // number of elements.
1477 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001478 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001479 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001480 return QualType();
1481 }
1482
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001483 // The component accessor looks fine - now we need to compute the actual type.
1484 // The vector type is implied by the component accessor. For example,
1485 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001486 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001487 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001488 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1489 : CompName.getLength();
1490 if (HexSwizzle)
1491 CompSize--;
1492
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001493 if (CompSize == 1)
1494 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001495
Nate Begemanaf6ed502008-04-18 23:10:10 +00001496 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001497 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001498 // diagostics look bad. We want extended vector types to appear built-in.
1499 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1500 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1501 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001502 }
1503 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001504}
1505
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001506/// constructSetterName - Return the setter name for the given
1507/// identifier, i.e. "set" + Name where the initial character of Name
1508/// has been capitalized.
1509// FIXME: Merge with same routine in Parser. But where should this
1510// live?
1511static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1512 const IdentifierInfo *Name) {
1513 llvm::SmallString<100> SelectorName;
1514 SelectorName = "set";
1515 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1516 SelectorName[3] = toupper(SelectorName[3]);
1517 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1518}
1519
Sebastian Redl8b769972009-01-19 00:08:26 +00001520Action::OwningExprResult
1521Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1522 tok::TokenKind OpKind, SourceLocation MemberLoc,
1523 IdentifierInfo &Member) {
1524 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001525 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001526
1527 // Perform default conversions.
1528 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001529
Steve Naroff2cb66382007-07-26 03:11:44 +00001530 QualType BaseType = BaseExpr->getType();
1531 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001532
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001533 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1534 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001535 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001536 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001537 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001538 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001539 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1540 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001541 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001542 return ExprError(Diag(MemberLoc,
1543 diag::err_typecheck_member_reference_arrow)
1544 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001545 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001546
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001547 // Handle field access to simple records. This also handles access to fields
1548 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001549 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001550 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001551 if (DiagnoseIncompleteType(OpLoc, BaseType,
1552 diag::err_typecheck_incomplete_tag,
1553 BaseExpr->getSourceRange()))
1554 return ExprError();
1555
Steve Naroff2cb66382007-07-26 03:11:44 +00001556 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001557 // FIXME: Qualified name lookup for C++ is a bit more complicated
1558 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001559 LookupResult Result
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001560 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001561 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001562
1563 Decl *MemberDecl = 0;
1564 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001565 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1566 << &Member << BaseExpr->getSourceRange());
1567 else if (Result.isAmbiguous()) {
1568 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1569 MemberLoc, BaseExpr->getSourceRange());
1570 return ExprError();
1571 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001572 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001573
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001574 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001575 // We may have found a field within an anonymous union or struct
1576 // (C++ [class.union]).
1577 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001578 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001579 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001580
Douglas Gregor82d44772008-12-20 23:49:58 +00001581 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1582 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001583 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001584 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1585 MemberType = Ref->getPointeeType();
1586 else {
1587 unsigned combinedQualifiers =
1588 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001589 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001590 combinedQualifiers &= ~QualType::Const;
1591 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1592 }
Eli Friedman76b49832008-02-06 22:48:16 +00001593
Steve Naroff774e4152009-01-21 00:14:39 +00001594 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1595 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001596 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001597 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001598 Var, MemberLoc,
1599 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001600 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001601 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1602 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001603 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001604 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001605 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001606 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001607 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001608 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Enum,
Sebastian Redl8b769972009-01-19 00:08:26 +00001609 MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001610 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001611 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1612 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001613
Douglas Gregor82d44772008-12-20 23:49:58 +00001614 // We found a declaration kind that we didn't expect. This is a
1615 // generic error message that tells the user that she can't refer
1616 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001617 return ExprError(Diag(MemberLoc,
1618 diag::err_typecheck_member_reference_unknown)
1619 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001620 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001621
Chris Lattnere9d71612008-07-21 04:59:05 +00001622 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1623 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001624 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001625 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Steve Naroff774e4152009-01-21 00:14:39 +00001626 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1627 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001628 OpKind == tok::arrow);
1629 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001630 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001631 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001632 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1633 << IFTy->getDecl()->getDeclName() << &Member
1634 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001635 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001636
Chris Lattnere9d71612008-07-21 04:59:05 +00001637 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1638 // pointer to a (potentially qualified) interface type.
1639 const PointerType *PTy;
1640 const ObjCInterfaceType *IFTy;
1641 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1642 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1643 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001644
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001645 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001646 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001647 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001648 MemberLoc, BaseExpr));
1649
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001650 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001651 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1652 E = IFTy->qual_end(); I != E; ++I)
1653 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001654 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001655 MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001656
1657 // If that failed, look for an "implicit" property by seeing if the nullary
1658 // selector is implemented.
1659
1660 // FIXME: The logic for looking up nullary and unary selectors should be
1661 // shared with the code in ActOnInstanceMessage.
1662
1663 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1664 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001665
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001666 // If this reference is in an @implementation, check for 'private' methods.
1667 if (!Getter)
1668 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1669 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1670 if (ObjCImplementationDecl *ImpDecl =
1671 ObjCImplementations[ClassDecl->getIdentifier()])
1672 Getter = ImpDecl->getInstanceMethod(Sel);
1673
Steve Naroff04151f32008-10-22 19:16:27 +00001674 // Look through local category implementations associated with the class.
1675 if (!Getter) {
1676 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1677 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1678 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1679 }
1680 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001681 if (Getter) {
1682 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001683 // will look for the matching setter, in case it is needed.
1684 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1685 &Member);
1686 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1687 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1688 if (!Setter) {
1689 // If this reference is in an @implementation, also check for 'private'
1690 // methods.
1691 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1692 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1693 if (ObjCImplementationDecl *ImpDecl =
1694 ObjCImplementations[ClassDecl->getIdentifier()])
1695 Setter = ImpDecl->getInstanceMethod(SetterSel);
1696 }
1697 // Look through local category implementations associated with the class.
1698 if (!Setter) {
1699 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1700 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1701 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1702 }
1703 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001704
1705 // FIXME: we must check that the setter has property type.
Steve Naroff774e4152009-01-21 00:14:39 +00001706 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
1707 Setter, MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001708 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001709
1710 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1711 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001712 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001713 // Handle properties on qualified "id" protocols.
1714 const ObjCQualifiedIdType *QIdTy;
1715 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1716 // Check protocols on qualified interfaces.
1717 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001718 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroffd1d44402008-10-20 22:53:06 +00001719 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001720 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001721 MemberLoc, BaseExpr));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001722 // Also must look for a getter name which uses property syntax.
1723 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1724 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Steve Naroff774e4152009-01-21 00:14:39 +00001725 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
1726 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001727 }
1728 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001729
1730 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1731 << &Member << BaseType);
1732 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001733 // Handle 'field access' to vectors, such as 'V.xx'.
1734 if (BaseType->isExtVectorType() && OpKind == tok::period) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001735 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1736 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001737 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00001738 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
1739 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001740 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001741
1742 return ExprError(Diag(MemberLoc,
1743 diag::err_typecheck_member_reference_struct_union)
1744 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001745}
1746
Douglas Gregor3257fb52008-12-22 05:46:06 +00001747/// ConvertArgumentsForCall - Converts the arguments specified in
1748/// Args/NumArgs to the parameter types of the function FDecl with
1749/// function prototype Proto. Call is the call expression itself, and
1750/// Fn is the function expression. For a C++ member function, this
1751/// routine does not attempt to convert the object argument. Returns
1752/// true if the call is ill-formed.
1753bool
1754Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1755 FunctionDecl *FDecl,
1756 const FunctionTypeProto *Proto,
1757 Expr **Args, unsigned NumArgs,
1758 SourceLocation RParenLoc) {
1759 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1760 // assignment, to the types of the corresponding parameter, ...
1761 unsigned NumArgsInProto = Proto->getNumArgs();
1762 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001763 bool Invalid = false;
1764
Douglas Gregor3257fb52008-12-22 05:46:06 +00001765 // If too few arguments are available (and we don't have default
1766 // arguments for the remaining parameters), don't make the call.
1767 if (NumArgs < NumArgsInProto) {
1768 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1769 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1770 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1771 // Use default arguments for missing arguments
1772 NumArgsToCheck = NumArgsInProto;
1773 Call->setNumArgs(NumArgsInProto);
1774 }
1775
1776 // If too many are passed and not variadic, error on the extras and drop
1777 // them.
1778 if (NumArgs > NumArgsInProto) {
1779 if (!Proto->isVariadic()) {
1780 Diag(Args[NumArgsInProto]->getLocStart(),
1781 diag::err_typecheck_call_too_many_args)
1782 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1783 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1784 Args[NumArgs-1]->getLocEnd());
1785 // This deletes the extra arguments.
1786 Call->setNumArgs(NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001787 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001788 }
1789 NumArgsToCheck = NumArgsInProto;
1790 }
1791
1792 // Continue to check argument types (even if we have too few/many args).
1793 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1794 QualType ProtoArgType = Proto->getArgType(i);
1795
1796 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001797 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001798 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001799
1800 // Pass the argument.
1801 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1802 return true;
1803 } else
1804 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00001805 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001806 QualType ArgType = Arg->getType();
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001807
Douglas Gregor3257fb52008-12-22 05:46:06 +00001808 Call->setArg(i, Arg);
1809 }
1810
1811 // If this is a variadic call, handle args passed through "...".
1812 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001813 VariadicCallType CallType = VariadicFunction;
1814 if (Fn->getType()->isBlockPointerType())
1815 CallType = VariadicBlock; // Block
1816 else if (isa<MemberExpr>(Fn))
1817 CallType = VariadicMethod;
1818
Douglas Gregor3257fb52008-12-22 05:46:06 +00001819 // Promote the arguments (C99 6.5.2.2p7).
1820 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1821 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001822 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001823 Call->setArg(i, Arg);
1824 }
1825 }
1826
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001827 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001828}
1829
Steve Naroff87d58b42007-09-16 03:34:24 +00001830/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001831/// This provides the location of the left/right parens and a list of comma
1832/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00001833Action::OwningExprResult
1834Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1835 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001836 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001837 unsigned NumArgs = args.size();
1838 Expr *Fn = static_cast<Expr *>(fn.release());
1839 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00001840 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001841 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001842
Douglas Gregora133e262008-12-06 00:22:45 +00001843 // Determine whether this is a dependent call inside a C++ template,
1844 // in which case we won't do any semantic analysis now.
1845 bool Dependent = false;
1846 if (Fn->isTypeDependent()) {
1847 if (CXXDependentNameExpr *FnName = dyn_cast<CXXDependentNameExpr>(Fn)) {
1848 if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1849 Dependent = true;
1850 else {
1851 // Resolve the CXXDependentNameExpr to an actual identifier;
1852 // it wasn't really a dependent name after all.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001853 // FIXME: in the presence of ADL, this resolves too early.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001854 OwningExprResult Resolved
1855 = ActOnDeclarationNameExpr(S, FnName->getLocation(),
1856 FnName->getName(),
Douglas Gregora133e262008-12-06 00:22:45 +00001857 /*HasTrailingLParen=*/true,
1858 /*SS=*/0,
1859 /*ForceResolution=*/true);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001860 if (Resolved.isInvalid())
Sebastian Redl8b769972009-01-19 00:08:26 +00001861 return ExprError();
Douglas Gregora133e262008-12-06 00:22:45 +00001862 else {
1863 delete Fn;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001864 Fn = (Expr *)Resolved.release();
Douglas Gregora133e262008-12-06 00:22:45 +00001865 }
1866 }
1867 } else
1868 Dependent = true;
1869 } else
1870 Dependent = Expr::hasAnyTypeDependentArguments(Args, NumArgs);
1871
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001872 // FIXME: Will need to cache the results of name lookup (including
1873 // ADL) in Fn.
Douglas Gregora133e262008-12-06 00:22:45 +00001874 if (Dependent)
Steve Naroff774e4152009-01-21 00:14:39 +00001875 return Owned(new (Context) CallExpr(Fn, Args, NumArgs,
1876 Context.DependentTy, RParenLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001877
Douglas Gregor3257fb52008-12-22 05:46:06 +00001878 // Determine whether this is a call to an object (C++ [over.call.object]).
1879 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001880 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1881 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001882
Douglas Gregor3257fb52008-12-22 05:46:06 +00001883 if (getLangOptions().CPlusPlus) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001884 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00001885 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1886 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1887 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00001888 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1889 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001890 }
1891
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001892 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00001893 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001894 Expr *FnExpr = Fn;
1895 bool ADL = true;
1896 while (true) {
1897 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
1898 FnExpr = IcExpr->getSubExpr();
1899 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
1900 // FIXME: Where does the C++ standard say this?
1901 ADL = false;
1902 FnExpr = PExpr->getSubExpr();
1903 } else if (isa<UnaryOperator>(FnExpr) &&
1904 cast<UnaryOperator>(FnExpr)->getOpcode()
1905 == UnaryOperator::AddrOf) {
1906 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
1907 } else {
1908 DRExpr = dyn_cast<DeclRefExpr>(FnExpr);
1909 break;
1910 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001911 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001912
1913 if (DRExpr)
1914 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregord2baafd2008-10-21 16:13:35 +00001915
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001916 if (getLangOptions().CPlusPlus && DRExpr &&
1917 (FDecl || isa<OverloadedFunctionDecl>(DRExpr->getDecl()))) {
1918 // C++ [basic.lookup.argdep]p1:
1919 // When an unqualified name is used as the postfix-expression in
1920 // a function call (5.2.2), other namespaces not considered
1921 // during the usual unqualified lookup (3.4.1) may be searched,
1922 // and namespace-scope friend func- tion declarations (11.4) not
1923 // otherwise visible may be found.
1924 if (DRExpr && isa<QualifiedDeclRefExpr>(DRExpr))
1925 ADL = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001926
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001927 // We don't perform ADL for builtins.
1928 if (FDecl && FDecl->getIdentifier() &&
1929 FDecl->getIdentifier()->getBuiltinID())
1930 ADL = false;
1931
1932 if ((DRExpr && isa<OverloadedFunctionDecl>(DRExpr->getDecl())) || ADL) {
1933 FDecl = ResolveOverloadedCallFn(Fn, DRExpr->getDecl(), LParenLoc, Args,
1934 NumArgs, CommaLocs, RParenLoc, ADL);
1935 if (!FDecl)
1936 return ExprError();
1937
1938 // Update Fn to refer to the actual function selected.
1939 Expr *NewFn = 0;
1940 if (QualifiedDeclRefExpr *QDRExpr
1941 = dyn_cast<QualifiedDeclRefExpr>(DRExpr))
1942 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
1943 QDRExpr->getLocation(),
1944 false, false,
1945 QDRExpr->getSourceRange().getBegin());
1946 else
1947 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
1948 Fn->getSourceRange().getBegin());
1949 Fn->Destroy(Context);
1950 Fn = NewFn;
1951 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001952 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001953
1954 // Promote the function operand.
1955 UsualUnaryConversions(Fn);
1956
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001957 // Make the call expr early, before semantic checks. This guarantees cleanup
1958 // of arguments and function on error.
Sebastian Redl8b769972009-01-19 00:08:26 +00001959 // FIXME: Except that llvm::OwningPtr uses delete, when it really must be
1960 // Destroy(), or nothing gets cleaned up.
Steve Naroff774e4152009-01-21 00:14:39 +00001961 llvm::OwningPtr<CallExpr> TheCall(new (Context) CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001962 Context.BoolTy, RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001963
Steve Naroffd6163f32008-09-05 22:11:13 +00001964 const FunctionType *FuncT;
1965 if (!Fn->getType()->isBlockPointerType()) {
1966 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1967 // have type pointer to function".
1968 const PointerType *PT = Fn->getType()->getAsPointerType();
1969 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00001970 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1971 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00001972 FuncT = PT->getPointeeType()->getAsFunctionType();
1973 } else { // This is a block call.
1974 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1975 getAsFunctionType();
1976 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001977 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00001978 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1979 << Fn->getType() << Fn->getSourceRange());
1980
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001981 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001982 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00001983
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001984 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001985 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
1986 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00001987 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001988 } else {
1989 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00001990
Steve Naroffdb65e052007-08-28 23:30:39 +00001991 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001992 for (unsigned i = 0; i != NumArgs; i++) {
1993 Expr *Arg = Args[i];
1994 DefaultArgumentPromotion(Arg);
1995 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001996 }
Chris Lattner4b009652007-07-25 00:24:17 +00001997 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001998
Douglas Gregor3257fb52008-12-22 05:46:06 +00001999 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2000 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002001 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2002 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002003
Chris Lattner2e64c072007-08-10 20:18:51 +00002004 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00002005 if (FDecl)
2006 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002007
Sebastian Redl8b769972009-01-19 00:08:26 +00002008 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002009}
2010
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002011Action::OwningExprResult
2012Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2013 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002014 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002015 QualType literalType = QualType::getFromOpaquePtr(Ty);
2016 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002017 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002018 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002019
Eli Friedman8c2173d2008-05-20 05:22:08 +00002020 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002021 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002022 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2023 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002024 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2025 diag::err_typecheck_decl_incomplete_type,
2026 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002027 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002028
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002029 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002030 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002031 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002032
Chris Lattnere5cb5862008-12-04 23:50:19 +00002033 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002034 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002035 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002036 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002037 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002038 InitExpr.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002039 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
2040 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002041}
2042
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002043Action::OwningExprResult
2044Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2045 InitListDesignations &Designators,
2046 SourceLocation RBraceLoc) {
2047 unsigned NumInit = initlist.size();
2048 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002049
Steve Naroff0acc9c92007-09-15 18:49:24 +00002050 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00002051 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002052
Steve Naroff774e4152009-01-21 00:14:39 +00002053 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002054 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002055 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002056 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002057}
2058
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002059/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002060bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002061 UsualUnaryConversions(castExpr);
2062
2063 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2064 // type needs to be scalar.
2065 if (castType->isVoidType()) {
2066 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002067 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2068 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002069 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002070 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2071 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2072 (castType->isStructureType() || castType->isUnionType())) {
2073 // GCC struct/union extension: allow cast to self.
2074 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2075 << castType << castExpr->getSourceRange();
2076 } else if (castType->isUnionType()) {
2077 // GCC cast to union extension
2078 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2079 RecordDecl::field_iterator Field, FieldEnd;
2080 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2081 Field != FieldEnd; ++Field) {
2082 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2083 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2084 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2085 << castExpr->getSourceRange();
2086 break;
2087 }
2088 }
2089 if (Field == FieldEnd)
2090 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2091 << castExpr->getType() << castExpr->getSourceRange();
2092 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002093 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002094 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002095 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002096 }
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002097 } else if (!castExpr->getType()->isScalarType() &&
2098 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002099 return Diag(castExpr->getLocStart(),
2100 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002101 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002102 } else if (castExpr->getType()->isVectorType()) {
2103 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2104 return true;
2105 } else if (castType->isVectorType()) {
2106 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2107 return true;
2108 }
2109 return false;
2110}
2111
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002112bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002113 assert(VectorTy->isVectorType() && "Not a vector type!");
2114
2115 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002116 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002117 return Diag(R.getBegin(),
2118 Ty->isVectorType() ?
2119 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002120 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002121 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002122 } else
2123 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002124 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002125 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002126
2127 return false;
2128}
2129
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002130Action::OwningExprResult
2131Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2132 SourceLocation RParenLoc, ExprArg Op) {
2133 assert((Ty != 0) && (Op.get() != 0) &&
2134 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002135
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002136 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002137 QualType castType = QualType::getFromOpaquePtr(Ty);
2138
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002139 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002140 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002141 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002142 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002143}
2144
Chris Lattner98a425c2007-11-26 01:40:58 +00002145/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2146/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00002147inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
2148 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
2149 UsualUnaryConversions(cond);
2150 UsualUnaryConversions(lex);
2151 UsualUnaryConversions(rex);
2152 QualType condT = cond->getType();
2153 QualType lexT = lex->getType();
2154 QualType rexT = rex->getType();
2155
2156 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002157 if (!cond->isTypeDependent()) {
2158 if (!condT->isScalarType()) { // C99 6.5.15p2
2159 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
2160 return QualType();
2161 }
Chris Lattner4b009652007-07-25 00:24:17 +00002162 }
Chris Lattner992ae932008-01-06 22:42:25 +00002163
2164 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002165 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
2166 return Context.DependentTy;
2167
Chris Lattner992ae932008-01-06 22:42:25 +00002168 // If both operands have arithmetic type, do the usual arithmetic conversions
2169 // to find a common type: C99 6.5.15p3,5.
2170 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002171 UsualArithmeticConversions(lex, rex);
2172 return lex->getType();
2173 }
Chris Lattner992ae932008-01-06 22:42:25 +00002174
2175 // If both operands are the same structure or union type, the result is that
2176 // type.
Chris Lattner71225142007-07-31 21:27:01 +00002177 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00002178 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002179 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00002180 // "If both the operands have structure or union type, the result has
2181 // that type." This implies that CV qualifiers are dropped.
2182 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002183 }
Chris Lattner992ae932008-01-06 22:42:25 +00002184
2185 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002186 // The following || allows only one side to be void (a GCC-ism).
2187 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00002188 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002189 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2190 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00002191 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002192 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2193 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00002194 ImpCastExprToType(lex, Context.VoidTy);
2195 ImpCastExprToType(rex, Context.VoidTy);
2196 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002197 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002198 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2199 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002200 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2201 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002202 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002203 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002204 return lexT;
2205 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002206 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2207 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002208 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002209 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002210 return rexT;
2211 }
Chris Lattner0ac51632008-01-06 22:50:31 +00002212 // Handle the case where both operands are pointers before we handle null
2213 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00002214 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2215 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2216 // get the "pointed to" types
2217 QualType lhptee = LHSPT->getPointeeType();
2218 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002219
Chris Lattner71225142007-07-31 21:27:01 +00002220 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2221 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002222 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002223 // Figure out necessary qualifiers (C99 6.5.15p6)
2224 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002225 QualType destType = Context.getPointerType(destPointee);
2226 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2227 ImpCastExprToType(rex, destType); // promote to void*
2228 return destType;
2229 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002230 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002231 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002232 QualType destType = Context.getPointerType(destPointee);
2233 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2234 ImpCastExprToType(rex, destType); // promote to void*
2235 return destType;
2236 }
Chris Lattner4b009652007-07-25 00:24:17 +00002237
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002238 QualType compositeType = lexT;
2239
2240 // If either type is an Objective-C object type then check
2241 // compatibility according to Objective-C.
2242 if (Context.isObjCObjectPointerType(lexT) ||
2243 Context.isObjCObjectPointerType(rexT)) {
2244 // If both operands are interfaces and either operand can be
2245 // assigned to the other, use that type as the composite
2246 // type. This allows
2247 // xxx ? (A*) a : (B*) b
2248 // where B is a subclass of A.
2249 //
2250 // Additionally, as for assignment, if either type is 'id'
2251 // allow silent coercion. Finally, if the types are
2252 // incompatible then make sure to use 'id' as the composite
2253 // type so the result is acceptable for sending messages to.
2254
2255 // FIXME: This code should not be localized to here. Also this
2256 // should use a compatible check instead of abusing the
2257 // canAssignObjCInterfaces code.
2258 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2259 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2260 if (LHSIface && RHSIface &&
2261 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2262 compositeType = lexT;
2263 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002264 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002265 compositeType = rexT;
2266 } else if (Context.isObjCIdType(lhptee) ||
2267 Context.isObjCIdType(rhptee)) {
2268 // FIXME: This code looks wrong, because isObjCIdType checks
2269 // the struct but getObjCIdType returns the pointer to
2270 // struct. This is horrible and should be fixed.
2271 compositeType = Context.getObjCIdType();
2272 } else {
2273 QualType incompatTy = Context.getObjCIdType();
2274 ImpCastExprToType(lex, incompatTy);
2275 ImpCastExprToType(rex, incompatTy);
2276 return incompatTy;
2277 }
2278 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2279 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002280 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002281 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002282 // In this situation, we assume void* type. No especially good
2283 // reason, but this is what gcc does, and we do have to pick
2284 // to get a consistent AST.
2285 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002286 ImpCastExprToType(lex, incompatTy);
2287 ImpCastExprToType(rex, incompatTy);
2288 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002289 }
2290 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002291 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2292 // differently qualified versions of compatible types, the result type is
2293 // a pointer to an appropriately qualified version of the *composite*
2294 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002295 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002296 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00002297 ImpCastExprToType(lex, compositeType);
2298 ImpCastExprToType(rex, compositeType);
2299 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002300 }
Chris Lattner4b009652007-07-25 00:24:17 +00002301 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002302 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2303 // evaluates to "struct objc_object *" (and is handled above when comparing
2304 // id with statically typed objects).
2305 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2306 // GCC allows qualified id and any Objective-C type to devolve to
2307 // id. Currently localizing to here until clear this should be
2308 // part of ObjCQualifiedIdTypesAreCompatible.
2309 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2310 (lexT->isObjCQualifiedIdType() &&
2311 Context.isObjCObjectPointerType(rexT)) ||
2312 (rexT->isObjCQualifiedIdType() &&
2313 Context.isObjCObjectPointerType(lexT))) {
2314 // FIXME: This is not the correct composite type. This only
2315 // happens to work because id can more or less be used anywhere,
2316 // however this may change the type of method sends.
2317 // FIXME: gcc adds some type-checking of the arguments and emits
2318 // (confusing) incompatible comparison warnings in some
2319 // cases. Investigate.
2320 QualType compositeType = Context.getObjCIdType();
2321 ImpCastExprToType(lex, compositeType);
2322 ImpCastExprToType(rex, compositeType);
2323 return compositeType;
2324 }
2325 }
2326
Steve Naroff3eac7692008-09-10 19:17:48 +00002327 // Selection between block pointer types is ok as long as they are the same.
2328 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2329 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2330 return lexT;
2331
Chris Lattner992ae932008-01-06 22:42:25 +00002332 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00002333 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002334 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002335 return QualType();
2336}
2337
Steve Naroff87d58b42007-09-16 03:34:24 +00002338/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002339/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002340Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2341 SourceLocation ColonLoc,
2342 ExprArg Cond, ExprArg LHS,
2343 ExprArg RHS) {
2344 Expr *CondExpr = (Expr *) Cond.get();
2345 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002346
2347 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2348 // was the condition.
2349 bool isLHSNull = LHSExpr == 0;
2350 if (isLHSNull)
2351 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002352
2353 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002354 RHSExpr, QuestionLoc);
2355 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002356 return ExprError();
2357
2358 Cond.release();
2359 LHS.release();
2360 RHS.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002361 return Owned(new (Context) ConditionalOperator(CondExpr,
2362 isLHSNull ? 0 : LHSExpr,
2363 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002364}
2365
Chris Lattner4b009652007-07-25 00:24:17 +00002366
2367// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2368// being closely modeled after the C99 spec:-). The odd characteristic of this
2369// routine is it effectively iqnores the qualifiers on the top level pointee.
2370// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2371// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00002372Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002373Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2374 QualType lhptee, rhptee;
2375
2376 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002377 lhptee = lhsType->getAsPointerType()->getPointeeType();
2378 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002379
2380 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002381 lhptee = Context.getCanonicalType(lhptee);
2382 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002383
Chris Lattner005ed752008-01-04 18:04:52 +00002384 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002385
2386 // C99 6.5.16.1p1: This following citation is common to constraints
2387 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2388 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00002389 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002390 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002391 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002392
2393 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2394 // incomplete type and the other is a pointer to a qualified or unqualified
2395 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002396 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002397 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002398 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002399
2400 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002401 assert(rhptee->isFunctionType());
2402 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002403 }
2404
2405 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002406 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002407 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002408
2409 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002410 assert(lhptee->isFunctionType());
2411 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002412 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002413
2414 // Check for ObjC interfaces
2415 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2416 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2417 if (LHSIface && RHSIface &&
2418 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2419 return ConvTy;
2420
2421 // ID acts sort of like void* for ObjC interfaces
2422 if (LHSIface && Context.isObjCIdType(rhptee))
2423 return ConvTy;
2424 if (RHSIface && Context.isObjCIdType(lhptee))
2425 return ConvTy;
2426
Chris Lattner4b009652007-07-25 00:24:17 +00002427 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2428 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002429 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2430 rhptee.getUnqualifiedType()))
2431 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002432 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002433}
2434
Steve Naroff3454b6c2008-09-04 15:10:53 +00002435/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2436/// block pointer types are compatible or whether a block and normal pointer
2437/// are compatible. It is more restrict than comparing two function pointer
2438// types.
2439Sema::AssignConvertType
2440Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2441 QualType rhsType) {
2442 QualType lhptee, rhptee;
2443
2444 // get the "pointed to" type (ignoring qualifiers at the top level)
2445 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2446 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2447
2448 // make sure we operate on the canonical type
2449 lhptee = Context.getCanonicalType(lhptee);
2450 rhptee = Context.getCanonicalType(rhptee);
2451
2452 AssignConvertType ConvTy = Compatible;
2453
2454 // For blocks we enforce that qualifiers are identical.
2455 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2456 ConvTy = CompatiblePointerDiscardsQualifiers;
2457
2458 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2459 return IncompatibleBlockPointer;
2460 return ConvTy;
2461}
2462
Chris Lattner4b009652007-07-25 00:24:17 +00002463/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2464/// has code to accommodate several GCC extensions when type checking
2465/// pointers. Here are some objectionable examples that GCC considers warnings:
2466///
2467/// int a, *pint;
2468/// short *pshort;
2469/// struct foo *pfoo;
2470///
2471/// pint = pshort; // warning: assignment from incompatible pointer type
2472/// a = pint; // warning: assignment makes integer from pointer without a cast
2473/// pint = a; // warning: assignment makes pointer from integer without a cast
2474/// pint = pfoo; // warning: assignment from incompatible pointer type
2475///
2476/// As a result, the code for dealing with pointers is more complex than the
2477/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002478///
Chris Lattner005ed752008-01-04 18:04:52 +00002479Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002480Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002481 // Get canonical types. We're not formatting these types, just comparing
2482 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002483 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2484 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002485
2486 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002487 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002488
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002489 // If the left-hand side is a reference type, then we are in a
2490 // (rare!) case where we've allowed the use of references in C,
2491 // e.g., as a parameter type in a built-in function. In this case,
2492 // just make sure that the type referenced is compatible with the
2493 // right-hand side type. The caller is responsible for adjusting
2494 // lhsType so that the resulting expression does not have reference
2495 // type.
2496 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2497 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002498 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002499 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002500 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002501
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002502 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2503 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002504 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002505 // Relax integer conversions like we do for pointers below.
2506 if (rhsType->isIntegerType())
2507 return IntToPointer;
2508 if (lhsType->isIntegerType())
2509 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002510 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002511 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002512
Nate Begemanc5f0f652008-07-14 18:02:46 +00002513 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002514 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002515 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2516 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002517 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002518
Nate Begemanc5f0f652008-07-14 18:02:46 +00002519 // If we are allowing lax vector conversions, and LHS and RHS are both
2520 // vectors, the total size only needs to be the same. This is a bitcast;
2521 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002522 if (getLangOptions().LaxVectorConversions &&
2523 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002524 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002525 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002526 }
2527 return Incompatible;
2528 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002529
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002530 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002531 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002532
Chris Lattner390564e2008-04-07 06:49:41 +00002533 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002534 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002535 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002536
Chris Lattner390564e2008-04-07 06:49:41 +00002537 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002538 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002539
Steve Naroffa982c712008-09-29 18:10:17 +00002540 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002541 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002542 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002543
2544 // Treat block pointers as objects.
2545 if (getLangOptions().ObjC1 &&
2546 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2547 return Compatible;
2548 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002549 return Incompatible;
2550 }
2551
2552 if (isa<BlockPointerType>(lhsType)) {
2553 if (rhsType->isIntegerType())
2554 return IntToPointer;
2555
Steve Naroffa982c712008-09-29 18:10:17 +00002556 // Treat block pointers as objects.
2557 if (getLangOptions().ObjC1 &&
2558 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2559 return Compatible;
2560
Steve Naroff3454b6c2008-09-04 15:10:53 +00002561 if (rhsType->isBlockPointerType())
2562 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2563
2564 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2565 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002566 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002567 }
Chris Lattner1853da22008-01-04 23:18:45 +00002568 return Incompatible;
2569 }
2570
Chris Lattner390564e2008-04-07 06:49:41 +00002571 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002572 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002573 if (lhsType == Context.BoolTy)
2574 return Compatible;
2575
2576 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002577 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002578
Chris Lattner390564e2008-04-07 06:49:41 +00002579 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002580 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002581
2582 if (isa<BlockPointerType>(lhsType) &&
2583 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002584 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002585 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002586 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002587
Chris Lattner1853da22008-01-04 23:18:45 +00002588 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002589 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002590 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002591 }
2592 return Incompatible;
2593}
2594
Chris Lattner005ed752008-01-04 18:04:52 +00002595Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002596Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002597 if (getLangOptions().CPlusPlus) {
2598 if (!lhsType->isRecordType()) {
2599 // C++ 5.17p3: If the left operand is not of class type, the
2600 // expression is implicitly converted (C++ 4) to the
2601 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002602 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2603 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002604 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002605 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002606 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002607 }
2608
2609 // FIXME: Currently, we fall through and treat C++ classes like C
2610 // structures.
2611 }
2612
Steve Naroffcdee22d2007-11-27 17:58:44 +00002613 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2614 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002615 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2616 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002617 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002618 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002619 return Compatible;
2620 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002621
2622 // We don't allow conversion of non-null-pointer constants to integers.
2623 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2624 return IntToBlockPointer;
2625
Chris Lattner5f505bf2007-10-16 02:55:40 +00002626 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002627 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002628 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002629 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002630 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002631 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002632 if (!lhsType->isReferenceType())
2633 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002634
Chris Lattner005ed752008-01-04 18:04:52 +00002635 Sema::AssignConvertType result =
2636 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002637
2638 // C99 6.5.16.1p2: The value of the right operand is converted to the
2639 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002640 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2641 // so that we can use references in built-in functions even in C.
2642 // The getNonReferenceType() call makes sure that the resulting expression
2643 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002644 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002645 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002646 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002647}
2648
Chris Lattner005ed752008-01-04 18:04:52 +00002649Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002650Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2651 return CheckAssignmentConstraints(lhsType, rhsType);
2652}
2653
Chris Lattner1eafdea2008-11-18 01:30:42 +00002654QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002655 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002656 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002657 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002658 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002659}
2660
Chris Lattner1eafdea2008-11-18 01:30:42 +00002661inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002662 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002663 // For conversion purposes, we ignore any qualifiers.
2664 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002665 QualType lhsType =
2666 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2667 QualType rhsType =
2668 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002669
Nate Begemanc5f0f652008-07-14 18:02:46 +00002670 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002671 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002672 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002673
Nate Begemanc5f0f652008-07-14 18:02:46 +00002674 // Handle the case of a vector & extvector type of the same size and element
2675 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00002676 if (getLangOptions().LaxVectorConversions) {
2677 // FIXME: Should we warn here?
2678 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002679 if (const VectorType *RV = rhsType->getAsVectorType())
2680 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00002681 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002682 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00002683 }
2684 }
2685 }
2686
Nate Begemanc5f0f652008-07-14 18:02:46 +00002687 // If the lhs is an extended vector and the rhs is a scalar of the same type
2688 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002689 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002690 QualType eltType = V->getElementType();
2691
2692 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2693 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2694 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002695 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002696 return lhsType;
2697 }
2698 }
2699
Nate Begemanc5f0f652008-07-14 18:02:46 +00002700 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002701 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002702 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002703 QualType eltType = V->getElementType();
2704
2705 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2706 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2707 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002708 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002709 return rhsType;
2710 }
2711 }
2712
Chris Lattner4b009652007-07-25 00:24:17 +00002713 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002714 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002715 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002716 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002717 return QualType();
2718}
2719
2720inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002721 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002722{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002723 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002724 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002725
Steve Naroff8f708362007-08-24 19:07:16 +00002726 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002727
Chris Lattner4b009652007-07-25 00:24:17 +00002728 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002729 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002730 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002731}
2732
2733inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002734 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002735{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002736 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2737 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2738 return CheckVectorOperands(Loc, lex, rex);
2739 return InvalidOperands(Loc, lex, rex);
2740 }
Chris Lattner4b009652007-07-25 00:24:17 +00002741
Steve Naroff8f708362007-08-24 19:07:16 +00002742 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002743
Chris Lattner4b009652007-07-25 00:24:17 +00002744 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002745 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002746 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002747}
2748
2749inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002750 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002751{
2752 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002753 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002754
Steve Naroff8f708362007-08-24 19:07:16 +00002755 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002756
Chris Lattner4b009652007-07-25 00:24:17 +00002757 // handle the common case first (both operands are arithmetic).
2758 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002759 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002760
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002761 // Put any potential pointer into PExp
2762 Expr* PExp = lex, *IExp = rex;
2763 if (IExp->getType()->isPointerType())
2764 std::swap(PExp, IExp);
2765
2766 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2767 if (IExp->getType()->isIntegerType()) {
2768 // Check for arithmetic on pointers to incomplete types
2769 if (!PTy->getPointeeType()->isObjectType()) {
2770 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002771 if (getLangOptions().CPlusPlus) {
2772 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2773 << lex->getSourceRange() << rex->getSourceRange();
2774 return QualType();
2775 }
2776
2777 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00002778 Diag(Loc, diag::ext_gnu_void_ptr)
2779 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002780 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002781 if (getLangOptions().CPlusPlus) {
2782 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2783 << lex->getType() << lex->getSourceRange();
2784 return QualType();
2785 }
2786
2787 // GNU extension: arithmetic on pointer to function
2788 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002789 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002790 } else {
2791 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2792 diag::err_typecheck_arithmetic_incomplete_type,
2793 lex->getSourceRange(), SourceRange(),
2794 lex->getType());
2795 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002796 }
2797 }
2798 return PExp->getType();
2799 }
2800 }
2801
Chris Lattner1eafdea2008-11-18 01:30:42 +00002802 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002803}
2804
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002805// C99 6.5.6
2806QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002807 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002808 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002809 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002810
Steve Naroff8f708362007-08-24 19:07:16 +00002811 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002812
Chris Lattnerf6da2912007-12-09 21:53:25 +00002813 // Enforce type constraints: C99 6.5.6p3.
2814
2815 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002816 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002817 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002818
2819 // Either ptr - int or ptr - ptr.
2820 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002821 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002822
Chris Lattnerf6da2912007-12-09 21:53:25 +00002823 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002824 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002825 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002826 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002827 Diag(Loc, diag::ext_gnu_void_ptr)
2828 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00002829 } else if (lpointee->isFunctionType()) {
2830 if (getLangOptions().CPlusPlus) {
2831 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2832 << lex->getType() << lex->getSourceRange();
2833 return QualType();
2834 }
2835
2836 // GNU extension: arithmetic on pointer to function
2837 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2838 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002839 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002840 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002841 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002842 return QualType();
2843 }
2844 }
2845
2846 // The result type of a pointer-int computation is the pointer type.
2847 if (rex->getType()->isIntegerType())
2848 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002849
Chris Lattnerf6da2912007-12-09 21:53:25 +00002850 // Handle pointer-pointer subtractions.
2851 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002852 QualType rpointee = RHSPTy->getPointeeType();
2853
Chris Lattnerf6da2912007-12-09 21:53:25 +00002854 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002855 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002856 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002857 if (rpointee->isVoidType()) {
2858 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002859 Diag(Loc, diag::ext_gnu_void_ptr)
2860 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00002861 } else if (rpointee->isFunctionType()) {
2862 if (getLangOptions().CPlusPlus) {
2863 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2864 << rex->getType() << rex->getSourceRange();
2865 return QualType();
2866 }
2867
2868 // GNU extension: arithmetic on pointer to function
2869 if (!lpointee->isFunctionType())
2870 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2871 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002872 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002873 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002874 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002875 return QualType();
2876 }
2877 }
2878
2879 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002880 if (!Context.typesAreCompatible(
2881 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2882 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002883 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002884 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002885 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002886 return QualType();
2887 }
2888
2889 return Context.getPointerDiffType();
2890 }
2891 }
2892
Chris Lattner1eafdea2008-11-18 01:30:42 +00002893 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002894}
2895
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002896// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002897QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002898 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002899 // C99 6.5.7p2: Each of the operands shall have integer type.
2900 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002901 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002902
Chris Lattner2c8bff72007-12-12 05:47:28 +00002903 // Shifts don't perform usual arithmetic conversions, they just do integer
2904 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002905 if (!isCompAssign)
2906 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002907 UsualUnaryConversions(rex);
2908
2909 // "The type of the result is that of the promoted left operand."
2910 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002911}
2912
Eli Friedman0d9549b2008-08-22 00:56:42 +00002913static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2914 ASTContext& Context) {
2915 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2916 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2917 // ID acts sort of like void* for ObjC interfaces
2918 if (LHSIface && Context.isObjCIdType(RHS))
2919 return true;
2920 if (RHSIface && Context.isObjCIdType(LHS))
2921 return true;
2922 if (!LHSIface || !RHSIface)
2923 return false;
2924 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2925 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2926}
2927
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002928// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002929QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002930 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002931 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002932 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002933
Chris Lattner254f3bc2007-08-26 01:18:55 +00002934 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002935 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2936 UsualArithmeticConversions(lex, rex);
2937 else {
2938 UsualUnaryConversions(lex);
2939 UsualUnaryConversions(rex);
2940 }
Chris Lattner4b009652007-07-25 00:24:17 +00002941 QualType lType = lex->getType();
2942 QualType rType = rex->getType();
2943
Ted Kremenek486509e2007-10-29 17:13:39 +00002944 // For non-floating point types, check for self-comparisons of the form
2945 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2946 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002947 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002948 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2949 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002950 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002951 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002952 }
2953
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002954 // The result of comparisons is 'bool' in C++, 'int' in C.
2955 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2956
Chris Lattner254f3bc2007-08-26 01:18:55 +00002957 if (isRelational) {
2958 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002959 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002960 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002961 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002962 if (lType->isFloatingType()) {
2963 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002964 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002965 }
2966
Chris Lattner254f3bc2007-08-26 01:18:55 +00002967 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002968 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002969 }
Chris Lattner4b009652007-07-25 00:24:17 +00002970
Chris Lattner22be8422007-08-26 01:10:14 +00002971 bool LHSIsNull = lex->isNullPointerConstant(Context);
2972 bool RHSIsNull = rex->isNullPointerConstant(Context);
2973
Chris Lattner254f3bc2007-08-26 01:18:55 +00002974 // All of the following pointer related warnings are GCC extensions, except
2975 // when handling null pointer constants. One day, we can consider making them
2976 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002977 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002978 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002979 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002980 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002981 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002982
Steve Naroff3b435622007-11-13 14:57:38 +00002983 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002984 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2985 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002986 RCanPointeeTy.getUnqualifiedType()) &&
2987 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002988 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002989 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002990 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002991 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002992 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002993 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002994 // Handle block pointer types.
2995 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2996 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2997 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2998
2999 if (!LHSIsNull && !RHSIsNull &&
3000 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003001 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003002 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003003 }
3004 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003005 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003006 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003007 // Allow block pointers to be compared with null pointer constants.
3008 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3009 (lType->isPointerType() && rType->isBlockPointerType())) {
3010 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003011 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003012 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003013 }
3014 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003015 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003016 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003017
Steve Naroff936c4362008-06-03 14:04:54 +00003018 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003019 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003020 const PointerType *LPT = lType->getAsPointerType();
3021 const PointerType *RPT = rType->getAsPointerType();
3022 bool LPtrToVoid = LPT ?
3023 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
3024 bool RPtrToVoid = RPT ?
3025 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
3026
3027 if (!LPtrToVoid && !RPtrToVoid &&
3028 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003029 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003030 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003031 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003032 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003033 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003034 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003035 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003036 }
Steve Naroff936c4362008-06-03 14:04:54 +00003037 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3038 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003039 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003040 } else {
3041 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003042 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003043 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003044 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003045 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003046 }
Steve Naroff936c4362008-06-03 14:04:54 +00003047 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003048 }
Steve Naroff936c4362008-06-03 14:04:54 +00003049 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
3050 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003051 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003052 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003053 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003054 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003055 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003056 }
Steve Naroff936c4362008-06-03 14:04:54 +00003057 if (lType->isIntegerType() &&
3058 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003059 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003060 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003061 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003062 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003063 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003064 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003065 // Handle block pointers.
3066 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3067 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003068 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003069 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003070 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003071 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003072 }
3073 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3074 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003075 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003076 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003077 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003078 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003079 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003080 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003081}
3082
Nate Begemanc5f0f652008-07-14 18:02:46 +00003083/// CheckVectorCompareOperands - vector comparisons are a clang extension that
3084/// operates on extended vector types. Instead of producing an IntTy result,
3085/// like a scalar comparison, a vector comparison produces a vector of integer
3086/// types.
3087QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003088 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003089 bool isRelational) {
3090 // Check to make sure we're operating on vectors of the same type and width,
3091 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003092 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003093 if (vType.isNull())
3094 return vType;
3095
3096 QualType lType = lex->getType();
3097 QualType rType = rex->getType();
3098
3099 // For non-floating point types, check for self-comparisons of the form
3100 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3101 // often indicate logic errors in the program.
3102 if (!lType->isFloatingType()) {
3103 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3104 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3105 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003106 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003107 }
3108
3109 // Check for comparisons of floating point operands using != and ==.
3110 if (!isRelational && lType->isFloatingType()) {
3111 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003112 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003113 }
3114
3115 // Return the type for the comparison, which is the same as vector type for
3116 // integer vectors, or an integer type of identical size and number of
3117 // elements for floating point vectors.
3118 if (lType->isIntegerType())
3119 return lType;
3120
3121 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003122 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003123 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003124 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003125 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3126 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3127
3128 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3129 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003130 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3131}
3132
Chris Lattner4b009652007-07-25 00:24:17 +00003133inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00003134 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003135{
3136 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003137 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003138
Steve Naroff8f708362007-08-24 19:07:16 +00003139 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00003140
3141 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003142 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003143 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003144}
3145
3146inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00003147 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003148{
3149 UsualUnaryConversions(lex);
3150 UsualUnaryConversions(rex);
3151
Eli Friedmanbea3f842008-05-13 20:16:47 +00003152 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003153 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003154 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003155}
3156
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003157/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3158/// is a read-only property; return true if so. A readonly property expression
3159/// depends on various declarations and thus must be treated specially.
3160///
3161static bool IsReadonlyProperty(Expr *E, Sema &S)
3162{
3163 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3164 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3165 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3166 QualType BaseType = PropExpr->getBase()->getType();
3167 if (const PointerType *PTy = BaseType->getAsPointerType())
3168 if (const ObjCInterfaceType *IFTy =
3169 PTy->getPointeeType()->getAsObjCInterfaceType())
3170 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3171 if (S.isPropertyReadonly(PDecl, IFace))
3172 return true;
3173 }
3174 }
3175 return false;
3176}
3177
Chris Lattner4c2642c2008-11-18 01:22:49 +00003178/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3179/// emit an error and return true. If so, return false.
3180static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003181 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3182 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3183 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003184 if (IsLV == Expr::MLV_Valid)
3185 return false;
3186
3187 unsigned Diag = 0;
3188 bool NeedType = false;
3189 switch (IsLV) { // C99 6.5.16p2
3190 default: assert(0 && "Unknown result from isModifiableLvalue!");
3191 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00003192 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003193 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3194 NeedType = true;
3195 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003196 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003197 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3198 NeedType = true;
3199 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003200 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003201 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3202 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003203 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003204 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3205 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003206 case Expr::MLV_IncompleteType:
3207 case Expr::MLV_IncompleteVoidType:
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003208 return S.DiagnoseIncompleteType(Loc, E->getType(),
3209 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3210 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003211 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003212 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3213 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003214 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003215 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3216 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003217 case Expr::MLV_ReadonlyProperty:
3218 Diag = diag::error_readonly_property_assignment;
3219 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003220 case Expr::MLV_NoSetterProperty:
3221 Diag = diag::error_nosetter_property_assignment;
3222 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003223 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003224
Chris Lattner4c2642c2008-11-18 01:22:49 +00003225 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003226 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003227 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003228 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003229 return true;
3230}
3231
3232
3233
3234// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003235QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3236 SourceLocation Loc,
3237 QualType CompoundType) {
3238 // Verify that LHS is a modifiable lvalue, and emit error if not.
3239 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003240 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003241
3242 QualType LHSType = LHS->getType();
3243 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003244
Chris Lattner005ed752008-01-04 18:04:52 +00003245 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003246 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003247 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003248 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003249 // Special case of NSObject attributes on c-style pointer types.
3250 if (ConvTy == IncompatiblePointer &&
3251 ((Context.isObjCNSObjectType(LHSType) &&
3252 Context.isObjCObjectPointerType(RHSType)) ||
3253 (Context.isObjCNSObjectType(RHSType) &&
3254 Context.isObjCObjectPointerType(LHSType))))
3255 ConvTy = Compatible;
3256
Chris Lattner34c85082008-08-21 18:04:13 +00003257 // If the RHS is a unary plus or minus, check to see if they = and + are
3258 // right next to each other. If so, the user may have typo'd "x =+ 4"
3259 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003260 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003261 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3262 RHSCheck = ICE->getSubExpr();
3263 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3264 if ((UO->getOpcode() == UnaryOperator::Plus ||
3265 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003266 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003267 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003268 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003269 Diag(Loc, diag::warn_not_compound_assign)
3270 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3271 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003272 }
3273 } else {
3274 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003275 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003276 }
Chris Lattner005ed752008-01-04 18:04:52 +00003277
Chris Lattner1eafdea2008-11-18 01:30:42 +00003278 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3279 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003280 return QualType();
3281
Chris Lattner4b009652007-07-25 00:24:17 +00003282 // C99 6.5.16p3: The type of an assignment expression is the type of the
3283 // left operand unless the left operand has qualified type, in which case
3284 // it is the unqualified version of the type of the left operand.
3285 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3286 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003287 // C++ 5.17p1: the type of the assignment expression is that of its left
3288 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003289 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003290}
3291
Chris Lattner1eafdea2008-11-18 01:30:42 +00003292// C99 6.5.17
3293QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3294 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00003295
3296 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003297 DefaultFunctionArrayConversion(RHS);
3298 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003299}
3300
3301/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3302/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003303QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3304 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003305 QualType ResType = Op->getType();
3306 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003307
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003308 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3309 // Decrement of bool is not allowed.
3310 if (!isInc) {
3311 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3312 return QualType();
3313 }
3314 // Increment of bool sets it to true, but is deprecated.
3315 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3316 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003317 // OK!
3318 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3319 // C99 6.5.2.4p2, 6.5.6p2
3320 if (PT->getPointeeType()->isObjectType()) {
3321 // Pointer to object is ok!
3322 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003323 if (getLangOptions().CPlusPlus) {
3324 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3325 << Op->getSourceRange();
3326 return QualType();
3327 }
3328
3329 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003330 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003331 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003332 if (getLangOptions().CPlusPlus) {
3333 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3334 << Op->getType() << Op->getSourceRange();
3335 return QualType();
3336 }
3337
3338 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003339 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003340 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003341 } else {
3342 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3343 diag::err_typecheck_arithmetic_incomplete_type,
3344 Op->getSourceRange(), SourceRange(),
3345 ResType);
3346 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003347 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003348 } else if (ResType->isComplexType()) {
3349 // C99 does not support ++/-- on complex types, we allow as an extension.
3350 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003351 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003352 } else {
3353 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003354 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003355 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003356 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00003357 // At this point, we know we have a real, complex or pointer type.
3358 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003359 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003360 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003361 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003362}
3363
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003364/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003365/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003366/// where the declaration is needed for type checking. We only need to
3367/// handle cases when the expression references a function designator
3368/// or is an lvalue. Here are some examples:
3369/// - &(x) => x
3370/// - &*****f => f for f a function designator.
3371/// - &s.xx => s
3372/// - &s.zz[1].yy -> s, if zz is an array
3373/// - *(x + 1) -> x, if x is an array
3374/// - &"123"[2] -> 0
3375/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003376static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003377 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003378 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003379 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003380 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003381 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003382 // Fields cannot be declared with a 'register' storage class.
3383 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003384 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003385 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003386 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003387 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003388 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003389
Douglas Gregord2baafd2008-10-21 16:13:35 +00003390 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003391 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003392 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003393 return 0;
3394 else
3395 return VD;
3396 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003397 case Stmt::UnaryOperatorClass: {
3398 UnaryOperator *UO = cast<UnaryOperator>(E);
3399
3400 switch(UO->getOpcode()) {
3401 case UnaryOperator::Deref: {
3402 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003403 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3404 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3405 if (!VD || VD->getType()->isPointerType())
3406 return 0;
3407 return VD;
3408 }
3409 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003410 }
3411 case UnaryOperator::Real:
3412 case UnaryOperator::Imag:
3413 case UnaryOperator::Extension:
3414 return getPrimaryDecl(UO->getSubExpr());
3415 default:
3416 return 0;
3417 }
3418 }
3419 case Stmt::BinaryOperatorClass: {
3420 BinaryOperator *BO = cast<BinaryOperator>(E);
3421
3422 // Handle cases involving pointer arithmetic. The result of an
3423 // Assign or AddAssign is not an lvalue so they can be ignored.
3424
3425 // (x + n) or (n + x) => x
3426 if (BO->getOpcode() == BinaryOperator::Add) {
3427 if (BO->getLHS()->getType()->isPointerType()) {
3428 return getPrimaryDecl(BO->getLHS());
3429 } else if (BO->getRHS()->getType()->isPointerType()) {
3430 return getPrimaryDecl(BO->getRHS());
3431 }
3432 }
3433
3434 return 0;
3435 }
Chris Lattner4b009652007-07-25 00:24:17 +00003436 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003437 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003438 case Stmt::ImplicitCastExprClass:
3439 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003440 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003441 default:
3442 return 0;
3443 }
3444}
3445
3446/// CheckAddressOfOperand - The operand of & must be either a function
3447/// designator or an lvalue designating an object. If it is an lvalue, the
3448/// object cannot be declared with storage class register or be a bit field.
3449/// Note: The usual conversions are *not* applied to the operand of the &
3450/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00003451/// In C++, the operand might be an overloaded function name, in which case
3452/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003453QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003454 if (op->isTypeDependent())
3455 return Context.DependentTy;
3456
Steve Naroff9c6c3592008-01-13 17:10:08 +00003457 if (getLangOptions().C99) {
3458 // Implement C99-only parts of addressof rules.
3459 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3460 if (uOp->getOpcode() == UnaryOperator::Deref)
3461 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3462 // (assuming the deref expression is valid).
3463 return uOp->getSubExpr()->getType();
3464 }
3465 // Technically, there should be a check for array subscript
3466 // expressions here, but the result of one is always an lvalue anyway.
3467 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003468 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003469 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003470
Chris Lattner4b009652007-07-25 00:24:17 +00003471 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003472 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3473 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003474 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3475 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003476 return QualType();
3477 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003478 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003479 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3480 if (Field->isBitField()) {
3481 Diag(OpLoc, diag::err_typecheck_address_of)
3482 << "bit-field" << op->getSourceRange();
3483 return QualType();
3484 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003485 }
3486 // Check for Apple extension for accessing vector components.
3487 } else if (isa<ArraySubscriptExpr>(op) &&
3488 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003489 Diag(OpLoc, diag::err_typecheck_address_of)
3490 << "vector" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003491 return QualType();
3492 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00003493 // We have an lvalue with a decl. Make sure the decl is not declared
3494 // with the register storage-class specifier.
3495 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3496 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003497 Diag(OpLoc, diag::err_typecheck_address_of)
3498 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003499 return QualType();
3500 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003501 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003502 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003503 } else if (isa<FieldDecl>(dcl)) {
3504 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00003505 // Could be a pointer to member, though, if there is an explicit
3506 // scope qualifier for the class.
3507 if (isa<QualifiedDeclRefExpr>(op)) {
3508 DeclContext *Ctx = dcl->getDeclContext();
3509 if (Ctx && Ctx->isRecord())
3510 return Context.getMemberPointerType(op->getType(),
3511 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3512 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003513 } else if (isa<FunctionDecl>(dcl)) {
3514 // Okay: we can take the address of a function.
Douglas Gregor5b82d612008-12-10 21:26:49 +00003515 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003516 else
Chris Lattner4b009652007-07-25 00:24:17 +00003517 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003518 }
Chris Lattnera55e3212008-07-27 00:48:22 +00003519
Chris Lattner4b009652007-07-25 00:24:17 +00003520 // If the operand has type "type", the result has type "pointer to type".
3521 return Context.getPointerType(op->getType());
3522}
3523
Chris Lattnerda5c0872008-11-23 09:13:29 +00003524QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3525 UsualUnaryConversions(Op);
3526 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003527
Chris Lattnerda5c0872008-11-23 09:13:29 +00003528 // Note that per both C89 and C99, this is always legal, even if ptype is an
3529 // incomplete type or void. It would be possible to warn about dereferencing
3530 // a void pointer, but it's completely well-defined, and such a warning is
3531 // unlikely to catch any mistakes.
3532 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003533 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00003534
Chris Lattner77d52da2008-11-20 06:06:08 +00003535 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003536 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003537 return QualType();
3538}
3539
3540static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3541 tok::TokenKind Kind) {
3542 BinaryOperator::Opcode Opc;
3543 switch (Kind) {
3544 default: assert(0 && "Unknown binop!");
3545 case tok::star: Opc = BinaryOperator::Mul; break;
3546 case tok::slash: Opc = BinaryOperator::Div; break;
3547 case tok::percent: Opc = BinaryOperator::Rem; break;
3548 case tok::plus: Opc = BinaryOperator::Add; break;
3549 case tok::minus: Opc = BinaryOperator::Sub; break;
3550 case tok::lessless: Opc = BinaryOperator::Shl; break;
3551 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3552 case tok::lessequal: Opc = BinaryOperator::LE; break;
3553 case tok::less: Opc = BinaryOperator::LT; break;
3554 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3555 case tok::greater: Opc = BinaryOperator::GT; break;
3556 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3557 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3558 case tok::amp: Opc = BinaryOperator::And; break;
3559 case tok::caret: Opc = BinaryOperator::Xor; break;
3560 case tok::pipe: Opc = BinaryOperator::Or; break;
3561 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3562 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3563 case tok::equal: Opc = BinaryOperator::Assign; break;
3564 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3565 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3566 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3567 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3568 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3569 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3570 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3571 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3572 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3573 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3574 case tok::comma: Opc = BinaryOperator::Comma; break;
3575 }
3576 return Opc;
3577}
3578
3579static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3580 tok::TokenKind Kind) {
3581 UnaryOperator::Opcode Opc;
3582 switch (Kind) {
3583 default: assert(0 && "Unknown unary op!");
3584 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3585 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3586 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3587 case tok::star: Opc = UnaryOperator::Deref; break;
3588 case tok::plus: Opc = UnaryOperator::Plus; break;
3589 case tok::minus: Opc = UnaryOperator::Minus; break;
3590 case tok::tilde: Opc = UnaryOperator::Not; break;
3591 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003592 case tok::kw___real: Opc = UnaryOperator::Real; break;
3593 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3594 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3595 }
3596 return Opc;
3597}
3598
Douglas Gregord7f915e2008-11-06 23:29:22 +00003599/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3600/// operator @p Opc at location @c TokLoc. This routine only supports
3601/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003602Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3603 unsigned Op,
3604 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003605 QualType ResultTy; // Result type of the binary operator.
3606 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3607 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3608
3609 switch (Opc) {
3610 default:
3611 assert(0 && "Unknown binary expr!");
3612 case BinaryOperator::Assign:
3613 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3614 break;
3615 case BinaryOperator::Mul:
3616 case BinaryOperator::Div:
3617 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3618 break;
3619 case BinaryOperator::Rem:
3620 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3621 break;
3622 case BinaryOperator::Add:
3623 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3624 break;
3625 case BinaryOperator::Sub:
3626 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3627 break;
3628 case BinaryOperator::Shl:
3629 case BinaryOperator::Shr:
3630 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3631 break;
3632 case BinaryOperator::LE:
3633 case BinaryOperator::LT:
3634 case BinaryOperator::GE:
3635 case BinaryOperator::GT:
3636 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3637 break;
3638 case BinaryOperator::EQ:
3639 case BinaryOperator::NE:
3640 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3641 break;
3642 case BinaryOperator::And:
3643 case BinaryOperator::Xor:
3644 case BinaryOperator::Or:
3645 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3646 break;
3647 case BinaryOperator::LAnd:
3648 case BinaryOperator::LOr:
3649 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3650 break;
3651 case BinaryOperator::MulAssign:
3652 case BinaryOperator::DivAssign:
3653 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3654 if (!CompTy.isNull())
3655 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3656 break;
3657 case BinaryOperator::RemAssign:
3658 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3659 if (!CompTy.isNull())
3660 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3661 break;
3662 case BinaryOperator::AddAssign:
3663 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3664 if (!CompTy.isNull())
3665 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3666 break;
3667 case BinaryOperator::SubAssign:
3668 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3669 if (!CompTy.isNull())
3670 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3671 break;
3672 case BinaryOperator::ShlAssign:
3673 case BinaryOperator::ShrAssign:
3674 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3675 if (!CompTy.isNull())
3676 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3677 break;
3678 case BinaryOperator::AndAssign:
3679 case BinaryOperator::XorAssign:
3680 case BinaryOperator::OrAssign:
3681 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3682 if (!CompTy.isNull())
3683 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3684 break;
3685 case BinaryOperator::Comma:
3686 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3687 break;
3688 }
3689 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003690 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00003691 if (CompTy.isNull())
3692 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3693 else
3694 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Steve Naroff8b9a98d2009-01-20 21:06:31 +00003695 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003696}
3697
Chris Lattner4b009652007-07-25 00:24:17 +00003698// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003699Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3700 tok::TokenKind Kind,
3701 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003702 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003703 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003704
Steve Naroff87d58b42007-09-16 03:34:24 +00003705 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3706 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003707
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003708 // If either expression is type-dependent, just build the AST.
3709 // FIXME: We'll need to perform some caching of the result of name
3710 // lookup for operator+.
3711 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff774e4152009-01-21 00:14:39 +00003712 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3713 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003714 Context.DependentTy,
3715 Context.DependentTy, TokLoc));
Steve Naroff774e4152009-01-21 00:14:39 +00003716 else
3717 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, Context.DependentTy,
3718 TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003719 }
3720
Douglas Gregord7f915e2008-11-06 23:29:22 +00003721 if (getLangOptions().CPlusPlus &&
3722 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3723 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003724 // If this is one of the assignment operators, we only perform
3725 // overload resolution if the left-hand side is a class or
3726 // enumeration type (C++ [expr.ass]p3).
3727 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3728 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3729 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3730 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003731
Douglas Gregord7f915e2008-11-06 23:29:22 +00003732 // Determine which overloaded operator we're dealing with.
3733 static const OverloadedOperatorKind OverOps[] = {
3734 OO_Star, OO_Slash, OO_Percent,
3735 OO_Plus, OO_Minus,
3736 OO_LessLess, OO_GreaterGreater,
3737 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3738 OO_EqualEqual, OO_ExclaimEqual,
3739 OO_Amp,
3740 OO_Caret,
3741 OO_Pipe,
3742 OO_AmpAmp,
3743 OO_PipePipe,
3744 OO_Equal, OO_StarEqual,
3745 OO_SlashEqual, OO_PercentEqual,
3746 OO_PlusEqual, OO_MinusEqual,
3747 OO_LessLessEqual, OO_GreaterGreaterEqual,
3748 OO_AmpEqual, OO_CaretEqual,
3749 OO_PipeEqual,
3750 OO_Comma
3751 };
3752 OverloadedOperatorKind OverOp = OverOps[Opc];
3753
Douglas Gregor5ed15042008-11-18 23:14:02 +00003754 // Add the appropriate overloaded operators (C++ [over.match.oper])
3755 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003756 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003757 Expr *Args[2] = { lhs, rhs };
Douglas Gregor5ed15042008-11-18 23:14:02 +00003758 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregord7f915e2008-11-06 23:29:22 +00003759
3760 // Perform overload resolution.
3761 OverloadCandidateSet::iterator Best;
3762 switch (BestViableFunction(CandidateSet, Best)) {
3763 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003764 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003765 FunctionDecl *FnDecl = Best->Function;
3766
Douglas Gregor70d26122008-11-12 17:17:38 +00003767 if (FnDecl) {
3768 // We matched an overloaded operator. Build a call to that
3769 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003770
Douglas Gregor70d26122008-11-12 17:17:38 +00003771 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003772 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3773 if (PerformObjectArgumentInitialization(lhs, Method) ||
3774 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3775 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003776 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003777 } else {
3778 // Convert the arguments.
3779 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3780 "passing") ||
3781 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3782 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003783 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003784 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003785
Douglas Gregor70d26122008-11-12 17:17:38 +00003786 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003787 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003788 = FnDecl->getType()->getAsFunctionType()->getResultType();
3789 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003790
Douglas Gregor70d26122008-11-12 17:17:38 +00003791 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003792 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3793 SourceLocation());
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003794 UsualUnaryConversions(FnExpr);
3795
Steve Naroff774e4152009-01-21 00:14:39 +00003796 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, Args, 2,
3797 ResultTy, TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003798 } else {
3799 // We matched a built-in operator. Convert the arguments, then
3800 // break out so that we will build the appropriate built-in
3801 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003802 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3803 Best->Conversions[0], "passing") ||
3804 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3805 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003806 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003807
3808 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003809 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003810 }
3811
3812 case OR_No_Viable_Function:
3813 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003814 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003815 break;
3816
3817 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003818 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3819 << BinaryOperator::getOpcodeStr(Opc)
3820 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003821 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003822 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003823 }
3824
Douglas Gregor70d26122008-11-12 17:17:38 +00003825 // Either we found no viable overloaded operator or we matched a
3826 // built-in operator. In either case, fall through to trying to
3827 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003828 }
3829
Douglas Gregord7f915e2008-11-06 23:29:22 +00003830 // Build a built-in binary operation.
3831 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003832}
3833
3834// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00003835Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3836 tok::TokenKind Op, ExprArg input) {
3837 // FIXME: Input is modified later, but smart pointer not reassigned.
3838 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00003839 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003840
3841 if (getLangOptions().CPlusPlus &&
3842 (Input->getType()->isRecordType()
3843 || Input->getType()->isEnumeralType())) {
3844 // Determine which overloaded operator we're dealing with.
3845 static const OverloadedOperatorKind OverOps[] = {
3846 OO_None, OO_None,
3847 OO_PlusPlus, OO_MinusMinus,
3848 OO_Amp, OO_Star,
3849 OO_Plus, OO_Minus,
3850 OO_Tilde, OO_Exclaim,
3851 OO_None, OO_None,
3852 OO_None,
3853 OO_None
3854 };
3855 OverloadedOperatorKind OverOp = OverOps[Opc];
3856
3857 // Add the appropriate overloaded operators (C++ [over.match.oper])
3858 // to the candidate set.
3859 OverloadCandidateSet CandidateSet;
3860 if (OverOp != OO_None)
3861 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3862
3863 // Perform overload resolution.
3864 OverloadCandidateSet::iterator Best;
3865 switch (BestViableFunction(CandidateSet, Best)) {
3866 case OR_Success: {
3867 // We found a built-in operator or an overloaded operator.
3868 FunctionDecl *FnDecl = Best->Function;
3869
3870 if (FnDecl) {
3871 // We matched an overloaded operator. Build a call to that
3872 // operator.
3873
3874 // Convert the arguments.
3875 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3876 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00003877 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003878 } else {
3879 // Convert the arguments.
3880 if (PerformCopyInitialization(Input,
3881 FnDecl->getParamDecl(0)->getType(),
3882 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003883 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003884 }
3885
3886 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00003887 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003888 = FnDecl->getType()->getAsFunctionType()->getResultType();
3889 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00003890
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003891 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003892 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3893 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003894 UsualUnaryConversions(FnExpr);
3895
Sebastian Redl8b769972009-01-19 00:08:26 +00003896 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00003897 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, &Input, 1,
3898 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003899 } else {
3900 // We matched a built-in operator. Convert the arguments, then
3901 // break out so that we will build the appropriate built-in
3902 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003903 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3904 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003905 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003906
3907 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00003908 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003909 }
3910
3911 case OR_No_Viable_Function:
3912 // No viable function; fall through to handling this as a
3913 // built-in operator, which will produce an error message for us.
3914 break;
3915
3916 case OR_Ambiguous:
3917 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3918 << UnaryOperator::getOpcodeStr(Opc)
3919 << Input->getSourceRange();
3920 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00003921 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003922 }
3923
3924 // Either we found no viable overloaded operator or we matched a
3925 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00003926 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003927 }
3928
Chris Lattner4b009652007-07-25 00:24:17 +00003929 QualType resultType;
3930 switch (Opc) {
3931 default:
3932 assert(0 && "Unimplemented unary expr!");
3933 case UnaryOperator::PreInc:
3934 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003935 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3936 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00003937 break;
3938 case UnaryOperator::AddrOf:
3939 resultType = CheckAddressOfOperand(Input, OpLoc);
3940 break;
3941 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00003942 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00003943 resultType = CheckIndirectionOperand(Input, OpLoc);
3944 break;
3945 case UnaryOperator::Plus:
3946 case UnaryOperator::Minus:
3947 UsualUnaryConversions(Input);
3948 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003949 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3950 break;
3951 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3952 resultType->isEnumeralType())
3953 break;
3954 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3955 Opc == UnaryOperator::Plus &&
3956 resultType->isPointerType())
3957 break;
3958
Sebastian Redl8b769972009-01-19 00:08:26 +00003959 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3960 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003961 case UnaryOperator::Not: // bitwise complement
3962 UsualUnaryConversions(Input);
3963 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00003964 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3965 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3966 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00003967 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003968 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00003969 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00003970 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3971 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003972 break;
3973 case UnaryOperator::LNot: // logical negation
3974 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
3975 DefaultFunctionArrayConversion(Input);
3976 resultType = Input->getType();
3977 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00003978 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3979 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003980 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00003981 // In C++, it's bool. C++ 5.3.1p8
3982 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003983 break;
Chris Lattner03931a72007-08-24 21:16:53 +00003984 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00003985 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00003986 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00003987 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003988 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00003989 resultType = Input->getType();
3990 break;
3991 }
3992 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00003993 return ExprError();
3994 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00003995 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00003996}
3997
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003998/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3999Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00004000 SourceLocation LabLoc,
4001 IdentifierInfo *LabelII) {
4002 // Look up the record for this label identifier.
4003 LabelStmt *&LabelDecl = LabelMap[LabelII];
4004
Daniel Dunbar879788d2008-08-04 16:51:22 +00004005 // If we haven't seen this label yet, create a forward reference. It
4006 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00004007 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004008 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00004009
4010 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff774e4152009-01-21 00:14:39 +00004011 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4012 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00004013}
4014
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004015Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00004016 SourceLocation RPLoc) { // "({..})"
4017 Stmt *SubStmt = static_cast<Stmt*>(substmt);
4018 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4019 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4020
Eli Friedmanbc941e12009-01-24 23:09:00 +00004021 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4022 if (isFileScope) {
4023 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4024 }
4025
Chris Lattner4b009652007-07-25 00:24:17 +00004026 // FIXME: there are a variety of strange constraints to enforce here, for
4027 // example, it is not possible to goto into a stmt expression apparently.
4028 // More semantic analysis is needed.
4029
4030 // FIXME: the last statement in the compount stmt has its value used. We
4031 // should not warn about it being unused.
4032
4033 // If there are sub stmts in the compound stmt, take the type of the last one
4034 // as the type of the stmtexpr.
4035 QualType Ty = Context.VoidTy;
4036
Chris Lattner200964f2008-07-26 19:51:01 +00004037 if (!Compound->body_empty()) {
4038 Stmt *LastStmt = Compound->body_back();
4039 // If LastStmt is a label, skip down through into the body.
4040 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4041 LastStmt = Label->getSubStmt();
4042
4043 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004044 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004045 }
Chris Lattner4b009652007-07-25 00:24:17 +00004046
Steve Naroff774e4152009-01-21 00:14:39 +00004047 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00004048}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004049
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004050Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4051 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004052 SourceLocation TypeLoc,
4053 TypeTy *argty,
4054 OffsetOfComponent *CompPtr,
4055 unsigned NumComponents,
4056 SourceLocation RPLoc) {
4057 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4058 assert(!ArgTy.isNull() && "Missing type argument!");
4059
4060 // We must have at least one component that refers to the type, and the first
4061 // one is known to be a field designator. Verify that the ArgTy represents
4062 // a struct/union/class.
4063 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00004064 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004065
4066 // Otherwise, create a compound literal expression as the base, and
4067 // iteratively process the offsetof designators.
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004068 InitListExpr *IList =
Douglas Gregorf603b472009-01-28 21:54:33 +00004069 new (Context) InitListExpr(SourceLocation(), 0, 0, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004070 IList->setType(ArgTy);
4071 Expr *Res =
4072 new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, IList, false);
4073
Chris Lattnerb37522e2007-08-31 21:49:13 +00004074 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4075 // GCC extension, diagnose them.
4076 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004077 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4078 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00004079
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004080 for (unsigned i = 0; i != NumComponents; ++i) {
4081 const OffsetOfComponent &OC = CompPtr[i];
4082 if (OC.isBrackets) {
4083 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00004084 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004085 if (!AT) {
4086 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00004087 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004088 }
4089
Chris Lattner2af6a802007-08-30 17:59:59 +00004090 // FIXME: C++: Verify that operator[] isn't overloaded.
4091
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004092 // C99 6.5.2.1p1
4093 Expr *Idx = static_cast<Expr*>(OC.U.E);
4094 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00004095 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4096 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004097
Steve Naroff774e4152009-01-21 00:14:39 +00004098 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4099 OC.LocEnd);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004100 continue;
4101 }
4102
4103 const RecordType *RC = Res->getType()->getAsRecordType();
4104 if (!RC) {
4105 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00004106 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004107 }
4108
4109 // Get the decl corresponding to this.
4110 RecordDecl *RD = RC->getDecl();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004111 FieldDecl *MemberDecl
Douglas Gregor52ae30c2009-01-30 01:04:22 +00004112 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4113 LookupMemberName)
4114 .getAsDecl());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004115 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00004116 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4117 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00004118
4119 // FIXME: C++: Verify that MemberDecl isn't a static field.
4120 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00004121 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4122 // matter here.
Steve Naroff774e4152009-01-21 00:14:39 +00004123 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4124 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004125 }
4126
Steve Naroff774e4152009-01-21 00:14:39 +00004127 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4128 Context.getSizeType(), BuiltinLoc);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004129}
4130
4131
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004132Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00004133 TypeTy *arg1, TypeTy *arg2,
4134 SourceLocation RPLoc) {
4135 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4136 QualType argT2 = QualType::getFromOpaquePtr(arg2);
4137
4138 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4139
Steve Naroff774e4152009-01-21 00:14:39 +00004140 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
4141 argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00004142}
4143
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004144Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00004145 ExprTy *expr1, ExprTy *expr2,
4146 SourceLocation RPLoc) {
4147 Expr *CondExpr = static_cast<Expr*>(cond);
4148 Expr *LHSExpr = static_cast<Expr*>(expr1);
4149 Expr *RHSExpr = static_cast<Expr*>(expr2);
4150
4151 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4152
4153 // The conditional expression is required to be a constant expression.
4154 llvm::APSInt condEval(32);
4155 SourceLocation ExpLoc;
4156 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004157 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4158 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00004159
4160 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4161 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
4162 RHSExpr->getType();
Steve Naroff774e4152009-01-21 00:14:39 +00004163 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4164 resType, RPLoc);
Steve Naroff93c53012007-08-03 21:21:27 +00004165}
4166
Steve Naroff52a81c02008-09-03 18:15:37 +00004167//===----------------------------------------------------------------------===//
4168// Clang Extensions.
4169//===----------------------------------------------------------------------===//
4170
4171/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004172void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004173 // Analyze block parameters.
4174 BlockSemaInfo *BSI = new BlockSemaInfo();
4175
4176 // Add BSI to CurBlock.
4177 BSI->PrevBlockInfo = CurBlock;
4178 CurBlock = BSI;
4179
4180 BSI->ReturnType = 0;
4181 BSI->TheScope = BlockScope;
4182
Steve Naroff52059382008-10-10 01:28:17 +00004183 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004184 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004185}
4186
4187void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004188 // Analyze arguments to block.
4189 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4190 "Not a function declarator!");
4191 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
4192
Steve Naroff52059382008-10-10 01:28:17 +00004193 CurBlock->hasPrototype = FTI.hasPrototype;
4194 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00004195
4196 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4197 // no arguments, not a function that takes a single void argument.
4198 if (FTI.hasPrototype &&
4199 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4200 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4201 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4202 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004203 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004204 } else if (FTI.hasPrototype) {
4205 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004206 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4207 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00004208 }
Steve Naroff52059382008-10-10 01:28:17 +00004209 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4210
4211 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4212 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4213 // If this has an identifier, add it to the scope stack.
4214 if ((*AI)->getIdentifier())
4215 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004216}
4217
4218/// ActOnBlockError - If there is an error parsing a block, this callback
4219/// is invoked to pop the information about the block from the action impl.
4220void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4221 // Ensure that CurBlock is deleted.
4222 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4223
4224 // Pop off CurBlock, handle nested blocks.
4225 CurBlock = CurBlock->PrevBlockInfo;
4226
4227 // FIXME: Delete the ParmVarDecl objects as well???
4228
4229}
4230
4231/// ActOnBlockStmtExpr - This is called when the body of a block statement
4232/// literal was successfully completed. ^(int x){...}
4233Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4234 Scope *CurScope) {
4235 // Ensure that CurBlock is deleted.
4236 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
4237 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
4238
Steve Naroff52059382008-10-10 01:28:17 +00004239 PopDeclContext();
4240
Steve Naroff52a81c02008-09-03 18:15:37 +00004241 // Pop off CurBlock, handle nested blocks.
4242 CurBlock = CurBlock->PrevBlockInfo;
4243
4244 QualType RetTy = Context.VoidTy;
4245 if (BSI->ReturnType)
4246 RetTy = QualType(BSI->ReturnType, 0);
4247
4248 llvm::SmallVector<QualType, 8> ArgTypes;
4249 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4250 ArgTypes.push_back(BSI->Params[i]->getType());
4251
4252 QualType BlockTy;
4253 if (!BSI->hasPrototype)
4254 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4255 else
4256 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004257 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00004258
4259 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00004260
Steve Naroff95029d92008-10-08 18:44:00 +00004261 BSI->TheDecl->setBody(Body.take());
Steve Naroff774e4152009-01-21 00:14:39 +00004262 return new (Context) BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004263}
4264
Nate Begemanbd881ef2008-01-30 20:50:20 +00004265/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004266/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00004267/// The number of arguments has already been validated to match the number of
4268/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004269static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4270 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004271 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00004272 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004273 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4274 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00004275
4276 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004277 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00004278 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004279 return true;
4280}
4281
4282Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4283 SourceLocation *CommaLocs,
4284 SourceLocation BuiltinLoc,
4285 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004286 // __builtin_overload requires at least 2 arguments
4287 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004288 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4289 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004290
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004291 // The first argument is required to be a constant expression. It tells us
4292 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00004293 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004294 Expr *NParamsExpr = Args[0];
4295 llvm::APSInt constEval(32);
4296 SourceLocation ExpLoc;
4297 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004298 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4299 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004300
4301 // Verify that the number of parameters is > 0
4302 unsigned NumParams = constEval.getZExtValue();
4303 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004304 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4305 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004306 // Verify that we have at least 1 + NumParams arguments to the builtin.
4307 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004308 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4309 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004310
4311 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00004312 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00004313 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004314 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4315 // UsualUnaryConversions will convert the function DeclRefExpr into a
4316 // pointer to function.
4317 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004318 const FunctionTypeProto *FnType = 0;
4319 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4320 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004321
4322 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4323 // parameters, and the number of parameters must match the value passed to
4324 // the builtin.
4325 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004326 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4327 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004328
4329 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00004330 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004331 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004332 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004333 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004334 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4335 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00004336 // Remember our match, and continue processing the remaining arguments
4337 // to catch any errors.
Steve Naroff774e4152009-01-21 00:14:39 +00004338 OE = new (Context) OverloadExpr(Args, NumArgs, i,
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004339 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00004340 BuiltinLoc, RParenLoc);
4341 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004342 }
Nate Begemanc6078c92008-01-31 05:38:29 +00004343 // Return the newly created OverloadExpr node, if we succeded in matching
4344 // exactly one of the candidate functions.
4345 if (OE)
4346 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004347
4348 // If we didn't find a matching function Expr in the __builtin_overload list
4349 // the return an error.
4350 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00004351 for (unsigned i = 0; i != NumParams; ++i) {
4352 if (i != 0) typeNames += ", ";
4353 typeNames += Args[i+1]->getType().getAsString();
4354 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004355
Chris Lattner77d52da2008-11-20 06:06:08 +00004356 return Diag(BuiltinLoc, diag::err_overload_no_match)
4357 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004358}
4359
Anders Carlsson36760332007-10-15 20:28:48 +00004360Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4361 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004362 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004363 Expr *E = static_cast<Expr*>(expr);
4364 QualType T = QualType::getFromOpaquePtr(type);
4365
4366 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004367
4368 // Get the va_list type
4369 QualType VaListType = Context.getBuiltinVaListType();
4370 // Deal with implicit array decay; for example, on x86-64,
4371 // va_list is an array, but it's supposed to decay to
4372 // a pointer for va_arg.
4373 if (VaListType->isArrayType())
4374 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004375 // Make sure the input expression also decays appropriately.
4376 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004377
4378 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004379 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004380 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004381 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00004382
4383 // FIXME: Warn if a non-POD type is passed in.
4384
Steve Naroff774e4152009-01-21 00:14:39 +00004385 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004386}
4387
Douglas Gregorad4b3792008-11-29 04:51:27 +00004388Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4389 // The type of __null will be int or long, depending on the size of
4390 // pointers on the target.
4391 QualType Ty;
4392 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4393 Ty = Context.IntTy;
4394 else
4395 Ty = Context.LongTy;
4396
Steve Naroff774e4152009-01-21 00:14:39 +00004397 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregorad4b3792008-11-29 04:51:27 +00004398}
4399
Chris Lattner005ed752008-01-04 18:04:52 +00004400bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4401 SourceLocation Loc,
4402 QualType DstType, QualType SrcType,
4403 Expr *SrcExpr, const char *Flavor) {
4404 // Decode the result (notice that AST's are still created for extensions).
4405 bool isInvalid = false;
4406 unsigned DiagKind;
4407 switch (ConvTy) {
4408 default: assert(0 && "Unknown conversion type");
4409 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004410 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004411 DiagKind = diag::ext_typecheck_convert_pointer_int;
4412 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004413 case IntToPointer:
4414 DiagKind = diag::ext_typecheck_convert_int_pointer;
4415 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004416 case IncompatiblePointer:
4417 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4418 break;
4419 case FunctionVoidPointer:
4420 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4421 break;
4422 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004423 // If the qualifiers lost were because we were applying the
4424 // (deprecated) C++ conversion from a string literal to a char*
4425 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4426 // Ideally, this check would be performed in
4427 // CheckPointerTypesForAssignment. However, that would require a
4428 // bit of refactoring (so that the second argument is an
4429 // expression, rather than a type), which should be done as part
4430 // of a larger effort to fix CheckPointerTypesForAssignment for
4431 // C++ semantics.
4432 if (getLangOptions().CPlusPlus &&
4433 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4434 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004435 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4436 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004437 case IntToBlockPointer:
4438 DiagKind = diag::err_int_to_block_pointer;
4439 break;
4440 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004441 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004442 break;
Steve Naroff19608432008-10-14 22:18:38 +00004443 case IncompatibleObjCQualifiedId:
4444 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4445 // it can give a more specific diagnostic.
4446 DiagKind = diag::warn_incompatible_qualified_id;
4447 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004448 case IncompatibleVectors:
4449 DiagKind = diag::warn_incompatible_vectors;
4450 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004451 case Incompatible:
4452 DiagKind = diag::err_typecheck_convert_incompatible;
4453 isInvalid = true;
4454 break;
4455 }
4456
Chris Lattner271d4c22008-11-24 05:29:24 +00004457 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4458 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004459 return isInvalid;
4460}
Anders Carlssond5201b92008-11-30 19:50:32 +00004461
4462bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4463{
4464 Expr::EvalResult EvalResult;
4465
4466 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4467 EvalResult.HasSideEffects) {
4468 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4469
4470 if (EvalResult.Diag) {
4471 // We only show the note if it's not the usual "invalid subexpression"
4472 // or if it's actually in a subexpression.
4473 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4474 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4475 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4476 }
4477
4478 return true;
4479 }
4480
4481 if (EvalResult.Diag) {
4482 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4483 E->getSourceRange();
4484
4485 // Print the reason it's not a constant.
4486 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4487 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4488 }
4489
4490 if (Result)
4491 *Result = EvalResult.Val.getInt();
4492 return false;
4493}