blob: 56ad4b5f26175458b8df42e39438cdb192697294 [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"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
Chris Lattner299b8842008-07-25 21:10:04 +000029//===----------------------------------------------------------------------===//
30// Standard Promotions and Conversions
31//===----------------------------------------------------------------------===//
32
Chris Lattner299b8842008-07-25 21:10:04 +000033/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
34void Sema::DefaultFunctionArrayConversion(Expr *&E) {
35 QualType Ty = E->getType();
36 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
37
Chris Lattner299b8842008-07-25 21:10:04 +000038 if (Ty->isFunctionType())
39 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +000040 else if (Ty->isArrayType()) {
41 // In C90 mode, arrays only promote to pointers if the array expression is
42 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
43 // type 'array of type' is converted to an expression that has type 'pointer
44 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
45 // that has type 'array of type' ...". The relevant change is "an lvalue"
46 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +000047 //
48 // C++ 4.2p1:
49 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
50 // T" can be converted to an rvalue of type "pointer to T".
51 //
52 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
53 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +000054 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
55 }
Chris Lattner299b8842008-07-25 21:10:04 +000056}
57
58/// UsualUnaryConversions - Performs various conversions that are common to most
59/// operators (C99 6.3). The conversions of array and function types are
60/// sometimes surpressed. For example, the array->pointer conversion doesn't
61/// apply if the array is an argument to the sizeof or address (&) operators.
62/// In these instances, this routine should *not* be called.
63Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
64 QualType Ty = Expr->getType();
65 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
66
Chris Lattner299b8842008-07-25 21:10:04 +000067 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
68 ImpCastExprToType(Expr, Context.IntTy);
69 else
70 DefaultFunctionArrayConversion(Expr);
71
72 return Expr;
73}
74
Chris Lattner9305c3d2008-07-25 22:25:12 +000075/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
76/// do not have a prototype. Arguments that have type float are promoted to
77/// double. All other argument types are converted by UsualUnaryConversions().
78void Sema::DefaultArgumentPromotion(Expr *&Expr) {
79 QualType Ty = Expr->getType();
80 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
81
82 // If this is a 'float' (CVR qualified or typedef) promote to double.
83 if (const BuiltinType *BT = Ty->getAsBuiltinType())
84 if (BT->getKind() == BuiltinType::Float)
85 return ImpCastExprToType(Expr, Context.DoubleTy);
86
87 UsualUnaryConversions(Expr);
88}
89
Anders Carlsson4b8e38c2009-01-16 16:48:51 +000090// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
91// will warn if the resulting type is not a POD type.
92void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT)
93
94{
95 DefaultArgumentPromotion(Expr);
96
97 if (!Expr->getType()->isPODType()) {
98 Diag(Expr->getLocStart(),
99 diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
100 Expr->getType() << CT;
101 }
102}
103
104
Chris Lattner299b8842008-07-25 21:10:04 +0000105/// UsualArithmeticConversions - Performs various conversions that are common to
106/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
107/// routine returns the first non-arithmetic type found. The client is
108/// responsible for emitting appropriate error diagnostics.
109/// FIXME: verify the conversion rules for "complex int" are consistent with
110/// GCC.
111QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
112 bool isCompAssign) {
113 if (!isCompAssign) {
114 UsualUnaryConversions(lhsExpr);
115 UsualUnaryConversions(rhsExpr);
116 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000117
Chris Lattner299b8842008-07-25 21:10:04 +0000118 // For conversion purposes, we ignore any qualifiers.
119 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000120 QualType lhs =
121 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
122 QualType rhs =
123 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000124
125 // If both types are identical, no conversion is needed.
126 if (lhs == rhs)
127 return lhs;
128
129 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
130 // The caller can deal with this (e.g. pointer + int).
131 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
132 return lhs;
133
134 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
135 if (!isCompAssign) {
136 ImpCastExprToType(lhsExpr, destType);
137 ImpCastExprToType(rhsExpr, destType);
138 }
139 return destType;
140}
141
142QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
143 // Perform the usual unary conversions. We do this early so that
144 // integral promotions to "int" can allow us to exit early, in the
145 // lhs == rhs check. Also, for conversion purposes, we ignore any
146 // qualifiers. For example, "const float" and "float" are
147 // equivalent.
Douglas Gregor3d4492e2008-11-13 20:12:29 +0000148 if (lhs->isPromotableIntegerType()) lhs = Context.IntTy;
149 else lhs = lhs.getUnqualifiedType();
150 if (rhs->isPromotableIntegerType()) rhs = Context.IntTy;
151 else rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000152
Chris Lattner299b8842008-07-25 21:10:04 +0000153 // If both types are identical, no conversion is needed.
154 if (lhs == rhs)
155 return lhs;
156
157 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
158 // The caller can deal with this (e.g. pointer + int).
159 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
160 return lhs;
161
162 // At this point, we have two different arithmetic types.
163
164 // Handle complex types first (C99 6.3.1.8p1).
165 if (lhs->isComplexType() || rhs->isComplexType()) {
166 // if we have an integer operand, the result is the complex type.
167 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
168 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000169 return lhs;
170 }
171 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
172 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000173 return rhs;
174 }
175 // This handles complex/complex, complex/float, or float/complex.
176 // When both operands are complex, the shorter operand is converted to the
177 // type of the longer, and that is the type of the result. This corresponds
178 // to what is done when combining two real floating-point operands.
179 // The fun begins when size promotion occur across type domains.
180 // From H&S 6.3.4: When one operand is complex and the other is a real
181 // floating-point type, the less precise type is converted, within it's
182 // real or complex domain, to the precision of the other type. For example,
183 // when combining a "long double" with a "double _Complex", the
184 // "double _Complex" is promoted to "long double _Complex".
185 int result = Context.getFloatingTypeOrder(lhs, rhs);
186
187 if (result > 0) { // The left side is bigger, convert rhs.
188 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000189 } else if (result < 0) { // The right side is bigger, convert lhs.
190 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000191 }
192 // At this point, lhs and rhs have the same rank/size. Now, make sure the
193 // domains match. This is a requirement for our implementation, C99
194 // does not require this promotion.
195 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
196 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000197 return rhs;
198 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000199 return lhs;
200 }
201 }
202 return lhs; // The domain/size match exactly.
203 }
204 // Now handle "real" floating types (i.e. float, double, long double).
205 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
206 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000207 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000208 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000209 return lhs;
210 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000211 if (rhs->isComplexIntegerType()) {
212 // convert rhs to the complex floating point type.
213 return Context.getComplexType(lhs);
214 }
215 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000216 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000217 return rhs;
218 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000219 if (lhs->isComplexIntegerType()) {
220 // convert lhs to the complex floating point type.
221 return Context.getComplexType(rhs);
222 }
Chris Lattner299b8842008-07-25 21:10:04 +0000223 // We have two real floating types, float/complex combos were handled above.
224 // Convert the smaller operand to the bigger result.
225 int result = Context.getFloatingTypeOrder(lhs, rhs);
226
227 if (result > 0) { // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000228 return lhs;
229 }
230 if (result < 0) { // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000231 return rhs;
232 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000233 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
Chris Lattner299b8842008-07-25 21:10:04 +0000234 }
235 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
236 // Handle GCC complex int extension.
237 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
238 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
239
240 if (lhsComplexInt && rhsComplexInt) {
241 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
242 rhsComplexInt->getElementType()) >= 0) {
243 // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000244 return lhs;
245 }
Chris Lattner299b8842008-07-25 21:10:04 +0000246 return rhs;
247 } else if (lhsComplexInt && rhs->isIntegerType()) {
248 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000249 return lhs;
250 } else if (rhsComplexInt && lhs->isIntegerType()) {
251 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000252 return rhs;
253 }
254 }
255 // Finally, we have two differing integer types.
256 // The rules for this case are in C99 6.3.1.8
257 int compare = Context.getIntegerTypeOrder(lhs, rhs);
258 bool lhsSigned = lhs->isSignedIntegerType(),
259 rhsSigned = rhs->isSignedIntegerType();
260 QualType destType;
261 if (lhsSigned == rhsSigned) {
262 // Same signedness; use the higher-ranked type
263 destType = compare >= 0 ? lhs : rhs;
264 } else if (compare != (lhsSigned ? 1 : -1)) {
265 // The unsigned type has greater than or equal rank to the
266 // signed type, so use the unsigned type
267 destType = lhsSigned ? rhs : lhs;
268 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
269 // The two types are different widths; if we are here, that
270 // means the signed type is larger than the unsigned type, so
271 // use the signed type.
272 destType = lhsSigned ? lhs : rhs;
273 } else {
274 // The signed type is higher-ranked than the unsigned type,
275 // but isn't actually any bigger (like unsigned int and long
276 // on most 32-bit systems). Use the unsigned type corresponding
277 // to the signed type.
278 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
279 }
Chris Lattner299b8842008-07-25 21:10:04 +0000280 return destType;
281}
282
283//===----------------------------------------------------------------------===//
284// Semantic Analysis for various Expression Types
285//===----------------------------------------------------------------------===//
286
287
Steve Naroff87d58b42007-09-16 03:34:24 +0000288/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000289/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
290/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
291/// multiple tokens. However, the common case is that StringToks points to one
292/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000293///
294Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000295Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000296 assert(NumStringToks && "Must have at least one string!");
297
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000298 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000299 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000300 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000301
302 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
303 for (unsigned i = 0; i != NumStringToks; ++i)
304 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000305
Chris Lattnera6dcce32008-02-11 00:02:17 +0000306 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000307 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000308 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000309
310 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
311 if (getLangOptions().CPlusPlus)
312 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000313
Chris Lattnera6dcce32008-02-11 00:02:17 +0000314 // Get an array type for the string, according to C99 6.4.5. This includes
315 // the nul terminator character as well as the string length for pascal
316 // strings.
317 StrTy = Context.getConstantArrayType(StrTy,
318 llvm::APInt(32, Literal.GetStringLength()+1),
319 ArrayType::Normal, 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000320
Chris Lattner4b009652007-07-25 00:24:17 +0000321 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Steve Naroff774e4152009-01-21 00:14:39 +0000322 return Owned(new (Context) StringLiteral(Literal.GetString(),
323 Literal.GetStringLength(),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000324 Literal.AnyWide, StrTy,
325 StringToks[0].getLocation(),
326 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000327}
328
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000329/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
330/// CurBlock to VD should cause it to be snapshotted (as we do for auto
331/// variables defined outside the block) or false if this is not needed (e.g.
332/// for values inside the block or for globals).
333///
334/// FIXME: This will create BlockDeclRefExprs for global variables,
335/// function references, etc which is suboptimal :) and breaks
336/// things like "integer constant expression" tests.
337static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
338 ValueDecl *VD) {
339 // If the value is defined inside the block, we couldn't snapshot it even if
340 // we wanted to.
341 if (CurBlock->TheDecl == VD->getDeclContext())
342 return false;
343
344 // If this is an enum constant or function, it is constant, don't snapshot.
345 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
346 return false;
347
348 // If this is a reference to an extern, static, or global variable, no need to
349 // snapshot it.
350 // FIXME: What about 'const' variables in C++?
351 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
352 return Var->hasLocalStorage();
353
354 return true;
355}
356
357
358
Steve Naroff0acc9c92007-09-15 18:49:24 +0000359/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000360/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000361/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000362/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000363/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000364Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
365 IdentifierInfo &II,
366 bool HasTrailingLParen,
367 const CXXScopeSpec *SS) {
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000368 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS);
369}
370
Douglas Gregor566782a2009-01-06 05:10:23 +0000371/// BuildDeclRefExpr - Build either a DeclRefExpr or a
372/// QualifiedDeclRefExpr based on whether or not SS is a
373/// nested-name-specifier.
374DeclRefExpr *Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
375 bool TypeDependent, bool ValueDependent,
376 const CXXScopeSpec *SS) {
Steve Naroff774e4152009-01-21 00:14:39 +0000377 if (SS && !SS->isEmpty())
378 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000379 ValueDependent, SS->getRange().getBegin());
Steve Naroff774e4152009-01-21 00:14:39 +0000380 else
381 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000382}
383
Douglas Gregor723d3332009-01-07 00:43:41 +0000384/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
385/// variable corresponding to the anonymous union or struct whose type
386/// is Record.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000387static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000388 assert(Record->isAnonymousStructOrUnion() &&
389 "Record must be an anonymous struct or union!");
390
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000391 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000392 // be an O(1) operation rather than a slow walk through DeclContext's
393 // vector (which itself will be eliminated). DeclGroups might make
394 // this even better.
395 DeclContext *Ctx = Record->getDeclContext();
396 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
397 DEnd = Ctx->decls_end();
398 D != DEnd; ++D) {
399 if (*D == Record) {
400 // The object for the anonymous struct/union directly
401 // follows its type in the list of declarations.
402 ++D;
403 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000404 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000405 return *D;
406 }
407 }
408
409 assert(false && "Missing object for anonymous record");
410 return 0;
411}
412
Sebastian Redlcd883f72009-01-18 18:53:16 +0000413Sema::OwningExprResult
Douglas Gregor723d3332009-01-07 00:43:41 +0000414Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
415 FieldDecl *Field,
416 Expr *BaseObjectExpr,
417 SourceLocation OpLoc) {
418 assert(Field->getDeclContext()->isRecord() &&
419 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
420 && "Field must be stored inside an anonymous struct or union");
421
422 // Construct the sequence of field member references
423 // we'll have to perform to get to the field in the anonymous
424 // union/struct. The list of members is built from the field
425 // outward, so traverse it backwards to go from an object in
426 // the current context to the field we found.
427 llvm::SmallVector<FieldDecl *, 4> AnonFields;
428 AnonFields.push_back(Field);
429 VarDecl *BaseObject = 0;
430 DeclContext *Ctx = Field->getDeclContext();
431 do {
432 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000433 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000434 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
435 AnonFields.push_back(AnonField);
436 else {
437 BaseObject = cast<VarDecl>(AnonObject);
438 break;
439 }
440 Ctx = Ctx->getParent();
441 } while (Ctx->isRecord() &&
442 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
443
444 // Build the expression that refers to the base object, from
445 // which we will build a sequence of member references to each
446 // of the anonymous union objects and, eventually, the field we
447 // found via name lookup.
448 bool BaseObjectIsPointer = false;
449 unsigned ExtraQuals = 0;
450 if (BaseObject) {
451 // BaseObject is an anonymous struct/union variable (and is,
452 // therefore, not part of another non-anonymous record).
453 delete BaseObjectExpr;
454
Steve Naroff774e4152009-01-21 00:14:39 +0000455 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000456 SourceLocation());
457 ExtraQuals
458 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
459 } else if (BaseObjectExpr) {
460 // The caller provided the base object expression. Determine
461 // whether its a pointer and whether it adds any qualifiers to the
462 // anonymous struct/union fields we're looking into.
463 QualType ObjectType = BaseObjectExpr->getType();
464 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
465 BaseObjectIsPointer = true;
466 ObjectType = ObjectPtr->getPointeeType();
467 }
468 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
469 } else {
470 // We've found a member of an anonymous struct/union that is
471 // inside a non-anonymous struct/union, so in a well-formed
472 // program our base object expression is "this".
473 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
474 if (!MD->isStatic()) {
475 QualType AnonFieldType
476 = Context.getTagDeclType(
477 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
478 QualType ThisType = Context.getTagDeclType(MD->getParent());
479 if ((Context.getCanonicalType(AnonFieldType)
480 == Context.getCanonicalType(ThisType)) ||
481 IsDerivedFrom(ThisType, AnonFieldType)) {
482 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000483 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000484 MD->getThisType(Context));
485 BaseObjectIsPointer = true;
486 }
487 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000488 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
489 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000490 }
491 ExtraQuals = MD->getTypeQualifiers();
492 }
493
494 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000495 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
496 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000497 }
498
499 // Build the implicit member references to the field of the
500 // anonymous struct/union.
501 Expr *Result = BaseObjectExpr;
502 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
503 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
504 FI != FIEnd; ++FI) {
505 QualType MemberType = (*FI)->getType();
506 if (!(*FI)->isMutable()) {
507 unsigned combinedQualifiers
508 = MemberType.getCVRQualifiers() | ExtraQuals;
509 MemberType = MemberType.getQualifiedType(combinedQualifiers);
510 }
Steve Naroff774e4152009-01-21 00:14:39 +0000511 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
512 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000513 BaseObjectIsPointer = false;
514 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
515 OpLoc = SourceLocation();
516 }
517
Sebastian Redlcd883f72009-01-18 18:53:16 +0000518 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000519}
520
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000521/// ActOnDeclarationNameExpr - The parser has read some kind of name
522/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
523/// performs lookup on that name and returns an expression that refers
524/// to that name. This routine isn't directly called from the parser,
525/// because the parser doesn't know about DeclarationName. Rather,
526/// this routine is called by ActOnIdentifierExpr,
527/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
528/// which form the DeclarationName from the corresponding syntactic
529/// forms.
530///
531/// HasTrailingLParen indicates whether this identifier is used in a
532/// function call context. LookupCtx is only used for a C++
533/// qualified-id (foo::bar) to indicate the class or namespace that
534/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000535///
536/// If ForceResolution is true, then we will attempt to resolve the
537/// name even if it looks like a dependent name. This option is off by
538/// default.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000539Sema::OwningExprResult
540Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
541 DeclarationName Name, bool HasTrailingLParen,
542 const CXXScopeSpec *SS, bool ForceResolution) {
Douglas Gregora133e262008-12-06 00:22:45 +0000543 if (S->getTemplateParamParent() && Name.getAsIdentifierInfo() &&
544 HasTrailingLParen && !SS && !ForceResolution) {
545 // We've seen something of the form
546 // identifier(
547 // and we are in a template, so it is likely that 's' is a
548 // dependent name. However, we won't know until we've parsed all
549 // of the call arguments. So, build a CXXDependentNameExpr node
550 // to represent this name. Then, if it turns out that none of the
551 // arguments are type-dependent, we'll force the resolution of the
552 // dependent name at that point.
Steve Naroff774e4152009-01-21 00:14:39 +0000553 return Owned(new (Context) CXXDependentNameExpr(Name.getAsIdentifierInfo(),
554 Context.DependentTy, Loc));
Douglas Gregora133e262008-12-06 00:22:45 +0000555 }
556
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000557 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000558 Decl *D = 0;
559 LookupResult Lookup;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000560 if (SS && !SS->isEmpty()) {
561 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
562 if (DC == 0)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000563 return ExprError();
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000564 Lookup = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000565 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000566 Lookup = LookupDecl(Name, Decl::IDNS_Ordinary, S);
567
Sebastian Redlcd883f72009-01-18 18:53:16 +0000568 if (Lookup.isAmbiguous()) {
569 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
570 SS && SS->isSet() ? SS->getRange()
571 : SourceRange());
572 return ExprError();
573 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000574 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000575
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000576 // If this reference is in an Objective-C method, then ivar lookup happens as
577 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000578 IdentifierInfo *II = Name.getAsIdentifierInfo();
579 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000580 // There are two cases to handle here. 1) scoped lookup could have failed,
581 // in which case we should look for an ivar. 2) scoped lookup could have
582 // found a decl, but that decl is outside the current method (i.e. a global
583 // variable). In these two cases, we do a lookup for an ivar with this
584 // name, if the lookup suceeds, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000585 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000586 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000587 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000588 // FIXME: This should use a new expr for a direct reference, don't turn
589 // this into Self->ivar, just return a BareIVarExpr or something.
590 IdentifierInfo &II = Context.Idents.get("self");
Sebastian Redlcd883f72009-01-18 18:53:16 +0000591 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Steve Naroff774e4152009-01-21 00:14:39 +0000592 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
593 Loc, static_cast<Expr*>(SelfExpr.release()),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000594 true, true);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000595 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000596 return Owned(MRef);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000597 }
598 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000599 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000600 if (D == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000601 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000602 getCurMethodDecl()->getClassInterface()));
Steve Naroff774e4152009-01-21 00:14:39 +0000603 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000604 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000605 }
Chris Lattner4b009652007-07-25 00:24:17 +0000606 if (D == 0) {
607 // Otherwise, this could be an implicitly declared function reference (legal
608 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000609 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000610 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000611 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000612 else {
613 // If this name wasn't predeclared and if this is not a function call,
614 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000615 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000616 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
617 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000618 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
619 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000620 return ExprError(Diag(Loc, diag::err_undeclared_use)
621 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000622 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000623 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000624 }
625 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000626
627 // We may have found a field within an anonymous union or struct
628 // (C++ [class.union]).
629 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
630 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
631 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000632
Douglas Gregor3257fb52008-12-22 05:46:06 +0000633 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
634 if (!MD->isStatic()) {
635 // C++ [class.mfct.nonstatic]p2:
636 // [...] if name lookup (3.4.1) resolves the name in the
637 // id-expression to a nonstatic nontype member of class X or of
638 // a base class of X, the id-expression is transformed into a
639 // class member access expression (5.2.5) using (*this) (9.3.2)
640 // as the postfix-expression to the left of the '.' operator.
641 DeclContext *Ctx = 0;
642 QualType MemberType;
643 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
644 Ctx = FD->getDeclContext();
645 MemberType = FD->getType();
646
647 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
648 MemberType = RefType->getPointeeType();
649 else if (!FD->isMutable()) {
650 unsigned combinedQualifiers
651 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
652 MemberType = MemberType.getQualifiedType(combinedQualifiers);
653 }
654 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
655 if (!Method->isStatic()) {
656 Ctx = Method->getParent();
657 MemberType = Method->getType();
658 }
659 } else if (OverloadedFunctionDecl *Ovl
660 = dyn_cast<OverloadedFunctionDecl>(D)) {
661 for (OverloadedFunctionDecl::function_iterator
662 Func = Ovl->function_begin(),
663 FuncEnd = Ovl->function_end();
664 Func != FuncEnd; ++Func) {
665 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
666 if (!DMethod->isStatic()) {
667 Ctx = Ovl->getDeclContext();
668 MemberType = Context.OverloadTy;
669 break;
670 }
671 }
672 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000673
674 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000675 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
676 QualType ThisType = Context.getTagDeclType(MD->getParent());
677 if ((Context.getCanonicalType(CtxType)
678 == Context.getCanonicalType(ThisType)) ||
679 IsDerivedFrom(ThisType, CtxType)) {
680 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000681 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor3257fb52008-12-22 05:46:06 +0000682 MD->getThisType(Context));
Steve Naroff774e4152009-01-21 00:14:39 +0000683 return Owned(new (Context) MemberExpr(This, true, cast<NamedDecl>(D),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000684 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000685 }
686 }
687 }
688 }
689
Douglas Gregor8acb7272008-12-11 16:49:14 +0000690 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000691 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
692 if (MD->isStatic())
693 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000694 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
695 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000696 }
697
Douglas Gregor3257fb52008-12-22 05:46:06 +0000698 // Any other ways we could have found the field in a well-formed
699 // program would have been turned into implicit member expressions
700 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000701 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
702 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000703 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000704
Chris Lattner4b009652007-07-25 00:24:17 +0000705 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000706 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000707 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000708 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000709 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000710 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000711
Steve Naroffd6163f32008-09-05 22:11:13 +0000712 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000713 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000714 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
715 false, false, SS));
Douglas Gregord2baafd2008-10-21 16:13:35 +0000716
Steve Naroffd6163f32008-09-05 22:11:13 +0000717 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000718
Steve Naroffd6163f32008-09-05 22:11:13 +0000719 // check if referencing an identifier with __attribute__((deprecated)).
720 if (VD->getAttr<DeprecatedAttr>())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000721 ExprError(Diag(Loc, diag::warn_deprecated) << VD->getDeclName());
722
Douglas Gregor48840c72008-12-10 23:01:14 +0000723 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
724 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
725 Scope *CheckS = S;
726 while (CheckS) {
727 if (CheckS->isWithinElse() &&
728 CheckS->getControlParent()->isDeclScope(Var)) {
729 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000730 ExprError(Diag(Loc, diag::warn_value_always_false)
731 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000732 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000733 ExprError(Diag(Loc, diag::warn_value_always_zero)
734 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000735 break;
736 }
737
738 // Move up one more control parent to check again.
739 CheckS = CheckS->getControlParent();
740 if (CheckS)
741 CheckS = CheckS->getParent();
742 }
743 }
744 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000745
746 // Only create DeclRefExpr's for valid Decl's.
747 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000748 return ExprError();
749
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000750 // If the identifier reference is inside a block, and it refers to a value
751 // that is outside the block, create a BlockDeclRefExpr instead of a
752 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
753 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000754 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000755 // We do not do this for things like enum constants, global variables, etc,
756 // as they do not get snapshotted.
757 //
758 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000759 // The BlocksAttr indicates the variable is bound by-reference.
760 if (VD->getAttr<BlocksAttr>())
Steve Naroff774e4152009-01-21 00:14:39 +0000761 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000762 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000763
Steve Naroff52059382008-10-10 01:28:17 +0000764 // Variable will be bound by-copy, make it const within the closure.
765 VD->getType().addConst();
Steve Naroff774e4152009-01-21 00:14:39 +0000766 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000767 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000768 }
769 // If this reference is not in a block or if the referenced variable is
770 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000771
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000772 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000773 bool ValueDependent = false;
774 if (getLangOptions().CPlusPlus) {
775 // C++ [temp.dep.expr]p3:
776 // An id-expression is type-dependent if it contains:
777 // - an identifier that was declared with a dependent type,
778 if (VD->getType()->isDependentType())
779 TypeDependent = true;
780 // - FIXME: a template-id that is dependent,
781 // - a conversion-function-id that specifies a dependent type,
782 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
783 Name.getCXXNameType()->isDependentType())
784 TypeDependent = true;
785 // - a nested-name-specifier that contains a class-name that
786 // names a dependent type.
787 else if (SS && !SS->isEmpty()) {
788 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
789 DC; DC = DC->getParent()) {
790 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000791 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000792 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
793 if (Context.getTypeDeclType(Record)->isDependentType()) {
794 TypeDependent = true;
795 break;
796 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000797 }
798 }
799 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000800
Douglas Gregora5d84612008-12-10 20:57:37 +0000801 // C++ [temp.dep.constexpr]p2:
802 //
803 // An identifier is value-dependent if it is:
804 // - a name declared with a dependent type,
805 if (TypeDependent)
806 ValueDependent = true;
807 // - the name of a non-type template parameter,
808 else if (isa<NonTypeTemplateParmDecl>(VD))
809 ValueDependent = true;
810 // - a constant with integral or enumeration type and is
811 // initialized with an expression that is value-dependent
812 // (FIXME!).
813 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000814
Sebastian Redlcd883f72009-01-18 18:53:16 +0000815 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
816 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000817}
818
Sebastian Redlcd883f72009-01-18 18:53:16 +0000819Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
820 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000821 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000822
Chris Lattner4b009652007-07-25 00:24:17 +0000823 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000824 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000825 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
826 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
827 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000828 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000829
Chris Lattner7e637512008-01-12 08:14:25 +0000830 // Pre-defined identifiers are of type char[x], where x is the length of the
831 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000832 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000833 if (FunctionDecl *FD = getCurFunctionDecl())
834 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000835 else if (ObjCMethodDecl *MD = getCurMethodDecl())
836 Length = MD->getSynthesizedMethodSize();
837 else {
838 Diag(Loc, diag::ext_predef_outside_function);
839 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
840 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
841 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000842
843
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000844 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000845 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000846 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +0000847 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +0000848}
849
Sebastian Redlcd883f72009-01-18 18:53:16 +0000850Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000851 llvm::SmallString<16> CharBuffer;
852 CharBuffer.resize(Tok.getLength());
853 const char *ThisTokBegin = &CharBuffer[0];
854 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000855
Chris Lattner4b009652007-07-25 00:24:17 +0000856 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
857 Tok.getLocation(), PP);
858 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000859 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +0000860
861 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
862
Sebastian Redl75324932009-01-20 22:23:13 +0000863 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
864 Literal.isWide(),
865 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000866}
867
Sebastian Redlcd883f72009-01-18 18:53:16 +0000868Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
869 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +0000870 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
871 if (Tok.getLength() == 1) {
Chris Lattnerfd5f1432009-01-16 07:10:29 +0000872 const char Val = PP.getSpelledCharacterAt(Tok.getLocation());
873 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +0000874 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +0000875 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000876 }
Ted Kremenekdbde2282009-01-13 23:19:12 +0000877
Chris Lattner4b009652007-07-25 00:24:17 +0000878 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000879 // Add padding so that NumericLiteralParser can overread by one character.
880 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000881 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +0000882
Chris Lattner4b009652007-07-25 00:24:17 +0000883 // Get the spelling of the token, which eliminates trigraphs, etc.
884 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000885
Chris Lattner4b009652007-07-25 00:24:17 +0000886 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
887 Tok.getLocation(), PP);
888 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000889 return ExprError();
890
Chris Lattner1de66eb2007-08-26 03:42:43 +0000891 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000892
Chris Lattner1de66eb2007-08-26 03:42:43 +0000893 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000894 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000895 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000896 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000897 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000898 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000899 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000900 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000901
902 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
903
Ted Kremenekddedbe22007-11-29 00:56:49 +0000904 // isExact will be set by GetFloatValue().
905 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +0000906 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
907 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +0000908
Chris Lattner1de66eb2007-08-26 03:42:43 +0000909 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000910 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +0000911 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000912 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000913
Neil Booth7421e9c2007-08-29 22:00:19 +0000914 // long long is a C99 feature.
915 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000916 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000917 Diag(Tok.getLocation(), diag::ext_longlong);
918
Chris Lattner4b009652007-07-25 00:24:17 +0000919 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000920 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000921
Chris Lattner4b009652007-07-25 00:24:17 +0000922 if (Literal.GetIntegerValue(ResultVal)) {
923 // If this value didn't fit into uintmax_t, warn and force to ull.
924 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000925 Ty = Context.UnsignedLongLongTy;
926 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000927 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000928 } else {
929 // If this value fits into a ULL, try to figure out what else it fits into
930 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000931
Chris Lattner4b009652007-07-25 00:24:17 +0000932 // Octal, Hexadecimal, and integers with a U suffix are allowed to
933 // be an unsigned int.
934 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
935
936 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000937 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000938 if (!Literal.isLong && !Literal.isLongLong) {
939 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000940 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000941
Chris Lattner4b009652007-07-25 00:24:17 +0000942 // Does it fit in a unsigned int?
943 if (ResultVal.isIntN(IntSize)) {
944 // Does it fit in a signed int?
945 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000946 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000947 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000948 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000949 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000950 }
Chris Lattner4b009652007-07-25 00:24:17 +0000951 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000952
Chris Lattner4b009652007-07-25 00:24:17 +0000953 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000954 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000955 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000956
Chris Lattner4b009652007-07-25 00:24:17 +0000957 // Does it fit in a unsigned long?
958 if (ResultVal.isIntN(LongSize)) {
959 // Does it fit in a signed long?
960 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000961 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000962 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000963 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000964 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000965 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000966 }
967
Chris Lattner4b009652007-07-25 00:24:17 +0000968 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000969 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000970 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000971
Chris Lattner4b009652007-07-25 00:24:17 +0000972 // Does it fit in a unsigned long long?
973 if (ResultVal.isIntN(LongLongSize)) {
974 // Does it fit in a signed long long?
975 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000976 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000977 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000978 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000979 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000980 }
981 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000982
Chris Lattner4b009652007-07-25 00:24:17 +0000983 // If we still couldn't decide a type, we probably have something that
984 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000985 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000986 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000987 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000988 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000989 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000990
Chris Lattnere4068872008-05-09 05:59:00 +0000991 if (ResultVal.getBitWidth() != Width)
992 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000993 }
Sebastian Redl75324932009-01-20 22:23:13 +0000994 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000995 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000996
Chris Lattner1de66eb2007-08-26 03:42:43 +0000997 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
998 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +0000999 Res = new (Context) ImaginaryLiteral(Res,
1000 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001001
1002 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001003}
1004
Sebastian Redlcd883f72009-01-18 18:53:16 +00001005Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1006 SourceLocation R, ExprArg Val) {
1007 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001008 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001009 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001010}
1011
1012/// The UsualUnaryConversions() function is *not* called by this routine.
1013/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001014bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1015 SourceLocation OpLoc,
1016 const SourceRange &ExprRange,
1017 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +00001018 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001019 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001020 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001021 if (isSizeof)
1022 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1023 return false;
1024 }
1025
1026 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001027 Diag(OpLoc, diag::ext_sizeof_void_type)
1028 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001029 return false;
1030 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001031
Chris Lattner159fe082009-01-24 19:46:37 +00001032 return DiagnoseIncompleteType(OpLoc, exprType,
1033 isSizeof ? diag::err_sizeof_incomplete_type :
1034 diag::err_alignof_incomplete_type,
1035 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001036}
1037
Chris Lattner8d9f7962009-01-24 20:17:12 +00001038bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1039 const SourceRange &ExprRange) {
1040 E = E->IgnoreParens();
1041
1042 // alignof decl is always ok.
1043 if (isa<DeclRefExpr>(E))
1044 return false;
1045
1046 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1047 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1048 if (FD->isBitField()) {
1049 Diag(OpLoc, diag::err_alignof_bitfield) << ExprRange;
1050 return true;
1051 }
1052 // Other fields are ok.
1053 return false;
1054 }
1055 }
1056 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1057}
1058
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001059/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1060/// the same for @c alignof and @c __alignof
1061/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001062Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001063Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1064 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001065 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001066 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001067
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001068 QualType ArgTy;
1069 SourceRange Range;
1070 if (isType) {
1071 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1072 Range = ArgRange;
Chris Lattnera78909b2009-01-24 19:49:13 +00001073
1074 // Verify that the operand is valid.
1075 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1076 return ExprError();
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001077 } else {
1078 // Get the end location.
1079 Expr *ArgEx = (Expr *)TyOrEx;
1080 Range = ArgEx->getSourceRange();
1081 ArgTy = ArgEx->getType();
Chris Lattnera78909b2009-01-24 19:49:13 +00001082
1083 // Verify that the operand is valid.
Chris Lattner8d9f7962009-01-24 20:17:12 +00001084 bool isInvalid;
1085 if (isSizeof)
1086 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1087 else
1088 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
1089
1090 if (isInvalid) {
Chris Lattnera78909b2009-01-24 19:49:13 +00001091 DeleteExpr(ArgEx);
1092 return ExprError();
1093 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001094 }
1095
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001096 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff774e4152009-01-21 00:14:39 +00001097 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner159fe082009-01-24 19:46:37 +00001098 Context.getSizeType(), OpLoc,
1099 Range.getEnd()));
Chris Lattner4b009652007-07-25 00:24:17 +00001100}
1101
Chris Lattner5110ad52007-08-24 21:41:10 +00001102QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +00001103 DefaultFunctionArrayConversion(V);
1104
Chris Lattnera16e42d2007-08-26 05:39:26 +00001105 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001106 if (const ComplexType *CT = V->getType()->getAsComplexType())
1107 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001108
1109 // Otherwise they pass through real integer and floating point types here.
1110 if (V->getType()->isArithmeticType())
1111 return V->getType();
1112
1113 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +00001114 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001115 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001116}
1117
1118
Chris Lattner4b009652007-07-25 00:24:17 +00001119
Sebastian Redl8b769972009-01-19 00:08:26 +00001120Action::OwningExprResult
1121Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1122 tok::TokenKind Kind, ExprArg Input) {
1123 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001124
Chris Lattner4b009652007-07-25 00:24:17 +00001125 UnaryOperator::Opcode Opc;
1126 switch (Kind) {
1127 default: assert(0 && "Unknown unary op!");
1128 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1129 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1130 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001131
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001132 if (getLangOptions().CPlusPlus &&
1133 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1134 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001135 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001136 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1137
1138 // C++ [over.inc]p1:
1139 //
1140 // [...] If the function is a member function with one
1141 // parameter (which shall be of type int) or a non-member
1142 // function with two parameters (the second of which shall be
1143 // of type int), it defines the postfix increment operator ++
1144 // for objects of that type. When the postfix increment is
1145 // called as a result of using the ++ operator, the int
1146 // argument will have value zero.
1147 Expr *Args[2] = {
1148 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001149 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1150 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001151 };
1152
1153 // Build the candidate set for overloading
1154 OverloadCandidateSet CandidateSet;
1155 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
1156
1157 // Perform overload resolution.
1158 OverloadCandidateSet::iterator Best;
1159 switch (BestViableFunction(CandidateSet, Best)) {
1160 case OR_Success: {
1161 // We found a built-in operator or an overloaded operator.
1162 FunctionDecl *FnDecl = Best->Function;
1163
1164 if (FnDecl) {
1165 // We matched an overloaded operator. Build a call to that
1166 // operator.
1167
1168 // Convert the arguments.
1169 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1170 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001171 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001172 } else {
1173 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001174 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001175 FnDecl->getParamDecl(0)->getType(),
1176 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001177 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001178 }
1179
1180 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001181 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001182 = FnDecl->getType()->getAsFunctionType()->getResultType();
1183 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001184
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001185 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001186 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001187 SourceLocation());
1188 UsualUnaryConversions(FnExpr);
1189
Sebastian Redl8b769972009-01-19 00:08:26 +00001190 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001191 return Owned(new (Context)CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy,
Steve Naroffe5f128a2009-01-20 19:53:53 +00001192 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001193 } else {
1194 // We matched a built-in operator. Convert the arguments, then
1195 // break out so that we will build the appropriate built-in
1196 // operator node.
1197 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1198 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001199 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001200
1201 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001202 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001203 }
1204
1205 case OR_No_Viable_Function:
1206 // No viable function; fall through to handling this as a
1207 // built-in operator, which will produce an error message for us.
1208 break;
1209
1210 case OR_Ambiguous:
1211 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1212 << UnaryOperator::getOpcodeStr(Opc)
1213 << Arg->getSourceRange();
1214 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001215 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001216 }
1217
1218 // Either we found no viable overloaded operator or we matched a
1219 // built-in operator. In either case, fall through to trying to
1220 // build a built-in operation.
1221 }
1222
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001223 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1224 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001225 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001226 return ExprError();
1227 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001228 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001229}
1230
Sebastian Redl8b769972009-01-19 00:08:26 +00001231Action::OwningExprResult
1232Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1233 ExprArg Idx, SourceLocation RLoc) {
1234 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1235 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001236
Douglas Gregor80723c52008-11-19 17:17:41 +00001237 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001238 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001239 LHSExp->getType()->isEnumeralType() ||
1240 RHSExp->getType()->isRecordType() ||
1241 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001242 // Add the appropriate overloaded operators (C++ [over.match.oper])
1243 // to the candidate set.
1244 OverloadCandidateSet CandidateSet;
1245 Expr *Args[2] = { LHSExp, RHSExp };
1246 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
Sebastian Redl8b769972009-01-19 00:08:26 +00001247
Douglas Gregor80723c52008-11-19 17:17:41 +00001248 // Perform overload resolution.
1249 OverloadCandidateSet::iterator Best;
1250 switch (BestViableFunction(CandidateSet, Best)) {
1251 case OR_Success: {
1252 // We found a built-in operator or an overloaded operator.
1253 FunctionDecl *FnDecl = Best->Function;
1254
1255 if (FnDecl) {
1256 // We matched an overloaded operator. Build a call to that
1257 // operator.
1258
1259 // Convert the arguments.
1260 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1261 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1262 PerformCopyInitialization(RHSExp,
1263 FnDecl->getParamDecl(0)->getType(),
1264 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001265 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001266 } else {
1267 // Convert the arguments.
1268 if (PerformCopyInitialization(LHSExp,
1269 FnDecl->getParamDecl(0)->getType(),
1270 "passing") ||
1271 PerformCopyInitialization(RHSExp,
1272 FnDecl->getParamDecl(1)->getType(),
1273 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001274 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001275 }
1276
1277 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001278 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001279 = FnDecl->getType()->getAsFunctionType()->getResultType();
1280 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001281
Douglas Gregor80723c52008-11-19 17:17:41 +00001282 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001283 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor80723c52008-11-19 17:17:41 +00001284 SourceLocation());
1285 UsualUnaryConversions(FnExpr);
1286
Sebastian Redl8b769972009-01-19 00:08:26 +00001287 Base.release();
1288 Idx.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001289 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, Args, 2,
1290 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001291 } else {
1292 // We matched a built-in operator. Convert the arguments, then
1293 // break out so that we will build the appropriate built-in
1294 // operator node.
1295 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1296 "passing") ||
1297 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1298 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001299 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001300
1301 break;
1302 }
1303 }
1304
1305 case OR_No_Viable_Function:
1306 // No viable function; fall through to handling this as a
1307 // built-in operator, which will produce an error message for us.
1308 break;
1309
1310 case OR_Ambiguous:
1311 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1312 << "[]"
1313 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1314 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001315 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001316 }
1317
1318 // Either we found no viable overloaded operator or we matched a
1319 // built-in operator. In either case, fall through to trying to
1320 // build a built-in operation.
1321 }
1322
Chris Lattner4b009652007-07-25 00:24:17 +00001323 // Perform default conversions.
1324 DefaultFunctionArrayConversion(LHSExp);
1325 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001326
Chris Lattner4b009652007-07-25 00:24:17 +00001327 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1328
1329 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001330 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001331 // in the subscript position. As a result, we need to derive the array base
1332 // and index from the expression types.
1333 Expr *BaseExpr, *IndexExpr;
1334 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001335 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001336 BaseExpr = LHSExp;
1337 IndexExpr = RHSExp;
1338 // FIXME: need to deal with const...
1339 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001340 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001341 // Handle the uncommon case of "123[Ptr]".
1342 BaseExpr = RHSExp;
1343 IndexExpr = LHSExp;
1344 // FIXME: need to deal with const...
1345 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001346 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1347 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001348 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001349
Chris Lattner4b009652007-07-25 00:24:17 +00001350 // FIXME: need to deal with const...
1351 ResultType = VTy->getElementType();
1352 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001353 return ExprError(Diag(LHSExp->getLocStart(),
1354 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1355 }
Chris Lattner4b009652007-07-25 00:24:17 +00001356 // C99 6.5.2.1p1
1357 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001358 return ExprError(Diag(IndexExpr->getLocStart(),
1359 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001360
1361 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1362 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001363 // void (*)(int)) and pointers to incomplete types. Functions are not
1364 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001365 if (!ResultType->isObjectType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001366 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001367 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001368 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001369
Sebastian Redl8b769972009-01-19 00:08:26 +00001370 Base.release();
1371 Idx.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001372 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1373 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001374}
1375
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001376QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001377CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001378 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001379 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001380
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001381 // The vector accessor can't exceed the number of elements.
1382 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001383
1384 // This flag determines whether or not the component is one of the four
1385 // special names that indicate a subset of exactly half the elements are
1386 // to be selected.
1387 bool HalvingSwizzle = false;
1388
1389 // This flag determines whether or not CompName has an 's' char prefix,
1390 // indicating that it is a string of hex values to be used as vector indices.
1391 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001392
1393 // Check that we've found one of the special components, or that the component
1394 // names must come from the same set.
1395 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001396 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1397 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001398 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001399 do
1400 compStr++;
1401 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001402 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001403 do
1404 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001405 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001406 }
Nate Begeman1486b502009-01-18 01:47:54 +00001407
1408 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001409 // We didn't get to the end of the string. This means the component names
1410 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001411 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1412 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001413 return QualType();
1414 }
Nate Begeman1486b502009-01-18 01:47:54 +00001415
1416 // Ensure no component accessor exceeds the width of the vector type it
1417 // operates on.
1418 if (!HalvingSwizzle) {
1419 compStr = CompName.getName();
1420
1421 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001422 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001423
1424 while (*compStr) {
1425 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1426 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1427 << baseType << SourceRange(CompLoc);
1428 return QualType();
1429 }
1430 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001431 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001432
Nate Begeman1486b502009-01-18 01:47:54 +00001433 // If this is a halving swizzle, verify that the base type has an even
1434 // number of elements.
1435 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001436 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001437 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001438 return QualType();
1439 }
1440
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001441 // The component accessor looks fine - now we need to compute the actual type.
1442 // The vector type is implied by the component accessor. For example,
1443 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001444 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001445 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001446 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1447 : CompName.getLength();
1448 if (HexSwizzle)
1449 CompSize--;
1450
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001451 if (CompSize == 1)
1452 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001453
Nate Begemanaf6ed502008-04-18 23:10:10 +00001454 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001455 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001456 // diagostics look bad. We want extended vector types to appear built-in.
1457 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1458 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1459 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001460 }
1461 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001462}
1463
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001464/// constructSetterName - Return the setter name for the given
1465/// identifier, i.e. "set" + Name where the initial character of Name
1466/// has been capitalized.
1467// FIXME: Merge with same routine in Parser. But where should this
1468// live?
1469static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1470 const IdentifierInfo *Name) {
1471 llvm::SmallString<100> SelectorName;
1472 SelectorName = "set";
1473 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1474 SelectorName[3] = toupper(SelectorName[3]);
1475 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1476}
1477
Sebastian Redl8b769972009-01-19 00:08:26 +00001478Action::OwningExprResult
1479Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1480 tok::TokenKind OpKind, SourceLocation MemberLoc,
1481 IdentifierInfo &Member) {
1482 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001483 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001484
1485 // Perform default conversions.
1486 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001487
Steve Naroff2cb66382007-07-26 03:11:44 +00001488 QualType BaseType = BaseExpr->getType();
1489 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001490
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001491 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1492 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001493 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001494 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001495 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001496 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001497 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1498 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001499 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001500 return ExprError(Diag(MemberLoc,
1501 diag::err_typecheck_member_reference_arrow)
1502 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001503 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001504
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001505 // Handle field access to simple records. This also handles access to fields
1506 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001507 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001508 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001509 if (DiagnoseIncompleteType(OpLoc, BaseType,
1510 diag::err_typecheck_incomplete_tag,
1511 BaseExpr->getSourceRange()))
1512 return ExprError();
1513
Steve Naroff2cb66382007-07-26 03:11:44 +00001514 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001515 // FIXME: Qualified name lookup for C++ is a bit more complicated
1516 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001517 LookupResult Result
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001518 = LookupQualifiedName(RDecl, DeclarationName(&Member),
1519 LookupCriteria(LookupCriteria::Member,
1520 /*RedeclarationOnly=*/false,
1521 getLangOptions().CPlusPlus));
1522
1523 Decl *MemberDecl = 0;
1524 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001525 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1526 << &Member << BaseExpr->getSourceRange());
1527 else if (Result.isAmbiguous()) {
1528 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1529 MemberLoc, BaseExpr->getSourceRange());
1530 return ExprError();
1531 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001532 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001533
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001534 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001535 // We may have found a field within an anonymous union or struct
1536 // (C++ [class.union]).
1537 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001538 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001539 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001540
Douglas Gregor82d44772008-12-20 23:49:58 +00001541 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1542 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001543 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001544 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1545 MemberType = Ref->getPointeeType();
1546 else {
1547 unsigned combinedQualifiers =
1548 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001549 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001550 combinedQualifiers &= ~QualType::Const;
1551 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1552 }
Eli Friedman76b49832008-02-06 22:48:16 +00001553
Steve Naroff774e4152009-01-21 00:14:39 +00001554 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1555 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001556 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001557 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001558 Var, MemberLoc,
1559 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001560 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001561 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1562 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001563 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001564 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001565 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001566 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001567 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001568 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Enum,
Sebastian Redl8b769972009-01-19 00:08:26 +00001569 MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001570 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001571 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1572 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001573
Douglas Gregor82d44772008-12-20 23:49:58 +00001574 // We found a declaration kind that we didn't expect. This is a
1575 // generic error message that tells the user that she can't refer
1576 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001577 return ExprError(Diag(MemberLoc,
1578 diag::err_typecheck_member_reference_unknown)
1579 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001580 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001581
Chris Lattnere9d71612008-07-21 04:59:05 +00001582 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1583 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001584 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001585 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Steve Naroff774e4152009-01-21 00:14:39 +00001586 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1587 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001588 OpKind == tok::arrow);
1589 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001590 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001591 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001592 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1593 << IFTy->getDecl()->getDeclName() << &Member
1594 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001595 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001596
Chris Lattnere9d71612008-07-21 04:59:05 +00001597 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1598 // pointer to a (potentially qualified) interface type.
1599 const PointerType *PTy;
1600 const ObjCInterfaceType *IFTy;
1601 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1602 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1603 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001604
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001605 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001606 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001607 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001608 MemberLoc, BaseExpr));
1609
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001610 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001611 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1612 E = IFTy->qual_end(); I != E; ++I)
1613 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001614 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001615 MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001616
1617 // If that failed, look for an "implicit" property by seeing if the nullary
1618 // selector is implemented.
1619
1620 // FIXME: The logic for looking up nullary and unary selectors should be
1621 // shared with the code in ActOnInstanceMessage.
1622
1623 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1624 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001625
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001626 // If this reference is in an @implementation, check for 'private' methods.
1627 if (!Getter)
1628 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1629 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1630 if (ObjCImplementationDecl *ImpDecl =
1631 ObjCImplementations[ClassDecl->getIdentifier()])
1632 Getter = ImpDecl->getInstanceMethod(Sel);
1633
Steve Naroff04151f32008-10-22 19:16:27 +00001634 // Look through local category implementations associated with the class.
1635 if (!Getter) {
1636 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1637 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1638 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1639 }
1640 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001641 if (Getter) {
1642 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001643 // will look for the matching setter, in case it is needed.
1644 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1645 &Member);
1646 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1647 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1648 if (!Setter) {
1649 // If this reference is in an @implementation, also check for 'private'
1650 // methods.
1651 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1652 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1653 if (ObjCImplementationDecl *ImpDecl =
1654 ObjCImplementations[ClassDecl->getIdentifier()])
1655 Setter = ImpDecl->getInstanceMethod(SetterSel);
1656 }
1657 // Look through local category implementations associated with the class.
1658 if (!Setter) {
1659 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1660 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1661 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1662 }
1663 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001664
1665 // FIXME: we must check that the setter has property type.
Steve Naroff774e4152009-01-21 00:14:39 +00001666 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
1667 Setter, MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001668 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001669
1670 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1671 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001672 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001673 // Handle properties on qualified "id" protocols.
1674 const ObjCQualifiedIdType *QIdTy;
1675 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1676 // Check protocols on qualified interfaces.
1677 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001678 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroffd1d44402008-10-20 22:53:06 +00001679 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Steve Naroff774e4152009-01-21 00:14:39 +00001680 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Sebastian Redl8b769972009-01-19 00:08:26 +00001681 MemberLoc, BaseExpr));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001682 // Also must look for a getter name which uses property syntax.
1683 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1684 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Steve Naroff774e4152009-01-21 00:14:39 +00001685 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
1686 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001687 }
1688 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001689
1690 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1691 << &Member << BaseType);
1692 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001693 // Handle 'field access' to vectors, such as 'V.xx'.
1694 if (BaseType->isExtVectorType() && OpKind == tok::period) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001695 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1696 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001697 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00001698 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
1699 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001700 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001701
1702 return ExprError(Diag(MemberLoc,
1703 diag::err_typecheck_member_reference_struct_union)
1704 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001705}
1706
Douglas Gregor3257fb52008-12-22 05:46:06 +00001707/// ConvertArgumentsForCall - Converts the arguments specified in
1708/// Args/NumArgs to the parameter types of the function FDecl with
1709/// function prototype Proto. Call is the call expression itself, and
1710/// Fn is the function expression. For a C++ member function, this
1711/// routine does not attempt to convert the object argument. Returns
1712/// true if the call is ill-formed.
1713bool
1714Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1715 FunctionDecl *FDecl,
1716 const FunctionTypeProto *Proto,
1717 Expr **Args, unsigned NumArgs,
1718 SourceLocation RParenLoc) {
1719 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1720 // assignment, to the types of the corresponding parameter, ...
1721 unsigned NumArgsInProto = Proto->getNumArgs();
1722 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001723 bool Invalid = false;
1724
Douglas Gregor3257fb52008-12-22 05:46:06 +00001725 // If too few arguments are available (and we don't have default
1726 // arguments for the remaining parameters), don't make the call.
1727 if (NumArgs < NumArgsInProto) {
1728 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1729 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1730 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1731 // Use default arguments for missing arguments
1732 NumArgsToCheck = NumArgsInProto;
1733 Call->setNumArgs(NumArgsInProto);
1734 }
1735
1736 // If too many are passed and not variadic, error on the extras and drop
1737 // them.
1738 if (NumArgs > NumArgsInProto) {
1739 if (!Proto->isVariadic()) {
1740 Diag(Args[NumArgsInProto]->getLocStart(),
1741 diag::err_typecheck_call_too_many_args)
1742 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1743 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1744 Args[NumArgs-1]->getLocEnd());
1745 // This deletes the extra arguments.
1746 Call->setNumArgs(NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001747 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001748 }
1749 NumArgsToCheck = NumArgsInProto;
1750 }
1751
1752 // Continue to check argument types (even if we have too few/many args).
1753 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1754 QualType ProtoArgType = Proto->getArgType(i);
1755
1756 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001757 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001758 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001759
1760 // Pass the argument.
1761 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1762 return true;
1763 } else
1764 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00001765 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001766 QualType ArgType = Arg->getType();
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001767
Douglas Gregor3257fb52008-12-22 05:46:06 +00001768 Call->setArg(i, Arg);
1769 }
1770
1771 // If this is a variadic call, handle args passed through "...".
1772 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001773 VariadicCallType CallType = VariadicFunction;
1774 if (Fn->getType()->isBlockPointerType())
1775 CallType = VariadicBlock; // Block
1776 else if (isa<MemberExpr>(Fn))
1777 CallType = VariadicMethod;
1778
Douglas Gregor3257fb52008-12-22 05:46:06 +00001779 // Promote the arguments (C99 6.5.2.2p7).
1780 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1781 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001782 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001783 Call->setArg(i, Arg);
1784 }
1785 }
1786
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001787 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001788}
1789
Steve Naroff87d58b42007-09-16 03:34:24 +00001790/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001791/// This provides the location of the left/right parens and a list of comma
1792/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00001793Action::OwningExprResult
1794Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1795 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001796 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001797 unsigned NumArgs = args.size();
1798 Expr *Fn = static_cast<Expr *>(fn.release());
1799 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00001800 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001801 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001802 OverloadedFunctionDecl *Ovl = NULL;
1803
Douglas Gregora133e262008-12-06 00:22:45 +00001804 // Determine whether this is a dependent call inside a C++ template,
1805 // in which case we won't do any semantic analysis now.
1806 bool Dependent = false;
1807 if (Fn->isTypeDependent()) {
1808 if (CXXDependentNameExpr *FnName = dyn_cast<CXXDependentNameExpr>(Fn)) {
1809 if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1810 Dependent = true;
1811 else {
1812 // Resolve the CXXDependentNameExpr to an actual identifier;
1813 // it wasn't really a dependent name after all.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001814 OwningExprResult Resolved
1815 = ActOnDeclarationNameExpr(S, FnName->getLocation(),
1816 FnName->getName(),
Douglas Gregora133e262008-12-06 00:22:45 +00001817 /*HasTrailingLParen=*/true,
1818 /*SS=*/0,
1819 /*ForceResolution=*/true);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001820 if (Resolved.isInvalid())
Sebastian Redl8b769972009-01-19 00:08:26 +00001821 return ExprError();
Douglas Gregora133e262008-12-06 00:22:45 +00001822 else {
1823 delete Fn;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001824 Fn = (Expr *)Resolved.release();
Douglas Gregora133e262008-12-06 00:22:45 +00001825 }
1826 }
1827 } else
1828 Dependent = true;
1829 } else
1830 Dependent = Expr::hasAnyTypeDependentArguments(Args, NumArgs);
1831
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001832 // FIXME: Will need to cache the results of name lookup (including
1833 // ADL) in Fn.
Douglas Gregora133e262008-12-06 00:22:45 +00001834 if (Dependent)
Steve Naroff774e4152009-01-21 00:14:39 +00001835 return Owned(new (Context) CallExpr(Fn, Args, NumArgs,
1836 Context.DependentTy, RParenLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001837
Douglas Gregor3257fb52008-12-22 05:46:06 +00001838 // Determine whether this is a call to an object (C++ [over.call.object]).
1839 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001840 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1841 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001842
1843 // Determine whether this is a call to a member function.
1844 if (getLangOptions().CPlusPlus) {
1845 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1846 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1847 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00001848 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1849 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001850 }
1851
Douglas Gregord2baafd2008-10-21 16:13:35 +00001852 // If we're directly calling a function or a set of overloaded
1853 // functions, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00001854 DeclRefExpr *DRExpr = NULL;
1855 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1856 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1857 else
1858 DRExpr = dyn_cast<DeclRefExpr>(Fn);
Sebastian Redl8b769972009-01-19 00:08:26 +00001859
Douglas Gregor566782a2009-01-06 05:10:23 +00001860 if (DRExpr) {
1861 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1862 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
Douglas Gregord2baafd2008-10-21 16:13:35 +00001863 }
1864
Douglas Gregord2baafd2008-10-21 16:13:35 +00001865 if (Ovl) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001866 FDecl = ResolveOverloadedCallFn(Fn, Ovl, LParenLoc, Args, NumArgs,
1867 CommaLocs, RParenLoc);
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001868 if (!FDecl)
Sebastian Redl8b769972009-01-19 00:08:26 +00001869 return ExprError();
Douglas Gregord2baafd2008-10-21 16:13:35 +00001870
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001871 // Update Fn to refer to the actual function selected.
Douglas Gregor566782a2009-01-06 05:10:23 +00001872 Expr *NewFn = 0;
1873 if (QualifiedDeclRefExpr *QDRExpr = dyn_cast<QualifiedDeclRefExpr>(DRExpr))
Steve Naroff774e4152009-01-21 00:14:39 +00001874 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregor566782a2009-01-06 05:10:23 +00001875 QDRExpr->getLocation(), false, false,
1876 QDRExpr->getSourceRange().getBegin());
1877 else
Steve Naroff774e4152009-01-21 00:14:39 +00001878 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
1879 Fn->getSourceRange().getBegin());
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001880 Fn->Destroy(Context);
1881 Fn = NewFn;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001882 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001883
1884 // Promote the function operand.
1885 UsualUnaryConversions(Fn);
1886
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001887 // Make the call expr early, before semantic checks. This guarantees cleanup
1888 // of arguments and function on error.
Sebastian Redl8b769972009-01-19 00:08:26 +00001889 // FIXME: Except that llvm::OwningPtr uses delete, when it really must be
1890 // Destroy(), or nothing gets cleaned up.
Steve Naroff774e4152009-01-21 00:14:39 +00001891 llvm::OwningPtr<CallExpr> TheCall(new (Context) CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001892 Context.BoolTy, RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001893
Steve Naroffd6163f32008-09-05 22:11:13 +00001894 const FunctionType *FuncT;
1895 if (!Fn->getType()->isBlockPointerType()) {
1896 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1897 // have type pointer to function".
1898 const PointerType *PT = Fn->getType()->getAsPointerType();
1899 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00001900 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1901 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00001902 FuncT = PT->getPointeeType()->getAsFunctionType();
1903 } else { // This is a block call.
1904 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1905 getAsFunctionType();
1906 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001907 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00001908 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1909 << Fn->getType() << Fn->getSourceRange());
1910
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001911 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001912 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00001913
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001914 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001915 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
1916 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00001917 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001918 } else {
1919 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00001920
Steve Naroffdb65e052007-08-28 23:30:39 +00001921 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001922 for (unsigned i = 0; i != NumArgs; i++) {
1923 Expr *Arg = Args[i];
1924 DefaultArgumentPromotion(Arg);
1925 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001926 }
Chris Lattner4b009652007-07-25 00:24:17 +00001927 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001928
Douglas Gregor3257fb52008-12-22 05:46:06 +00001929 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
1930 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00001931 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
1932 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00001933
Chris Lattner2e64c072007-08-10 20:18:51 +00001934 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001935 if (FDecl)
1936 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001937
Sebastian Redl8b769972009-01-19 00:08:26 +00001938 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00001939}
1940
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001941Action::OwningExprResult
1942Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
1943 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001944 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001945 QualType literalType = QualType::getFromOpaquePtr(Ty);
1946 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001947 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001948 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00001949
Eli Friedman8c2173d2008-05-20 05:22:08 +00001950 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001951 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001952 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
1953 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001954 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
1955 diag::err_typecheck_decl_incomplete_type,
1956 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001957 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00001958
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001959 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001960 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001961 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00001962
Chris Lattnere5cb5862008-12-04 23:50:19 +00001963 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001964 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001965 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001966 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00001967 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001968 InitExpr.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001969 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
1970 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00001971}
1972
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001973Action::OwningExprResult
1974Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
1975 InitListDesignations &Designators,
1976 SourceLocation RBraceLoc) {
1977 unsigned NumInit = initlist.size();
1978 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00001979
Steve Naroff0acc9c92007-09-15 18:49:24 +00001980 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001981 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001982
Steve Naroff774e4152009-01-21 00:14:39 +00001983 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
1984 RBraceLoc, Designators.hasAnyDesignators());
Chris Lattner48d7f382008-04-02 04:24:33 +00001985 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001986 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00001987}
1988
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001989/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001990bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001991 UsualUnaryConversions(castExpr);
1992
1993 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1994 // type needs to be scalar.
1995 if (castType->isVoidType()) {
1996 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001997 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
1998 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001999 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002000 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2001 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2002 (castType->isStructureType() || castType->isUnionType())) {
2003 // GCC struct/union extension: allow cast to self.
2004 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2005 << castType << castExpr->getSourceRange();
2006 } else if (castType->isUnionType()) {
2007 // GCC cast to union extension
2008 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2009 RecordDecl::field_iterator Field, FieldEnd;
2010 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2011 Field != FieldEnd; ++Field) {
2012 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2013 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2014 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2015 << castExpr->getSourceRange();
2016 break;
2017 }
2018 }
2019 if (Field == FieldEnd)
2020 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2021 << castExpr->getType() << castExpr->getSourceRange();
2022 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002023 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002024 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002025 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002026 }
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002027 } else if (!castExpr->getType()->isScalarType() &&
2028 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002029 return Diag(castExpr->getLocStart(),
2030 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002031 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002032 } else if (castExpr->getType()->isVectorType()) {
2033 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2034 return true;
2035 } else if (castType->isVectorType()) {
2036 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2037 return true;
2038 }
2039 return false;
2040}
2041
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002042bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002043 assert(VectorTy->isVectorType() && "Not a vector type!");
2044
2045 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002046 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002047 return Diag(R.getBegin(),
2048 Ty->isVectorType() ?
2049 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002050 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002051 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002052 } else
2053 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002054 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002055 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002056
2057 return false;
2058}
2059
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002060Action::OwningExprResult
2061Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2062 SourceLocation RParenLoc, ExprArg Op) {
2063 assert((Ty != 0) && (Op.get() != 0) &&
2064 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002065
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002066 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002067 QualType castType = QualType::getFromOpaquePtr(Ty);
2068
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002069 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002070 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002071 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002072 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002073}
2074
Chris Lattner98a425c2007-11-26 01:40:58 +00002075/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2076/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00002077inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
2078 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
2079 UsualUnaryConversions(cond);
2080 UsualUnaryConversions(lex);
2081 UsualUnaryConversions(rex);
2082 QualType condT = cond->getType();
2083 QualType lexT = lex->getType();
2084 QualType rexT = rex->getType();
2085
2086 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002087 if (!cond->isTypeDependent()) {
2088 if (!condT->isScalarType()) { // C99 6.5.15p2
2089 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
2090 return QualType();
2091 }
Chris Lattner4b009652007-07-25 00:24:17 +00002092 }
Chris Lattner992ae932008-01-06 22:42:25 +00002093
2094 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002095 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
2096 return Context.DependentTy;
2097
Chris Lattner992ae932008-01-06 22:42:25 +00002098 // If both operands have arithmetic type, do the usual arithmetic conversions
2099 // to find a common type: C99 6.5.15p3,5.
2100 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002101 UsualArithmeticConversions(lex, rex);
2102 return lex->getType();
2103 }
Chris Lattner992ae932008-01-06 22:42:25 +00002104
2105 // If both operands are the same structure or union type, the result is that
2106 // type.
Chris Lattner71225142007-07-31 21:27:01 +00002107 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00002108 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002109 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00002110 // "If both the operands have structure or union type, the result has
2111 // that type." This implies that CV qualifiers are dropped.
2112 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002113 }
Chris Lattner992ae932008-01-06 22:42:25 +00002114
2115 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002116 // The following || allows only one side to be void (a GCC-ism).
2117 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00002118 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002119 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2120 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00002121 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002122 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2123 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00002124 ImpCastExprToType(lex, Context.VoidTy);
2125 ImpCastExprToType(rex, Context.VoidTy);
2126 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002127 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002128 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2129 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002130 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2131 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002132 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002133 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002134 return lexT;
2135 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002136 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2137 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002138 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002139 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002140 return rexT;
2141 }
Chris Lattner0ac51632008-01-06 22:50:31 +00002142 // Handle the case where both operands are pointers before we handle null
2143 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00002144 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2145 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2146 // get the "pointed to" types
2147 QualType lhptee = LHSPT->getPointeeType();
2148 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002149
Chris Lattner71225142007-07-31 21:27:01 +00002150 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2151 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002152 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002153 // Figure out necessary qualifiers (C99 6.5.15p6)
2154 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002155 QualType destType = Context.getPointerType(destPointee);
2156 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2157 ImpCastExprToType(rex, destType); // promote to void*
2158 return destType;
2159 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002160 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002161 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002162 QualType destType = Context.getPointerType(destPointee);
2163 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2164 ImpCastExprToType(rex, destType); // promote to void*
2165 return destType;
2166 }
Chris Lattner4b009652007-07-25 00:24:17 +00002167
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002168 QualType compositeType = lexT;
2169
2170 // If either type is an Objective-C object type then check
2171 // compatibility according to Objective-C.
2172 if (Context.isObjCObjectPointerType(lexT) ||
2173 Context.isObjCObjectPointerType(rexT)) {
2174 // If both operands are interfaces and either operand can be
2175 // assigned to the other, use that type as the composite
2176 // type. This allows
2177 // xxx ? (A*) a : (B*) b
2178 // where B is a subclass of A.
2179 //
2180 // Additionally, as for assignment, if either type is 'id'
2181 // allow silent coercion. Finally, if the types are
2182 // incompatible then make sure to use 'id' as the composite
2183 // type so the result is acceptable for sending messages to.
2184
2185 // FIXME: This code should not be localized to here. Also this
2186 // should use a compatible check instead of abusing the
2187 // canAssignObjCInterfaces code.
2188 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2189 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2190 if (LHSIface && RHSIface &&
2191 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2192 compositeType = lexT;
2193 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002194 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002195 compositeType = rexT;
2196 } else if (Context.isObjCIdType(lhptee) ||
2197 Context.isObjCIdType(rhptee)) {
2198 // FIXME: This code looks wrong, because isObjCIdType checks
2199 // the struct but getObjCIdType returns the pointer to
2200 // struct. This is horrible and should be fixed.
2201 compositeType = Context.getObjCIdType();
2202 } else {
2203 QualType incompatTy = Context.getObjCIdType();
2204 ImpCastExprToType(lex, incompatTy);
2205 ImpCastExprToType(rex, incompatTy);
2206 return incompatTy;
2207 }
2208 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2209 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002210 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002211 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002212 // In this situation, we assume void* type. No especially good
2213 // reason, but this is what gcc does, and we do have to pick
2214 // to get a consistent AST.
2215 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002216 ImpCastExprToType(lex, incompatTy);
2217 ImpCastExprToType(rex, incompatTy);
2218 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002219 }
2220 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002221 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2222 // differently qualified versions of compatible types, the result type is
2223 // a pointer to an appropriately qualified version of the *composite*
2224 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002225 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002226 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00002227 ImpCastExprToType(lex, compositeType);
2228 ImpCastExprToType(rex, compositeType);
2229 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002230 }
Chris Lattner4b009652007-07-25 00:24:17 +00002231 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002232 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2233 // evaluates to "struct objc_object *" (and is handled above when comparing
2234 // id with statically typed objects).
2235 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2236 // GCC allows qualified id and any Objective-C type to devolve to
2237 // id. Currently localizing to here until clear this should be
2238 // part of ObjCQualifiedIdTypesAreCompatible.
2239 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2240 (lexT->isObjCQualifiedIdType() &&
2241 Context.isObjCObjectPointerType(rexT)) ||
2242 (rexT->isObjCQualifiedIdType() &&
2243 Context.isObjCObjectPointerType(lexT))) {
2244 // FIXME: This is not the correct composite type. This only
2245 // happens to work because id can more or less be used anywhere,
2246 // however this may change the type of method sends.
2247 // FIXME: gcc adds some type-checking of the arguments and emits
2248 // (confusing) incompatible comparison warnings in some
2249 // cases. Investigate.
2250 QualType compositeType = Context.getObjCIdType();
2251 ImpCastExprToType(lex, compositeType);
2252 ImpCastExprToType(rex, compositeType);
2253 return compositeType;
2254 }
2255 }
2256
Steve Naroff3eac7692008-09-10 19:17:48 +00002257 // Selection between block pointer types is ok as long as they are the same.
2258 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2259 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2260 return lexT;
2261
Chris Lattner992ae932008-01-06 22:42:25 +00002262 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00002263 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002264 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002265 return QualType();
2266}
2267
Steve Naroff87d58b42007-09-16 03:34:24 +00002268/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002269/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002270Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2271 SourceLocation ColonLoc,
2272 ExprArg Cond, ExprArg LHS,
2273 ExprArg RHS) {
2274 Expr *CondExpr = (Expr *) Cond.get();
2275 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002276
2277 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2278 // was the condition.
2279 bool isLHSNull = LHSExpr == 0;
2280 if (isLHSNull)
2281 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002282
2283 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002284 RHSExpr, QuestionLoc);
2285 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002286 return ExprError();
2287
2288 Cond.release();
2289 LHS.release();
2290 RHS.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002291 return Owned(new (Context) ConditionalOperator(CondExpr,
2292 isLHSNull ? 0 : LHSExpr,
2293 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002294}
2295
Chris Lattner4b009652007-07-25 00:24:17 +00002296
2297// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2298// being closely modeled after the C99 spec:-). The odd characteristic of this
2299// routine is it effectively iqnores the qualifiers on the top level pointee.
2300// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2301// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00002302Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002303Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2304 QualType lhptee, rhptee;
2305
2306 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002307 lhptee = lhsType->getAsPointerType()->getPointeeType();
2308 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002309
2310 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002311 lhptee = Context.getCanonicalType(lhptee);
2312 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002313
Chris Lattner005ed752008-01-04 18:04:52 +00002314 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002315
2316 // C99 6.5.16.1p1: This following citation is common to constraints
2317 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2318 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00002319 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002320 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002321 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002322
2323 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2324 // incomplete type and the other is a pointer to a qualified or unqualified
2325 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002326 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002327 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002328 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002329
2330 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002331 assert(rhptee->isFunctionType());
2332 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002333 }
2334
2335 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002336 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002337 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002338
2339 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002340 assert(lhptee->isFunctionType());
2341 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002342 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002343
2344 // Check for ObjC interfaces
2345 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2346 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2347 if (LHSIface && RHSIface &&
2348 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2349 return ConvTy;
2350
2351 // ID acts sort of like void* for ObjC interfaces
2352 if (LHSIface && Context.isObjCIdType(rhptee))
2353 return ConvTy;
2354 if (RHSIface && Context.isObjCIdType(lhptee))
2355 return ConvTy;
2356
Chris Lattner4b009652007-07-25 00:24:17 +00002357 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2358 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002359 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2360 rhptee.getUnqualifiedType()))
2361 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002362 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002363}
2364
Steve Naroff3454b6c2008-09-04 15:10:53 +00002365/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2366/// block pointer types are compatible or whether a block and normal pointer
2367/// are compatible. It is more restrict than comparing two function pointer
2368// types.
2369Sema::AssignConvertType
2370Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2371 QualType rhsType) {
2372 QualType lhptee, rhptee;
2373
2374 // get the "pointed to" type (ignoring qualifiers at the top level)
2375 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2376 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2377
2378 // make sure we operate on the canonical type
2379 lhptee = Context.getCanonicalType(lhptee);
2380 rhptee = Context.getCanonicalType(rhptee);
2381
2382 AssignConvertType ConvTy = Compatible;
2383
2384 // For blocks we enforce that qualifiers are identical.
2385 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2386 ConvTy = CompatiblePointerDiscardsQualifiers;
2387
2388 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2389 return IncompatibleBlockPointer;
2390 return ConvTy;
2391}
2392
Chris Lattner4b009652007-07-25 00:24:17 +00002393/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2394/// has code to accommodate several GCC extensions when type checking
2395/// pointers. Here are some objectionable examples that GCC considers warnings:
2396///
2397/// int a, *pint;
2398/// short *pshort;
2399/// struct foo *pfoo;
2400///
2401/// pint = pshort; // warning: assignment from incompatible pointer type
2402/// a = pint; // warning: assignment makes integer from pointer without a cast
2403/// pint = a; // warning: assignment makes pointer from integer without a cast
2404/// pint = pfoo; // warning: assignment from incompatible pointer type
2405///
2406/// As a result, the code for dealing with pointers is more complex than the
2407/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002408///
Chris Lattner005ed752008-01-04 18:04:52 +00002409Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002410Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002411 // Get canonical types. We're not formatting these types, just comparing
2412 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002413 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2414 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002415
2416 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002417 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002418
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002419 // If the left-hand side is a reference type, then we are in a
2420 // (rare!) case where we've allowed the use of references in C,
2421 // e.g., as a parameter type in a built-in function. In this case,
2422 // just make sure that the type referenced is compatible with the
2423 // right-hand side type. The caller is responsible for adjusting
2424 // lhsType so that the resulting expression does not have reference
2425 // type.
2426 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2427 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002428 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002429 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002430 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002431
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002432 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2433 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002434 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002435 // Relax integer conversions like we do for pointers below.
2436 if (rhsType->isIntegerType())
2437 return IntToPointer;
2438 if (lhsType->isIntegerType())
2439 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002440 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002441 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002442
Nate Begemanc5f0f652008-07-14 18:02:46 +00002443 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002444 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002445 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2446 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002447 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002448
Nate Begemanc5f0f652008-07-14 18:02:46 +00002449 // If we are allowing lax vector conversions, and LHS and RHS are both
2450 // vectors, the total size only needs to be the same. This is a bitcast;
2451 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002452 if (getLangOptions().LaxVectorConversions &&
2453 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002454 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2455 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002456 }
2457 return Incompatible;
2458 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002459
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002460 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002461 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002462
Chris Lattner390564e2008-04-07 06:49:41 +00002463 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002464 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002465 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002466
Chris Lattner390564e2008-04-07 06:49:41 +00002467 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002468 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002469
Steve Naroffa982c712008-09-29 18:10:17 +00002470 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002471 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002472 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002473
2474 // Treat block pointers as objects.
2475 if (getLangOptions().ObjC1 &&
2476 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2477 return Compatible;
2478 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002479 return Incompatible;
2480 }
2481
2482 if (isa<BlockPointerType>(lhsType)) {
2483 if (rhsType->isIntegerType())
2484 return IntToPointer;
2485
Steve Naroffa982c712008-09-29 18:10:17 +00002486 // Treat block pointers as objects.
2487 if (getLangOptions().ObjC1 &&
2488 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2489 return Compatible;
2490
Steve Naroff3454b6c2008-09-04 15:10:53 +00002491 if (rhsType->isBlockPointerType())
2492 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2493
2494 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2495 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002496 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002497 }
Chris Lattner1853da22008-01-04 23:18:45 +00002498 return Incompatible;
2499 }
2500
Chris Lattner390564e2008-04-07 06:49:41 +00002501 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002502 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002503 if (lhsType == Context.BoolTy)
2504 return Compatible;
2505
2506 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002507 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002508
Chris Lattner390564e2008-04-07 06:49:41 +00002509 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002510 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002511
2512 if (isa<BlockPointerType>(lhsType) &&
2513 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002514 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002515 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002516 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002517
Chris Lattner1853da22008-01-04 23:18:45 +00002518 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002519 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002520 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002521 }
2522 return Incompatible;
2523}
2524
Chris Lattner005ed752008-01-04 18:04:52 +00002525Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002526Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002527 if (getLangOptions().CPlusPlus) {
2528 if (!lhsType->isRecordType()) {
2529 // C++ 5.17p3: If the left operand is not of class type, the
2530 // expression is implicitly converted (C++ 4) to the
2531 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002532 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2533 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002534 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002535 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002536 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002537 }
2538
2539 // FIXME: Currently, we fall through and treat C++ classes like C
2540 // structures.
2541 }
2542
Steve Naroffcdee22d2007-11-27 17:58:44 +00002543 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2544 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002545 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2546 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002547 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002548 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002549 return Compatible;
2550 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002551
2552 // We don't allow conversion of non-null-pointer constants to integers.
2553 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2554 return IntToBlockPointer;
2555
Chris Lattner5f505bf2007-10-16 02:55:40 +00002556 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002557 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002558 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002559 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002560 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002561 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002562 if (!lhsType->isReferenceType())
2563 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002564
Chris Lattner005ed752008-01-04 18:04:52 +00002565 Sema::AssignConvertType result =
2566 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002567
2568 // C99 6.5.16.1p2: The value of the right operand is converted to the
2569 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002570 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2571 // so that we can use references in built-in functions even in C.
2572 // The getNonReferenceType() call makes sure that the resulting expression
2573 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002574 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002575 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002576 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002577}
2578
Chris Lattner005ed752008-01-04 18:04:52 +00002579Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002580Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2581 return CheckAssignmentConstraints(lhsType, rhsType);
2582}
2583
Chris Lattner1eafdea2008-11-18 01:30:42 +00002584QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002585 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002586 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002587 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002588 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002589}
2590
Chris Lattner1eafdea2008-11-18 01:30:42 +00002591inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002592 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002593 // For conversion purposes, we ignore any qualifiers.
2594 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002595 QualType lhsType =
2596 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2597 QualType rhsType =
2598 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002599
Nate Begemanc5f0f652008-07-14 18:02:46 +00002600 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002601 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002602 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002603
Nate Begemanc5f0f652008-07-14 18:02:46 +00002604 // Handle the case of a vector & extvector type of the same size and element
2605 // type. It would be nice if we only had one vector type someday.
2606 if (getLangOptions().LaxVectorConversions)
2607 if (const VectorType *LV = lhsType->getAsVectorType())
2608 if (const VectorType *RV = rhsType->getAsVectorType())
2609 if (LV->getElementType() == RV->getElementType() &&
2610 LV->getNumElements() == RV->getNumElements())
2611 return lhsType->isExtVectorType() ? lhsType : rhsType;
2612
2613 // If the lhs is an extended vector and the rhs is a scalar of the same type
2614 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002615 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002616 QualType eltType = V->getElementType();
2617
2618 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2619 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2620 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002621 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002622 return lhsType;
2623 }
2624 }
2625
Nate Begemanc5f0f652008-07-14 18:02:46 +00002626 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002627 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002628 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002629 QualType eltType = V->getElementType();
2630
2631 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2632 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2633 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002634 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002635 return rhsType;
2636 }
2637 }
2638
Chris Lattner4b009652007-07-25 00:24:17 +00002639 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002640 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002641 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002642 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002643 return QualType();
2644}
2645
2646inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002647 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002648{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002649 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002650 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002651
Steve Naroff8f708362007-08-24 19:07:16 +00002652 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002653
Chris Lattner4b009652007-07-25 00:24:17 +00002654 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002655 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002656 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002657}
2658
2659inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002660 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002661{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002662 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2663 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2664 return CheckVectorOperands(Loc, lex, rex);
2665 return InvalidOperands(Loc, lex, rex);
2666 }
Chris Lattner4b009652007-07-25 00:24:17 +00002667
Steve Naroff8f708362007-08-24 19:07:16 +00002668 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002669
Chris Lattner4b009652007-07-25 00:24:17 +00002670 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002671 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002672 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002673}
2674
2675inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002676 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002677{
2678 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002679 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002680
Steve Naroff8f708362007-08-24 19:07:16 +00002681 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002682
Chris Lattner4b009652007-07-25 00:24:17 +00002683 // handle the common case first (both operands are arithmetic).
2684 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002685 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002686
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002687 // Put any potential pointer into PExp
2688 Expr* PExp = lex, *IExp = rex;
2689 if (IExp->getType()->isPointerType())
2690 std::swap(PExp, IExp);
2691
2692 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2693 if (IExp->getType()->isIntegerType()) {
2694 // Check for arithmetic on pointers to incomplete types
2695 if (!PTy->getPointeeType()->isObjectType()) {
2696 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002697 if (getLangOptions().CPlusPlus) {
2698 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2699 << lex->getSourceRange() << rex->getSourceRange();
2700 return QualType();
2701 }
2702
2703 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00002704 Diag(Loc, diag::ext_gnu_void_ptr)
2705 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002706 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002707 if (getLangOptions().CPlusPlus) {
2708 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2709 << lex->getType() << lex->getSourceRange();
2710 return QualType();
2711 }
2712
2713 // GNU extension: arithmetic on pointer to function
2714 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002715 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002716 } else {
2717 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2718 diag::err_typecheck_arithmetic_incomplete_type,
2719 lex->getSourceRange(), SourceRange(),
2720 lex->getType());
2721 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002722 }
2723 }
2724 return PExp->getType();
2725 }
2726 }
2727
Chris Lattner1eafdea2008-11-18 01:30:42 +00002728 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002729}
2730
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002731// C99 6.5.6
2732QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002733 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002734 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002735 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002736
Steve Naroff8f708362007-08-24 19:07:16 +00002737 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002738
Chris Lattnerf6da2912007-12-09 21:53:25 +00002739 // Enforce type constraints: C99 6.5.6p3.
2740
2741 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002742 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002743 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002744
2745 // Either ptr - int or ptr - ptr.
2746 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002747 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002748
Chris Lattnerf6da2912007-12-09 21:53:25 +00002749 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002750 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002751 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002752 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002753 Diag(Loc, diag::ext_gnu_void_ptr)
2754 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00002755 } else if (lpointee->isFunctionType()) {
2756 if (getLangOptions().CPlusPlus) {
2757 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2758 << lex->getType() << lex->getSourceRange();
2759 return QualType();
2760 }
2761
2762 // GNU extension: arithmetic on pointer to function
2763 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2764 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002765 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002766 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002767 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002768 return QualType();
2769 }
2770 }
2771
2772 // The result type of a pointer-int computation is the pointer type.
2773 if (rex->getType()->isIntegerType())
2774 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002775
Chris Lattnerf6da2912007-12-09 21:53:25 +00002776 // Handle pointer-pointer subtractions.
2777 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002778 QualType rpointee = RHSPTy->getPointeeType();
2779
Chris Lattnerf6da2912007-12-09 21:53:25 +00002780 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002781 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002782 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002783 if (rpointee->isVoidType()) {
2784 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002785 Diag(Loc, diag::ext_gnu_void_ptr)
2786 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00002787 } else if (rpointee->isFunctionType()) {
2788 if (getLangOptions().CPlusPlus) {
2789 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2790 << rex->getType() << rex->getSourceRange();
2791 return QualType();
2792 }
2793
2794 // GNU extension: arithmetic on pointer to function
2795 if (!lpointee->isFunctionType())
2796 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2797 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002798 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002799 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002800 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002801 return QualType();
2802 }
2803 }
2804
2805 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002806 if (!Context.typesAreCompatible(
2807 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2808 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002809 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002810 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002811 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002812 return QualType();
2813 }
2814
2815 return Context.getPointerDiffType();
2816 }
2817 }
2818
Chris Lattner1eafdea2008-11-18 01:30:42 +00002819 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002820}
2821
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002822// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002823QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002824 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002825 // C99 6.5.7p2: Each of the operands shall have integer type.
2826 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002827 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002828
Chris Lattner2c8bff72007-12-12 05:47:28 +00002829 // Shifts don't perform usual arithmetic conversions, they just do integer
2830 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002831 if (!isCompAssign)
2832 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002833 UsualUnaryConversions(rex);
2834
2835 // "The type of the result is that of the promoted left operand."
2836 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002837}
2838
Eli Friedman0d9549b2008-08-22 00:56:42 +00002839static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2840 ASTContext& Context) {
2841 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2842 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2843 // ID acts sort of like void* for ObjC interfaces
2844 if (LHSIface && Context.isObjCIdType(RHS))
2845 return true;
2846 if (RHSIface && Context.isObjCIdType(LHS))
2847 return true;
2848 if (!LHSIface || !RHSIface)
2849 return false;
2850 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2851 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2852}
2853
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002854// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002855QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002856 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002857 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002858 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002859
Chris Lattner254f3bc2007-08-26 01:18:55 +00002860 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002861 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2862 UsualArithmeticConversions(lex, rex);
2863 else {
2864 UsualUnaryConversions(lex);
2865 UsualUnaryConversions(rex);
2866 }
Chris Lattner4b009652007-07-25 00:24:17 +00002867 QualType lType = lex->getType();
2868 QualType rType = rex->getType();
2869
Ted Kremenek486509e2007-10-29 17:13:39 +00002870 // For non-floating point types, check for self-comparisons of the form
2871 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2872 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002873 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002874 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2875 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002876 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002877 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002878 }
2879
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002880 // The result of comparisons is 'bool' in C++, 'int' in C.
2881 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2882
Chris Lattner254f3bc2007-08-26 01:18:55 +00002883 if (isRelational) {
2884 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002885 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002886 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002887 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002888 if (lType->isFloatingType()) {
2889 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002890 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002891 }
2892
Chris Lattner254f3bc2007-08-26 01:18:55 +00002893 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002894 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002895 }
Chris Lattner4b009652007-07-25 00:24:17 +00002896
Chris Lattner22be8422007-08-26 01:10:14 +00002897 bool LHSIsNull = lex->isNullPointerConstant(Context);
2898 bool RHSIsNull = rex->isNullPointerConstant(Context);
2899
Chris Lattner254f3bc2007-08-26 01:18:55 +00002900 // All of the following pointer related warnings are GCC extensions, except
2901 // when handling null pointer constants. One day, we can consider making them
2902 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002903 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002904 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002905 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002906 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002907 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002908
Steve Naroff3b435622007-11-13 14:57:38 +00002909 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002910 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2911 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002912 RCanPointeeTy.getUnqualifiedType()) &&
2913 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002914 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002915 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002916 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002917 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002918 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002919 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002920 // Handle block pointer types.
2921 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2922 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2923 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2924
2925 if (!LHSIsNull && !RHSIsNull &&
2926 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002927 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002928 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00002929 }
2930 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002931 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002932 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002933 // Allow block pointers to be compared with null pointer constants.
2934 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2935 (lType->isPointerType() && rType->isBlockPointerType())) {
2936 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002937 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002938 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00002939 }
2940 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002941 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00002942 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002943
Steve Naroff936c4362008-06-03 14:04:54 +00002944 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002945 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00002946 const PointerType *LPT = lType->getAsPointerType();
2947 const PointerType *RPT = rType->getAsPointerType();
2948 bool LPtrToVoid = LPT ?
2949 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2950 bool RPtrToVoid = RPT ?
2951 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2952
2953 if (!LPtrToVoid && !RPtrToVoid &&
2954 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002955 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002956 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00002957 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002958 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00002959 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002960 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002961 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002962 }
Steve Naroff936c4362008-06-03 14:04:54 +00002963 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2964 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002965 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002966 } else {
2967 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002968 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00002969 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002970 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002971 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002972 }
Steve Naroff936c4362008-06-03 14:04:54 +00002973 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002974 }
Steve Naroff936c4362008-06-03 14:04:54 +00002975 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2976 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002977 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002978 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002979 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002980 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002981 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002982 }
Steve Naroff936c4362008-06-03 14:04:54 +00002983 if (lType->isIntegerType() &&
2984 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002985 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002986 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002987 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002988 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002989 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002990 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002991 // Handle block pointers.
2992 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2993 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002994 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002995 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002996 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002997 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002998 }
2999 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3000 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003001 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003002 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003003 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003004 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003005 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003006 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003007}
3008
Nate Begemanc5f0f652008-07-14 18:02:46 +00003009/// CheckVectorCompareOperands - vector comparisons are a clang extension that
3010/// operates on extended vector types. Instead of producing an IntTy result,
3011/// like a scalar comparison, a vector comparison produces a vector of integer
3012/// types.
3013QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003014 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003015 bool isRelational) {
3016 // Check to make sure we're operating on vectors of the same type and width,
3017 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003018 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003019 if (vType.isNull())
3020 return vType;
3021
3022 QualType lType = lex->getType();
3023 QualType rType = rex->getType();
3024
3025 // For non-floating point types, check for self-comparisons of the form
3026 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3027 // often indicate logic errors in the program.
3028 if (!lType->isFloatingType()) {
3029 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3030 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3031 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003032 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003033 }
3034
3035 // Check for comparisons of floating point operands using != and ==.
3036 if (!isRelational && lType->isFloatingType()) {
3037 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003038 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003039 }
3040
3041 // Return the type for the comparison, which is the same as vector type for
3042 // integer vectors, or an integer type of identical size and number of
3043 // elements for floating point vectors.
3044 if (lType->isIntegerType())
3045 return lType;
3046
3047 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003048 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003049 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003050 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003051 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3052 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3053
3054 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3055 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003056 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3057}
3058
Chris Lattner4b009652007-07-25 00:24:17 +00003059inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00003060 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003061{
3062 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003063 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003064
Steve Naroff8f708362007-08-24 19:07:16 +00003065 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00003066
3067 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003068 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003069 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003070}
3071
3072inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00003073 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003074{
3075 UsualUnaryConversions(lex);
3076 UsualUnaryConversions(rex);
3077
Eli Friedmanbea3f842008-05-13 20:16:47 +00003078 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003079 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003080 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003081}
3082
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003083/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3084/// is a read-only property; return true if so. A readonly property expression
3085/// depends on various declarations and thus must be treated specially.
3086///
3087static bool IsReadonlyProperty(Expr *E, Sema &S)
3088{
3089 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3090 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3091 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3092 QualType BaseType = PropExpr->getBase()->getType();
3093 if (const PointerType *PTy = BaseType->getAsPointerType())
3094 if (const ObjCInterfaceType *IFTy =
3095 PTy->getPointeeType()->getAsObjCInterfaceType())
3096 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3097 if (S.isPropertyReadonly(PDecl, IFace))
3098 return true;
3099 }
3100 }
3101 return false;
3102}
3103
Chris Lattner4c2642c2008-11-18 01:22:49 +00003104/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3105/// emit an error and return true. If so, return false.
3106static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003107 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3108 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3109 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003110 if (IsLV == Expr::MLV_Valid)
3111 return false;
3112
3113 unsigned Diag = 0;
3114 bool NeedType = false;
3115 switch (IsLV) { // C99 6.5.16p2
3116 default: assert(0 && "Unknown result from isModifiableLvalue!");
3117 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00003118 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003119 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3120 NeedType = true;
3121 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003122 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003123 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3124 NeedType = true;
3125 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003126 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003127 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3128 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003129 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003130 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3131 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003132 case Expr::MLV_IncompleteType:
3133 case Expr::MLV_IncompleteVoidType:
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003134 return S.DiagnoseIncompleteType(Loc, E->getType(),
3135 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3136 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003137 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003138 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3139 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003140 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003141 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3142 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003143 case Expr::MLV_ReadonlyProperty:
3144 Diag = diag::error_readonly_property_assignment;
3145 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003146 case Expr::MLV_NoSetterProperty:
3147 Diag = diag::error_nosetter_property_assignment;
3148 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003149 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003150
Chris Lattner4c2642c2008-11-18 01:22:49 +00003151 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003152 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003153 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003154 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003155 return true;
3156}
3157
3158
3159
3160// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003161QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3162 SourceLocation Loc,
3163 QualType CompoundType) {
3164 // Verify that LHS is a modifiable lvalue, and emit error if not.
3165 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003166 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003167
3168 QualType LHSType = LHS->getType();
3169 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003170
Chris Lattner005ed752008-01-04 18:04:52 +00003171 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003172 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003173 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003174 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003175 // Special case of NSObject attributes on c-style pointer types.
3176 if (ConvTy == IncompatiblePointer &&
3177 ((Context.isObjCNSObjectType(LHSType) &&
3178 Context.isObjCObjectPointerType(RHSType)) ||
3179 (Context.isObjCNSObjectType(RHSType) &&
3180 Context.isObjCObjectPointerType(LHSType))))
3181 ConvTy = Compatible;
3182
Chris Lattner34c85082008-08-21 18:04:13 +00003183 // If the RHS is a unary plus or minus, check to see if they = and + are
3184 // right next to each other. If so, the user may have typo'd "x =+ 4"
3185 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003186 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003187 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3188 RHSCheck = ICE->getSubExpr();
3189 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3190 if ((UO->getOpcode() == UnaryOperator::Plus ||
3191 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003192 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003193 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003194 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003195 Diag(Loc, diag::warn_not_compound_assign)
3196 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3197 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003198 }
3199 } else {
3200 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003201 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003202 }
Chris Lattner005ed752008-01-04 18:04:52 +00003203
Chris Lattner1eafdea2008-11-18 01:30:42 +00003204 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3205 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003206 return QualType();
3207
Chris Lattner4b009652007-07-25 00:24:17 +00003208 // C99 6.5.16p3: The type of an assignment expression is the type of the
3209 // left operand unless the left operand has qualified type, in which case
3210 // it is the unqualified version of the type of the left operand.
3211 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3212 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003213 // C++ 5.17p1: the type of the assignment expression is that of its left
3214 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003215 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003216}
3217
Chris Lattner1eafdea2008-11-18 01:30:42 +00003218// C99 6.5.17
3219QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3220 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00003221
3222 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003223 DefaultFunctionArrayConversion(RHS);
3224 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003225}
3226
3227/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3228/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003229QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3230 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003231 QualType ResType = Op->getType();
3232 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003233
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003234 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3235 // Decrement of bool is not allowed.
3236 if (!isInc) {
3237 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3238 return QualType();
3239 }
3240 // Increment of bool sets it to true, but is deprecated.
3241 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3242 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003243 // OK!
3244 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3245 // C99 6.5.2.4p2, 6.5.6p2
3246 if (PT->getPointeeType()->isObjectType()) {
3247 // Pointer to object is ok!
3248 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003249 if (getLangOptions().CPlusPlus) {
3250 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3251 << Op->getSourceRange();
3252 return QualType();
3253 }
3254
3255 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003256 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003257 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003258 if (getLangOptions().CPlusPlus) {
3259 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3260 << Op->getType() << Op->getSourceRange();
3261 return QualType();
3262 }
3263
3264 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003265 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003266 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003267 } else {
3268 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3269 diag::err_typecheck_arithmetic_incomplete_type,
3270 Op->getSourceRange(), SourceRange(),
3271 ResType);
3272 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003273 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003274 } else if (ResType->isComplexType()) {
3275 // C99 does not support ++/-- on complex types, we allow as an extension.
3276 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003277 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003278 } else {
3279 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003280 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003281 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003282 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00003283 // At this point, we know we have a real, complex or pointer type.
3284 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003285 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003286 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003287 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003288}
3289
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003290/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003291/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003292/// where the declaration is needed for type checking. We only need to
3293/// handle cases when the expression references a function designator
3294/// or is an lvalue. Here are some examples:
3295/// - &(x) => x
3296/// - &*****f => f for f a function designator.
3297/// - &s.xx => s
3298/// - &s.zz[1].yy -> s, if zz is an array
3299/// - *(x + 1) -> x, if x is an array
3300/// - &"123"[2] -> 0
3301/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003302static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003303 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003304 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003305 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003306 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003307 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003308 // Fields cannot be declared with a 'register' storage class.
3309 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003310 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003311 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003312 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003313 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003314 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003315
Douglas Gregord2baafd2008-10-21 16:13:35 +00003316 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003317 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003318 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003319 return 0;
3320 else
3321 return VD;
3322 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003323 case Stmt::UnaryOperatorClass: {
3324 UnaryOperator *UO = cast<UnaryOperator>(E);
3325
3326 switch(UO->getOpcode()) {
3327 case UnaryOperator::Deref: {
3328 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003329 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3330 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3331 if (!VD || VD->getType()->isPointerType())
3332 return 0;
3333 return VD;
3334 }
3335 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003336 }
3337 case UnaryOperator::Real:
3338 case UnaryOperator::Imag:
3339 case UnaryOperator::Extension:
3340 return getPrimaryDecl(UO->getSubExpr());
3341 default:
3342 return 0;
3343 }
3344 }
3345 case Stmt::BinaryOperatorClass: {
3346 BinaryOperator *BO = cast<BinaryOperator>(E);
3347
3348 // Handle cases involving pointer arithmetic. The result of an
3349 // Assign or AddAssign is not an lvalue so they can be ignored.
3350
3351 // (x + n) or (n + x) => x
3352 if (BO->getOpcode() == BinaryOperator::Add) {
3353 if (BO->getLHS()->getType()->isPointerType()) {
3354 return getPrimaryDecl(BO->getLHS());
3355 } else if (BO->getRHS()->getType()->isPointerType()) {
3356 return getPrimaryDecl(BO->getRHS());
3357 }
3358 }
3359
3360 return 0;
3361 }
Chris Lattner4b009652007-07-25 00:24:17 +00003362 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003363 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003364 case Stmt::ImplicitCastExprClass:
3365 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003366 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003367 default:
3368 return 0;
3369 }
3370}
3371
3372/// CheckAddressOfOperand - The operand of & must be either a function
3373/// designator or an lvalue designating an object. If it is an lvalue, the
3374/// object cannot be declared with storage class register or be a bit field.
3375/// Note: The usual conversions are *not* applied to the operand of the &
3376/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00003377/// In C++, the operand might be an overloaded function name, in which case
3378/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003379QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003380 if (op->isTypeDependent())
3381 return Context.DependentTy;
3382
Steve Naroff9c6c3592008-01-13 17:10:08 +00003383 if (getLangOptions().C99) {
3384 // Implement C99-only parts of addressof rules.
3385 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3386 if (uOp->getOpcode() == UnaryOperator::Deref)
3387 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3388 // (assuming the deref expression is valid).
3389 return uOp->getSubExpr()->getType();
3390 }
3391 // Technically, there should be a check for array subscript
3392 // expressions here, but the result of one is always an lvalue anyway.
3393 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003394 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003395 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003396
Chris Lattner4b009652007-07-25 00:24:17 +00003397 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003398 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3399 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003400 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3401 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003402 return QualType();
3403 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003404 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003405 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3406 if (Field->isBitField()) {
3407 Diag(OpLoc, diag::err_typecheck_address_of)
3408 << "bit-field" << op->getSourceRange();
3409 return QualType();
3410 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003411 }
3412 // Check for Apple extension for accessing vector components.
3413 } else if (isa<ArraySubscriptExpr>(op) &&
3414 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003415 Diag(OpLoc, diag::err_typecheck_address_of)
3416 << "vector" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003417 return QualType();
3418 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00003419 // We have an lvalue with a decl. Make sure the decl is not declared
3420 // with the register storage-class specifier.
3421 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3422 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003423 Diag(OpLoc, diag::err_typecheck_address_of)
3424 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003425 return QualType();
3426 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003427 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003428 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003429 } else if (isa<FieldDecl>(dcl)) {
3430 // Okay: we can take the address of a field.
Nuno Lopesdf239522008-12-16 22:58:26 +00003431 } else if (isa<FunctionDecl>(dcl)) {
3432 // Okay: we can take the address of a function.
Douglas Gregor5b82d612008-12-10 21:26:49 +00003433 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003434 else
Chris Lattner4b009652007-07-25 00:24:17 +00003435 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003436 }
Chris Lattnera55e3212008-07-27 00:48:22 +00003437
Chris Lattner4b009652007-07-25 00:24:17 +00003438 // If the operand has type "type", the result has type "pointer to type".
3439 return Context.getPointerType(op->getType());
3440}
3441
Chris Lattnerda5c0872008-11-23 09:13:29 +00003442QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3443 UsualUnaryConversions(Op);
3444 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003445
Chris Lattnerda5c0872008-11-23 09:13:29 +00003446 // Note that per both C89 and C99, this is always legal, even if ptype is an
3447 // incomplete type or void. It would be possible to warn about dereferencing
3448 // a void pointer, but it's completely well-defined, and such a warning is
3449 // unlikely to catch any mistakes.
3450 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003451 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00003452
Chris Lattner77d52da2008-11-20 06:06:08 +00003453 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003454 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003455 return QualType();
3456}
3457
3458static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3459 tok::TokenKind Kind) {
3460 BinaryOperator::Opcode Opc;
3461 switch (Kind) {
3462 default: assert(0 && "Unknown binop!");
3463 case tok::star: Opc = BinaryOperator::Mul; break;
3464 case tok::slash: Opc = BinaryOperator::Div; break;
3465 case tok::percent: Opc = BinaryOperator::Rem; break;
3466 case tok::plus: Opc = BinaryOperator::Add; break;
3467 case tok::minus: Opc = BinaryOperator::Sub; break;
3468 case tok::lessless: Opc = BinaryOperator::Shl; break;
3469 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3470 case tok::lessequal: Opc = BinaryOperator::LE; break;
3471 case tok::less: Opc = BinaryOperator::LT; break;
3472 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3473 case tok::greater: Opc = BinaryOperator::GT; break;
3474 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3475 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3476 case tok::amp: Opc = BinaryOperator::And; break;
3477 case tok::caret: Opc = BinaryOperator::Xor; break;
3478 case tok::pipe: Opc = BinaryOperator::Or; break;
3479 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3480 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3481 case tok::equal: Opc = BinaryOperator::Assign; break;
3482 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3483 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3484 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3485 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3486 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3487 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3488 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3489 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3490 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3491 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3492 case tok::comma: Opc = BinaryOperator::Comma; break;
3493 }
3494 return Opc;
3495}
3496
3497static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3498 tok::TokenKind Kind) {
3499 UnaryOperator::Opcode Opc;
3500 switch (Kind) {
3501 default: assert(0 && "Unknown unary op!");
3502 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3503 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3504 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3505 case tok::star: Opc = UnaryOperator::Deref; break;
3506 case tok::plus: Opc = UnaryOperator::Plus; break;
3507 case tok::minus: Opc = UnaryOperator::Minus; break;
3508 case tok::tilde: Opc = UnaryOperator::Not; break;
3509 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003510 case tok::kw___real: Opc = UnaryOperator::Real; break;
3511 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3512 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3513 }
3514 return Opc;
3515}
3516
Douglas Gregord7f915e2008-11-06 23:29:22 +00003517/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3518/// operator @p Opc at location @c TokLoc. This routine only supports
3519/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003520Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3521 unsigned Op,
3522 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003523 QualType ResultTy; // Result type of the binary operator.
3524 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3525 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3526
3527 switch (Opc) {
3528 default:
3529 assert(0 && "Unknown binary expr!");
3530 case BinaryOperator::Assign:
3531 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3532 break;
3533 case BinaryOperator::Mul:
3534 case BinaryOperator::Div:
3535 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3536 break;
3537 case BinaryOperator::Rem:
3538 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3539 break;
3540 case BinaryOperator::Add:
3541 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3542 break;
3543 case BinaryOperator::Sub:
3544 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3545 break;
3546 case BinaryOperator::Shl:
3547 case BinaryOperator::Shr:
3548 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3549 break;
3550 case BinaryOperator::LE:
3551 case BinaryOperator::LT:
3552 case BinaryOperator::GE:
3553 case BinaryOperator::GT:
3554 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3555 break;
3556 case BinaryOperator::EQ:
3557 case BinaryOperator::NE:
3558 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3559 break;
3560 case BinaryOperator::And:
3561 case BinaryOperator::Xor:
3562 case BinaryOperator::Or:
3563 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3564 break;
3565 case BinaryOperator::LAnd:
3566 case BinaryOperator::LOr:
3567 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3568 break;
3569 case BinaryOperator::MulAssign:
3570 case BinaryOperator::DivAssign:
3571 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3572 if (!CompTy.isNull())
3573 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3574 break;
3575 case BinaryOperator::RemAssign:
3576 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3577 if (!CompTy.isNull())
3578 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3579 break;
3580 case BinaryOperator::AddAssign:
3581 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3582 if (!CompTy.isNull())
3583 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3584 break;
3585 case BinaryOperator::SubAssign:
3586 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3587 if (!CompTy.isNull())
3588 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3589 break;
3590 case BinaryOperator::ShlAssign:
3591 case BinaryOperator::ShrAssign:
3592 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3593 if (!CompTy.isNull())
3594 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3595 break;
3596 case BinaryOperator::AndAssign:
3597 case BinaryOperator::XorAssign:
3598 case BinaryOperator::OrAssign:
3599 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3600 if (!CompTy.isNull())
3601 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3602 break;
3603 case BinaryOperator::Comma:
3604 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3605 break;
3606 }
3607 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003608 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00003609 if (CompTy.isNull())
3610 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3611 else
3612 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Steve Naroff8b9a98d2009-01-20 21:06:31 +00003613 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003614}
3615
Chris Lattner4b009652007-07-25 00:24:17 +00003616// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003617Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3618 tok::TokenKind Kind,
3619 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003620 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003621 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003622
Steve Naroff87d58b42007-09-16 03:34:24 +00003623 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3624 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003625
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003626 // If either expression is type-dependent, just build the AST.
3627 // FIXME: We'll need to perform some caching of the result of name
3628 // lookup for operator+.
3629 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff774e4152009-01-21 00:14:39 +00003630 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3631 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003632 Context.DependentTy,
3633 Context.DependentTy, TokLoc));
Steve Naroff774e4152009-01-21 00:14:39 +00003634 else
3635 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, Context.DependentTy,
3636 TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003637 }
3638
Douglas Gregord7f915e2008-11-06 23:29:22 +00003639 if (getLangOptions().CPlusPlus &&
3640 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3641 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003642 // If this is one of the assignment operators, we only perform
3643 // overload resolution if the left-hand side is a class or
3644 // enumeration type (C++ [expr.ass]p3).
3645 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3646 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3647 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3648 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003649
Douglas Gregord7f915e2008-11-06 23:29:22 +00003650 // Determine which overloaded operator we're dealing with.
3651 static const OverloadedOperatorKind OverOps[] = {
3652 OO_Star, OO_Slash, OO_Percent,
3653 OO_Plus, OO_Minus,
3654 OO_LessLess, OO_GreaterGreater,
3655 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3656 OO_EqualEqual, OO_ExclaimEqual,
3657 OO_Amp,
3658 OO_Caret,
3659 OO_Pipe,
3660 OO_AmpAmp,
3661 OO_PipePipe,
3662 OO_Equal, OO_StarEqual,
3663 OO_SlashEqual, OO_PercentEqual,
3664 OO_PlusEqual, OO_MinusEqual,
3665 OO_LessLessEqual, OO_GreaterGreaterEqual,
3666 OO_AmpEqual, OO_CaretEqual,
3667 OO_PipeEqual,
3668 OO_Comma
3669 };
3670 OverloadedOperatorKind OverOp = OverOps[Opc];
3671
Douglas Gregor5ed15042008-11-18 23:14:02 +00003672 // Add the appropriate overloaded operators (C++ [over.match.oper])
3673 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003674 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003675 Expr *Args[2] = { lhs, rhs };
Douglas Gregor5ed15042008-11-18 23:14:02 +00003676 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregord7f915e2008-11-06 23:29:22 +00003677
3678 // Perform overload resolution.
3679 OverloadCandidateSet::iterator Best;
3680 switch (BestViableFunction(CandidateSet, Best)) {
3681 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003682 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003683 FunctionDecl *FnDecl = Best->Function;
3684
Douglas Gregor70d26122008-11-12 17:17:38 +00003685 if (FnDecl) {
3686 // We matched an overloaded operator. Build a call to that
3687 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003688
Douglas Gregor70d26122008-11-12 17:17:38 +00003689 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003690 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3691 if (PerformObjectArgumentInitialization(lhs, Method) ||
3692 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3693 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003694 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003695 } else {
3696 // Convert the arguments.
3697 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3698 "passing") ||
3699 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3700 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003701 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003702 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003703
Douglas Gregor70d26122008-11-12 17:17:38 +00003704 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003705 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003706 = FnDecl->getType()->getAsFunctionType()->getResultType();
3707 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003708
Douglas Gregor70d26122008-11-12 17:17:38 +00003709 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003710 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3711 SourceLocation());
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003712 UsualUnaryConversions(FnExpr);
3713
Steve Naroff774e4152009-01-21 00:14:39 +00003714 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, Args, 2,
3715 ResultTy, TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003716 } else {
3717 // We matched a built-in operator. Convert the arguments, then
3718 // break out so that we will build the appropriate built-in
3719 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003720 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3721 Best->Conversions[0], "passing") ||
3722 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3723 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003724 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003725
3726 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003727 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003728 }
3729
3730 case OR_No_Viable_Function:
3731 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003732 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003733 break;
3734
3735 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003736 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3737 << BinaryOperator::getOpcodeStr(Opc)
3738 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003739 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003740 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003741 }
3742
Douglas Gregor70d26122008-11-12 17:17:38 +00003743 // Either we found no viable overloaded operator or we matched a
3744 // built-in operator. In either case, fall through to trying to
3745 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003746 }
3747
Douglas Gregord7f915e2008-11-06 23:29:22 +00003748 // Build a built-in binary operation.
3749 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003750}
3751
3752// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00003753Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3754 tok::TokenKind Op, ExprArg input) {
3755 // FIXME: Input is modified later, but smart pointer not reassigned.
3756 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00003757 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003758
3759 if (getLangOptions().CPlusPlus &&
3760 (Input->getType()->isRecordType()
3761 || Input->getType()->isEnumeralType())) {
3762 // Determine which overloaded operator we're dealing with.
3763 static const OverloadedOperatorKind OverOps[] = {
3764 OO_None, OO_None,
3765 OO_PlusPlus, OO_MinusMinus,
3766 OO_Amp, OO_Star,
3767 OO_Plus, OO_Minus,
3768 OO_Tilde, OO_Exclaim,
3769 OO_None, OO_None,
3770 OO_None,
3771 OO_None
3772 };
3773 OverloadedOperatorKind OverOp = OverOps[Opc];
3774
3775 // Add the appropriate overloaded operators (C++ [over.match.oper])
3776 // to the candidate set.
3777 OverloadCandidateSet CandidateSet;
3778 if (OverOp != OO_None)
3779 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3780
3781 // Perform overload resolution.
3782 OverloadCandidateSet::iterator Best;
3783 switch (BestViableFunction(CandidateSet, Best)) {
3784 case OR_Success: {
3785 // We found a built-in operator or an overloaded operator.
3786 FunctionDecl *FnDecl = Best->Function;
3787
3788 if (FnDecl) {
3789 // We matched an overloaded operator. Build a call to that
3790 // operator.
3791
3792 // Convert the arguments.
3793 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3794 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00003795 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003796 } else {
3797 // Convert the arguments.
3798 if (PerformCopyInitialization(Input,
3799 FnDecl->getParamDecl(0)->getType(),
3800 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003801 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003802 }
3803
3804 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00003805 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003806 = FnDecl->getType()->getAsFunctionType()->getResultType();
3807 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00003808
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003809 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003810 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3811 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003812 UsualUnaryConversions(FnExpr);
3813
Sebastian Redl8b769972009-01-19 00:08:26 +00003814 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00003815 return Owned(new (Context) CXXOperatorCallExpr(FnExpr, &Input, 1,
3816 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003817 } else {
3818 // We matched a built-in operator. Convert the arguments, then
3819 // break out so that we will build the appropriate built-in
3820 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003821 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3822 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003823 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003824
3825 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00003826 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003827 }
3828
3829 case OR_No_Viable_Function:
3830 // No viable function; fall through to handling this as a
3831 // built-in operator, which will produce an error message for us.
3832 break;
3833
3834 case OR_Ambiguous:
3835 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3836 << UnaryOperator::getOpcodeStr(Opc)
3837 << Input->getSourceRange();
3838 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00003839 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003840 }
3841
3842 // Either we found no viable overloaded operator or we matched a
3843 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00003844 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003845 }
3846
Chris Lattner4b009652007-07-25 00:24:17 +00003847 QualType resultType;
3848 switch (Opc) {
3849 default:
3850 assert(0 && "Unimplemented unary expr!");
3851 case UnaryOperator::PreInc:
3852 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003853 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3854 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00003855 break;
3856 case UnaryOperator::AddrOf:
3857 resultType = CheckAddressOfOperand(Input, OpLoc);
3858 break;
3859 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00003860 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00003861 resultType = CheckIndirectionOperand(Input, OpLoc);
3862 break;
3863 case UnaryOperator::Plus:
3864 case UnaryOperator::Minus:
3865 UsualUnaryConversions(Input);
3866 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003867 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3868 break;
3869 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3870 resultType->isEnumeralType())
3871 break;
3872 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3873 Opc == UnaryOperator::Plus &&
3874 resultType->isPointerType())
3875 break;
3876
Sebastian Redl8b769972009-01-19 00:08:26 +00003877 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3878 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003879 case UnaryOperator::Not: // bitwise complement
3880 UsualUnaryConversions(Input);
3881 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00003882 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3883 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3884 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00003885 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003886 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00003887 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00003888 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3889 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003890 break;
3891 case UnaryOperator::LNot: // logical negation
3892 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
3893 DefaultFunctionArrayConversion(Input);
3894 resultType = Input->getType();
3895 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00003896 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3897 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003898 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00003899 // In C++, it's bool. C++ 5.3.1p8
3900 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003901 break;
Chris Lattner03931a72007-08-24 21:16:53 +00003902 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00003903 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00003904 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00003905 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003906 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00003907 resultType = Input->getType();
3908 break;
3909 }
3910 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00003911 return ExprError();
3912 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00003913 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00003914}
3915
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003916/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3917Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00003918 SourceLocation LabLoc,
3919 IdentifierInfo *LabelII) {
3920 // Look up the record for this label identifier.
3921 LabelStmt *&LabelDecl = LabelMap[LabelII];
3922
Daniel Dunbar879788d2008-08-04 16:51:22 +00003923 // If we haven't seen this label yet, create a forward reference. It
3924 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00003925 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00003926 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00003927
3928 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff774e4152009-01-21 00:14:39 +00003929 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3930 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00003931}
3932
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003933Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00003934 SourceLocation RPLoc) { // "({..})"
3935 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3936 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3937 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3938
3939 // FIXME: there are a variety of strange constraints to enforce here, for
3940 // example, it is not possible to goto into a stmt expression apparently.
3941 // More semantic analysis is needed.
3942
3943 // FIXME: the last statement in the compount stmt has its value used. We
3944 // should not warn about it being unused.
3945
3946 // If there are sub stmts in the compound stmt, take the type of the last one
3947 // as the type of the stmtexpr.
3948 QualType Ty = Context.VoidTy;
3949
Chris Lattner200964f2008-07-26 19:51:01 +00003950 if (!Compound->body_empty()) {
3951 Stmt *LastStmt = Compound->body_back();
3952 // If LastStmt is a label, skip down through into the body.
3953 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3954 LastStmt = Label->getSubStmt();
3955
3956 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00003957 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00003958 }
Chris Lattner4b009652007-07-25 00:24:17 +00003959
Steve Naroff774e4152009-01-21 00:14:39 +00003960 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00003961}
Steve Naroff63bad2d2007-08-01 22:05:33 +00003962
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003963Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
3964 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003965 SourceLocation TypeLoc,
3966 TypeTy *argty,
3967 OffsetOfComponent *CompPtr,
3968 unsigned NumComponents,
3969 SourceLocation RPLoc) {
3970 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3971 assert(!ArgTy.isNull() && "Missing type argument!");
3972
3973 // We must have at least one component that refers to the type, and the first
3974 // one is known to be a field designator. Verify that the ArgTy represents
3975 // a struct/union/class.
3976 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00003977 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003978
3979 // Otherwise, create a compound literal expression as the base, and
3980 // iteratively process the offsetof designators.
Steve Naroff774e4152009-01-21 00:14:39 +00003981 Expr *Res = new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, 0,
3982 false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003983
Chris Lattnerb37522e2007-08-31 21:49:13 +00003984 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3985 // GCC extension, diagnose them.
3986 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003987 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3988 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00003989
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003990 for (unsigned i = 0; i != NumComponents; ++i) {
3991 const OffsetOfComponent &OC = CompPtr[i];
3992 if (OC.isBrackets) {
3993 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00003994 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003995 if (!AT) {
3996 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003997 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003998 }
3999
Chris Lattner2af6a802007-08-30 17:59:59 +00004000 // FIXME: C++: Verify that operator[] isn't overloaded.
4001
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004002 // C99 6.5.2.1p1
4003 Expr *Idx = static_cast<Expr*>(OC.U.E);
4004 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00004005 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4006 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004007
Steve Naroff774e4152009-01-21 00:14:39 +00004008 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4009 OC.LocEnd);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004010 continue;
4011 }
4012
4013 const RecordType *RC = Res->getType()->getAsRecordType();
4014 if (!RC) {
4015 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00004016 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004017 }
4018
4019 // Get the decl corresponding to this.
4020 RecordDecl *RD = RC->getDecl();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004021 FieldDecl *MemberDecl
4022 = dyn_cast_or_null<FieldDecl>(LookupDecl(OC.U.IdentInfo,
4023 Decl::IDNS_Ordinary,
Douglas Gregor78d70132009-01-14 22:20:51 +00004024 S, RD, false, false).getAsDecl());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004025 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00004026 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4027 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00004028
4029 // FIXME: C++: Verify that MemberDecl isn't a static field.
4030 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00004031 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4032 // matter here.
Steve Naroff774e4152009-01-21 00:14:39 +00004033 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4034 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004035 }
4036
Steve Naroff774e4152009-01-21 00:14:39 +00004037 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4038 Context.getSizeType(), BuiltinLoc);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004039}
4040
4041
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004042Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00004043 TypeTy *arg1, TypeTy *arg2,
4044 SourceLocation RPLoc) {
4045 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4046 QualType argT2 = QualType::getFromOpaquePtr(arg2);
4047
4048 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4049
Steve Naroff774e4152009-01-21 00:14:39 +00004050 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
4051 argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00004052}
4053
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004054Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00004055 ExprTy *expr1, ExprTy *expr2,
4056 SourceLocation RPLoc) {
4057 Expr *CondExpr = static_cast<Expr*>(cond);
4058 Expr *LHSExpr = static_cast<Expr*>(expr1);
4059 Expr *RHSExpr = static_cast<Expr*>(expr2);
4060
4061 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4062
4063 // The conditional expression is required to be a constant expression.
4064 llvm::APSInt condEval(32);
4065 SourceLocation ExpLoc;
4066 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004067 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4068 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00004069
4070 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4071 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
4072 RHSExpr->getType();
Steve Naroff774e4152009-01-21 00:14:39 +00004073 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4074 resType, RPLoc);
Steve Naroff93c53012007-08-03 21:21:27 +00004075}
4076
Steve Naroff52a81c02008-09-03 18:15:37 +00004077//===----------------------------------------------------------------------===//
4078// Clang Extensions.
4079//===----------------------------------------------------------------------===//
4080
4081/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004082void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004083 // Analyze block parameters.
4084 BlockSemaInfo *BSI = new BlockSemaInfo();
4085
4086 // Add BSI to CurBlock.
4087 BSI->PrevBlockInfo = CurBlock;
4088 CurBlock = BSI;
4089
4090 BSI->ReturnType = 0;
4091 BSI->TheScope = BlockScope;
4092
Steve Naroff52059382008-10-10 01:28:17 +00004093 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004094 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004095}
4096
4097void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004098 // Analyze arguments to block.
4099 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4100 "Not a function declarator!");
4101 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
4102
Steve Naroff52059382008-10-10 01:28:17 +00004103 CurBlock->hasPrototype = FTI.hasPrototype;
4104 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00004105
4106 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4107 // no arguments, not a function that takes a single void argument.
4108 if (FTI.hasPrototype &&
4109 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4110 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4111 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4112 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004113 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004114 } else if (FTI.hasPrototype) {
4115 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004116 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4117 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00004118 }
Steve Naroff52059382008-10-10 01:28:17 +00004119 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4120
4121 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4122 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4123 // If this has an identifier, add it to the scope stack.
4124 if ((*AI)->getIdentifier())
4125 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004126}
4127
4128/// ActOnBlockError - If there is an error parsing a block, this callback
4129/// is invoked to pop the information about the block from the action impl.
4130void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4131 // Ensure that CurBlock is deleted.
4132 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4133
4134 // Pop off CurBlock, handle nested blocks.
4135 CurBlock = CurBlock->PrevBlockInfo;
4136
4137 // FIXME: Delete the ParmVarDecl objects as well???
4138
4139}
4140
4141/// ActOnBlockStmtExpr - This is called when the body of a block statement
4142/// literal was successfully completed. ^(int x){...}
4143Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4144 Scope *CurScope) {
4145 // Ensure that CurBlock is deleted.
4146 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
4147 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
4148
Steve Naroff52059382008-10-10 01:28:17 +00004149 PopDeclContext();
4150
Steve Naroff52a81c02008-09-03 18:15:37 +00004151 // Pop off CurBlock, handle nested blocks.
4152 CurBlock = CurBlock->PrevBlockInfo;
4153
4154 QualType RetTy = Context.VoidTy;
4155 if (BSI->ReturnType)
4156 RetTy = QualType(BSI->ReturnType, 0);
4157
4158 llvm::SmallVector<QualType, 8> ArgTypes;
4159 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4160 ArgTypes.push_back(BSI->Params[i]->getType());
4161
4162 QualType BlockTy;
4163 if (!BSI->hasPrototype)
4164 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4165 else
4166 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004167 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00004168
4169 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00004170
Steve Naroff95029d92008-10-08 18:44:00 +00004171 BSI->TheDecl->setBody(Body.take());
Steve Naroff774e4152009-01-21 00:14:39 +00004172 return new (Context) BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004173}
4174
Nate Begemanbd881ef2008-01-30 20:50:20 +00004175/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004176/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00004177/// The number of arguments has already been validated to match the number of
4178/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004179static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4180 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004181 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00004182 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004183 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4184 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00004185
4186 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004187 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00004188 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004189 return true;
4190}
4191
4192Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4193 SourceLocation *CommaLocs,
4194 SourceLocation BuiltinLoc,
4195 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004196 // __builtin_overload requires at least 2 arguments
4197 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004198 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4199 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004200
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004201 // The first argument is required to be a constant expression. It tells us
4202 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00004203 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004204 Expr *NParamsExpr = Args[0];
4205 llvm::APSInt constEval(32);
4206 SourceLocation ExpLoc;
4207 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004208 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4209 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004210
4211 // Verify that the number of parameters is > 0
4212 unsigned NumParams = constEval.getZExtValue();
4213 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004214 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4215 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004216 // Verify that we have at least 1 + NumParams arguments to the builtin.
4217 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004218 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4219 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004220
4221 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00004222 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00004223 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004224 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4225 // UsualUnaryConversions will convert the function DeclRefExpr into a
4226 // pointer to function.
4227 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004228 const FunctionTypeProto *FnType = 0;
4229 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4230 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004231
4232 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4233 // parameters, and the number of parameters must match the value passed to
4234 // the builtin.
4235 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004236 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4237 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004238
4239 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00004240 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004241 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004242 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004243 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004244 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4245 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00004246 // Remember our match, and continue processing the remaining arguments
4247 // to catch any errors.
Steve Naroff774e4152009-01-21 00:14:39 +00004248 OE = new (Context) OverloadExpr(Args, NumArgs, i,
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004249 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00004250 BuiltinLoc, RParenLoc);
4251 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004252 }
Nate Begemanc6078c92008-01-31 05:38:29 +00004253 // Return the newly created OverloadExpr node, if we succeded in matching
4254 // exactly one of the candidate functions.
4255 if (OE)
4256 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004257
4258 // If we didn't find a matching function Expr in the __builtin_overload list
4259 // the return an error.
4260 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00004261 for (unsigned i = 0; i != NumParams; ++i) {
4262 if (i != 0) typeNames += ", ";
4263 typeNames += Args[i+1]->getType().getAsString();
4264 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004265
Chris Lattner77d52da2008-11-20 06:06:08 +00004266 return Diag(BuiltinLoc, diag::err_overload_no_match)
4267 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004268}
4269
Anders Carlsson36760332007-10-15 20:28:48 +00004270Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4271 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004272 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004273 Expr *E = static_cast<Expr*>(expr);
4274 QualType T = QualType::getFromOpaquePtr(type);
4275
4276 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004277
4278 // Get the va_list type
4279 QualType VaListType = Context.getBuiltinVaListType();
4280 // Deal with implicit array decay; for example, on x86-64,
4281 // va_list is an array, but it's supposed to decay to
4282 // a pointer for va_arg.
4283 if (VaListType->isArrayType())
4284 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004285 // Make sure the input expression also decays appropriately.
4286 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004287
4288 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004289 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004290 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004291 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00004292
4293 // FIXME: Warn if a non-POD type is passed in.
4294
Steve Naroff774e4152009-01-21 00:14:39 +00004295 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004296}
4297
Douglas Gregorad4b3792008-11-29 04:51:27 +00004298Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4299 // The type of __null will be int or long, depending on the size of
4300 // pointers on the target.
4301 QualType Ty;
4302 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4303 Ty = Context.IntTy;
4304 else
4305 Ty = Context.LongTy;
4306
Steve Naroff774e4152009-01-21 00:14:39 +00004307 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregorad4b3792008-11-29 04:51:27 +00004308}
4309
Chris Lattner005ed752008-01-04 18:04:52 +00004310bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4311 SourceLocation Loc,
4312 QualType DstType, QualType SrcType,
4313 Expr *SrcExpr, const char *Flavor) {
4314 // Decode the result (notice that AST's are still created for extensions).
4315 bool isInvalid = false;
4316 unsigned DiagKind;
4317 switch (ConvTy) {
4318 default: assert(0 && "Unknown conversion type");
4319 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004320 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004321 DiagKind = diag::ext_typecheck_convert_pointer_int;
4322 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004323 case IntToPointer:
4324 DiagKind = diag::ext_typecheck_convert_int_pointer;
4325 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004326 case IncompatiblePointer:
4327 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4328 break;
4329 case FunctionVoidPointer:
4330 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4331 break;
4332 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004333 // If the qualifiers lost were because we were applying the
4334 // (deprecated) C++ conversion from a string literal to a char*
4335 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4336 // Ideally, this check would be performed in
4337 // CheckPointerTypesForAssignment. However, that would require a
4338 // bit of refactoring (so that the second argument is an
4339 // expression, rather than a type), which should be done as part
4340 // of a larger effort to fix CheckPointerTypesForAssignment for
4341 // C++ semantics.
4342 if (getLangOptions().CPlusPlus &&
4343 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4344 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004345 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4346 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004347 case IntToBlockPointer:
4348 DiagKind = diag::err_int_to_block_pointer;
4349 break;
4350 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004351 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004352 break;
Steve Naroff19608432008-10-14 22:18:38 +00004353 case IncompatibleObjCQualifiedId:
4354 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4355 // it can give a more specific diagnostic.
4356 DiagKind = diag::warn_incompatible_qualified_id;
4357 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004358 case Incompatible:
4359 DiagKind = diag::err_typecheck_convert_incompatible;
4360 isInvalid = true;
4361 break;
4362 }
4363
Chris Lattner271d4c22008-11-24 05:29:24 +00004364 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4365 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004366 return isInvalid;
4367}
Anders Carlssond5201b92008-11-30 19:50:32 +00004368
4369bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4370{
4371 Expr::EvalResult EvalResult;
4372
4373 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4374 EvalResult.HasSideEffects) {
4375 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4376
4377 if (EvalResult.Diag) {
4378 // We only show the note if it's not the usual "invalid subexpression"
4379 // or if it's actually in a subexpression.
4380 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4381 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4382 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4383 }
4384
4385 return true;
4386 }
4387
4388 if (EvalResult.Diag) {
4389 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4390 E->getSourceRange();
4391
4392 // Print the reason it's not a constant.
4393 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4394 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4395 }
4396
4397 if (Result)
4398 *Result = EvalResult.Val.getInt();
4399 return false;
4400}