blob: 5b6b00ceb1663e941724586ab4c0f8fd31583b58 [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!
Sebastian Redlcd883f72009-01-18 18:53:16 +0000322 return Owned(new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
323 Literal.AnyWide, StrTy,
324 StringToks[0].getLocation(),
325 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000326}
327
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000328/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
329/// CurBlock to VD should cause it to be snapshotted (as we do for auto
330/// variables defined outside the block) or false if this is not needed (e.g.
331/// for values inside the block or for globals).
332///
333/// FIXME: This will create BlockDeclRefExprs for global variables,
334/// function references, etc which is suboptimal :) and breaks
335/// things like "integer constant expression" tests.
336static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
337 ValueDecl *VD) {
338 // If the value is defined inside the block, we couldn't snapshot it even if
339 // we wanted to.
340 if (CurBlock->TheDecl == VD->getDeclContext())
341 return false;
342
343 // If this is an enum constant or function, it is constant, don't snapshot.
344 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
345 return false;
346
347 // If this is a reference to an extern, static, or global variable, no need to
348 // snapshot it.
349 // FIXME: What about 'const' variables in C++?
350 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
351 return Var->hasLocalStorage();
352
353 return true;
354}
355
356
357
Steve Naroff0acc9c92007-09-15 18:49:24 +0000358/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000359/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000360/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000361/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000362/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000363Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
364 IdentifierInfo &II,
365 bool HasTrailingLParen,
366 const CXXScopeSpec *SS) {
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000367 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS);
368}
369
Douglas Gregor566782a2009-01-06 05:10:23 +0000370/// BuildDeclRefExpr - Build either a DeclRefExpr or a
371/// QualifiedDeclRefExpr based on whether or not SS is a
372/// nested-name-specifier.
373DeclRefExpr *Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
374 bool TypeDependent, bool ValueDependent,
375 const CXXScopeSpec *SS) {
376 if (SS && !SS->isEmpty())
377 return new QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent,
378 SS->getRange().getBegin());
379 else
380 return new DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
381}
382
Douglas Gregor723d3332009-01-07 00:43:41 +0000383/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
384/// variable corresponding to the anonymous union or struct whose type
385/// is Record.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000386static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000387 assert(Record->isAnonymousStructOrUnion() &&
388 "Record must be an anonymous struct or union!");
389
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000390 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000391 // be an O(1) operation rather than a slow walk through DeclContext's
392 // vector (which itself will be eliminated). DeclGroups might make
393 // this even better.
394 DeclContext *Ctx = Record->getDeclContext();
395 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
396 DEnd = Ctx->decls_end();
397 D != DEnd; ++D) {
398 if (*D == Record) {
399 // The object for the anonymous struct/union directly
400 // follows its type in the list of declarations.
401 ++D;
402 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000403 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000404 return *D;
405 }
406 }
407
408 assert(false && "Missing object for anonymous record");
409 return 0;
410}
411
Sebastian Redlcd883f72009-01-18 18:53:16 +0000412Sema::OwningExprResult
Douglas Gregor723d3332009-01-07 00:43:41 +0000413Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
414 FieldDecl *Field,
415 Expr *BaseObjectExpr,
416 SourceLocation OpLoc) {
417 assert(Field->getDeclContext()->isRecord() &&
418 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
419 && "Field must be stored inside an anonymous struct or union");
420
421 // Construct the sequence of field member references
422 // we'll have to perform to get to the field in the anonymous
423 // union/struct. The list of members is built from the field
424 // outward, so traverse it backwards to go from an object in
425 // the current context to the field we found.
426 llvm::SmallVector<FieldDecl *, 4> AnonFields;
427 AnonFields.push_back(Field);
428 VarDecl *BaseObject = 0;
429 DeclContext *Ctx = Field->getDeclContext();
430 do {
431 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000432 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000433 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
434 AnonFields.push_back(AnonField);
435 else {
436 BaseObject = cast<VarDecl>(AnonObject);
437 break;
438 }
439 Ctx = Ctx->getParent();
440 } while (Ctx->isRecord() &&
441 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
442
443 // Build the expression that refers to the base object, from
444 // which we will build a sequence of member references to each
445 // of the anonymous union objects and, eventually, the field we
446 // found via name lookup.
447 bool BaseObjectIsPointer = false;
448 unsigned ExtraQuals = 0;
449 if (BaseObject) {
450 // BaseObject is an anonymous struct/union variable (and is,
451 // therefore, not part of another non-anonymous record).
452 delete BaseObjectExpr;
453
454 BaseObjectExpr = new DeclRefExpr(BaseObject, BaseObject->getType(),
455 SourceLocation());
456 ExtraQuals
457 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
458 } else if (BaseObjectExpr) {
459 // The caller provided the base object expression. Determine
460 // whether its a pointer and whether it adds any qualifiers to the
461 // anonymous struct/union fields we're looking into.
462 QualType ObjectType = BaseObjectExpr->getType();
463 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
464 BaseObjectIsPointer = true;
465 ObjectType = ObjectPtr->getPointeeType();
466 }
467 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
468 } else {
469 // We've found a member of an anonymous struct/union that is
470 // inside a non-anonymous struct/union, so in a well-formed
471 // program our base object expression is "this".
472 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
473 if (!MD->isStatic()) {
474 QualType AnonFieldType
475 = Context.getTagDeclType(
476 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
477 QualType ThisType = Context.getTagDeclType(MD->getParent());
478 if ((Context.getCanonicalType(AnonFieldType)
479 == Context.getCanonicalType(ThisType)) ||
480 IsDerivedFrom(ThisType, AnonFieldType)) {
481 // Our base object expression is "this".
482 BaseObjectExpr = new CXXThisExpr(SourceLocation(),
483 MD->getThisType(Context));
484 BaseObjectIsPointer = true;
485 }
486 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000487 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
488 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000489 }
490 ExtraQuals = MD->getTypeQualifiers();
491 }
492
493 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000494 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
495 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000496 }
497
498 // Build the implicit member references to the field of the
499 // anonymous struct/union.
500 Expr *Result = BaseObjectExpr;
501 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
502 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
503 FI != FIEnd; ++FI) {
504 QualType MemberType = (*FI)->getType();
505 if (!(*FI)->isMutable()) {
506 unsigned combinedQualifiers
507 = MemberType.getCVRQualifiers() | ExtraQuals;
508 MemberType = MemberType.getQualifiedType(combinedQualifiers);
509 }
510 Result = new MemberExpr(Result, BaseObjectIsPointer, *FI,
511 OpLoc, MemberType);
512 BaseObjectIsPointer = false;
513 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
514 OpLoc = SourceLocation();
515 }
516
Sebastian Redlcd883f72009-01-18 18:53:16 +0000517 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000518}
519
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000520/// ActOnDeclarationNameExpr - The parser has read some kind of name
521/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
522/// performs lookup on that name and returns an expression that refers
523/// to that name. This routine isn't directly called from the parser,
524/// because the parser doesn't know about DeclarationName. Rather,
525/// this routine is called by ActOnIdentifierExpr,
526/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
527/// which form the DeclarationName from the corresponding syntactic
528/// forms.
529///
530/// HasTrailingLParen indicates whether this identifier is used in a
531/// function call context. LookupCtx is only used for a C++
532/// qualified-id (foo::bar) to indicate the class or namespace that
533/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000534///
535/// If ForceResolution is true, then we will attempt to resolve the
536/// name even if it looks like a dependent name. This option is off by
537/// default.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000538Sema::OwningExprResult
539Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
540 DeclarationName Name, bool HasTrailingLParen,
541 const CXXScopeSpec *SS, bool ForceResolution) {
Douglas Gregora133e262008-12-06 00:22:45 +0000542 if (S->getTemplateParamParent() && Name.getAsIdentifierInfo() &&
543 HasTrailingLParen && !SS && !ForceResolution) {
544 // We've seen something of the form
545 // identifier(
546 // and we are in a template, so it is likely that 's' is a
547 // dependent name. However, we won't know until we've parsed all
548 // of the call arguments. So, build a CXXDependentNameExpr node
549 // to represent this name. Then, if it turns out that none of the
550 // arguments are type-dependent, we'll force the resolution of the
551 // dependent name at that point.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000552 return Owned(new CXXDependentNameExpr(Name.getAsIdentifierInfo(),
553 Context.DependentTy, Loc));
Douglas Gregora133e262008-12-06 00:22:45 +0000554 }
555
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000556 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000557 Decl *D = 0;
558 LookupResult Lookup;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000559 if (SS && !SS->isEmpty()) {
560 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
561 if (DC == 0)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000562 return ExprError();
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000563 Lookup = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000564 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000565 Lookup = LookupDecl(Name, Decl::IDNS_Ordinary, S);
566
Sebastian Redlcd883f72009-01-18 18:53:16 +0000567 if (Lookup.isAmbiguous()) {
568 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
569 SS && SS->isSet() ? SS->getRange()
570 : SourceRange());
571 return ExprError();
572 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000573 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000574
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000575 // If this reference is in an Objective-C method, then ivar lookup happens as
576 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000577 IdentifierInfo *II = Name.getAsIdentifierInfo();
578 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000579 // There are two cases to handle here. 1) scoped lookup could have failed,
580 // in which case we should look for an ivar. 2) scoped lookup could have
581 // found a decl, but that decl is outside the current method (i.e. a global
582 // variable). In these two cases, we do a lookup for an ivar with this
583 // name, if the lookup suceeds, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000584 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000585 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000586 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000587 // FIXME: This should use a new expr for a direct reference, don't turn
588 // this into Self->ivar, just return a BareIVarExpr or something.
589 IdentifierInfo &II = Context.Idents.get("self");
Sebastian Redlcd883f72009-01-18 18:53:16 +0000590 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
591 ObjCIvarRefExpr *MRef = new ObjCIvarRefExpr(IV, IV->getType(), Loc,
592 static_cast<Expr*>(SelfExpr.release()),
593 true, true);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000594 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000595 return Owned(MRef);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000596 }
597 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000598 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000599 if (D == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000600 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000601 getCurMethodDecl()->getClassInterface()));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000602 return Owned(new ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000603 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000604 }
Chris Lattner4b009652007-07-25 00:24:17 +0000605 if (D == 0) {
606 // Otherwise, this could be an implicitly declared function reference (legal
607 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000608 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000609 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000610 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000611 else {
612 // If this name wasn't predeclared and if this is not a function call,
613 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000614 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000615 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
616 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000617 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
618 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000619 return ExprError(Diag(Loc, diag::err_undeclared_use)
620 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000621 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000622 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000623 }
624 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000625
626 // We may have found a field within an anonymous union or struct
627 // (C++ [class.union]).
628 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
629 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
630 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000631
Douglas Gregor3257fb52008-12-22 05:46:06 +0000632 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
633 if (!MD->isStatic()) {
634 // C++ [class.mfct.nonstatic]p2:
635 // [...] if name lookup (3.4.1) resolves the name in the
636 // id-expression to a nonstatic nontype member of class X or of
637 // a base class of X, the id-expression is transformed into a
638 // class member access expression (5.2.5) using (*this) (9.3.2)
639 // as the postfix-expression to the left of the '.' operator.
640 DeclContext *Ctx = 0;
641 QualType MemberType;
642 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
643 Ctx = FD->getDeclContext();
644 MemberType = FD->getType();
645
646 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
647 MemberType = RefType->getPointeeType();
648 else if (!FD->isMutable()) {
649 unsigned combinedQualifiers
650 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
651 MemberType = MemberType.getQualifiedType(combinedQualifiers);
652 }
653 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
654 if (!Method->isStatic()) {
655 Ctx = Method->getParent();
656 MemberType = Method->getType();
657 }
658 } else if (OverloadedFunctionDecl *Ovl
659 = dyn_cast<OverloadedFunctionDecl>(D)) {
660 for (OverloadedFunctionDecl::function_iterator
661 Func = Ovl->function_begin(),
662 FuncEnd = Ovl->function_end();
663 Func != FuncEnd; ++Func) {
664 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
665 if (!DMethod->isStatic()) {
666 Ctx = Ovl->getDeclContext();
667 MemberType = Context.OverloadTy;
668 break;
669 }
670 }
671 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000672
673 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000674 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
675 QualType ThisType = Context.getTagDeclType(MD->getParent());
676 if ((Context.getCanonicalType(CtxType)
677 == Context.getCanonicalType(ThisType)) ||
678 IsDerivedFrom(ThisType, CtxType)) {
679 // Build the implicit member access expression.
680 Expr *This = new CXXThisExpr(SourceLocation(),
681 MD->getThisType(Context));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000682 return Owned(new MemberExpr(This, true, cast<NamedDecl>(D),
683 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000684 }
685 }
686 }
687 }
688
Douglas Gregor8acb7272008-12-11 16:49:14 +0000689 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000690 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
691 if (MD->isStatic())
692 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000693 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
694 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000695 }
696
Douglas Gregor3257fb52008-12-22 05:46:06 +0000697 // Any other ways we could have found the field in a well-formed
698 // program would have been turned into implicit member expressions
699 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000700 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
701 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000702 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000703
Chris Lattner4b009652007-07-25 00:24:17 +0000704 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000705 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000706 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000707 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000708 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000709 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000710
Steve Naroffd6163f32008-09-05 22:11:13 +0000711 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000712 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000713 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
714 false, false, SS));
Douglas Gregord2baafd2008-10-21 16:13:35 +0000715
Steve Naroffd6163f32008-09-05 22:11:13 +0000716 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000717
Steve Naroffd6163f32008-09-05 22:11:13 +0000718 // check if referencing an identifier with __attribute__((deprecated)).
719 if (VD->getAttr<DeprecatedAttr>())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000720 ExprError(Diag(Loc, diag::warn_deprecated) << VD->getDeclName());
721
Douglas Gregor48840c72008-12-10 23:01:14 +0000722 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
723 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
724 Scope *CheckS = S;
725 while (CheckS) {
726 if (CheckS->isWithinElse() &&
727 CheckS->getControlParent()->isDeclScope(Var)) {
728 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000729 ExprError(Diag(Loc, diag::warn_value_always_false)
730 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000731 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000732 ExprError(Diag(Loc, diag::warn_value_always_zero)
733 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000734 break;
735 }
736
737 // Move up one more control parent to check again.
738 CheckS = CheckS->getControlParent();
739 if (CheckS)
740 CheckS = CheckS->getParent();
741 }
742 }
743 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000744
745 // Only create DeclRefExpr's for valid Decl's.
746 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000747 return ExprError();
748
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000749 // If the identifier reference is inside a block, and it refers to a value
750 // that is outside the block, create a BlockDeclRefExpr instead of a
751 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
752 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000753 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000754 // We do not do this for things like enum constants, global variables, etc,
755 // as they do not get snapshotted.
756 //
757 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000758 // The BlocksAttr indicates the variable is bound by-reference.
759 if (VD->getAttr<BlocksAttr>())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000760 return Owned(new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
761 Loc, true));
762
Steve Naroff52059382008-10-10 01:28:17 +0000763 // Variable will be bound by-copy, make it const within the closure.
764 VD->getType().addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000765 return Owned(new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
766 Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000767 }
768 // If this reference is not in a block or if the referenced variable is
769 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000770
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000771 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000772 bool ValueDependent = false;
773 if (getLangOptions().CPlusPlus) {
774 // C++ [temp.dep.expr]p3:
775 // An id-expression is type-dependent if it contains:
776 // - an identifier that was declared with a dependent type,
777 if (VD->getType()->isDependentType())
778 TypeDependent = true;
779 // - FIXME: a template-id that is dependent,
780 // - a conversion-function-id that specifies a dependent type,
781 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
782 Name.getCXXNameType()->isDependentType())
783 TypeDependent = true;
784 // - a nested-name-specifier that contains a class-name that
785 // names a dependent type.
786 else if (SS && !SS->isEmpty()) {
787 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
788 DC; DC = DC->getParent()) {
789 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000790 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000791 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
792 if (Context.getTypeDeclType(Record)->isDependentType()) {
793 TypeDependent = true;
794 break;
795 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000796 }
797 }
798 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000799
Douglas Gregora5d84612008-12-10 20:57:37 +0000800 // C++ [temp.dep.constexpr]p2:
801 //
802 // An identifier is value-dependent if it is:
803 // - a name declared with a dependent type,
804 if (TypeDependent)
805 ValueDependent = true;
806 // - the name of a non-type template parameter,
807 else if (isa<NonTypeTemplateParmDecl>(VD))
808 ValueDependent = true;
809 // - a constant with integral or enumeration type and is
810 // initialized with an expression that is value-dependent
811 // (FIXME!).
812 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000813
Sebastian Redlcd883f72009-01-18 18:53:16 +0000814 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
815 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000816}
817
Sebastian Redlcd883f72009-01-18 18:53:16 +0000818Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
819 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000820 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000821
Chris Lattner4b009652007-07-25 00:24:17 +0000822 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000823 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000824 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
825 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
826 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000827 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000828
Chris Lattner7e637512008-01-12 08:14:25 +0000829 // Pre-defined identifiers are of type char[x], where x is the length of the
830 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000831 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000832 if (FunctionDecl *FD = getCurFunctionDecl())
833 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000834 else if (ObjCMethodDecl *MD = getCurMethodDecl())
835 Length = MD->getSynthesizedMethodSize();
836 else {
837 Diag(Loc, diag::ext_predef_outside_function);
838 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
839 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
840 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000841
842
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000843 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000844 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000845 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000846 return Owned(new PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +0000847}
848
Sebastian Redlcd883f72009-01-18 18:53:16 +0000849Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000850 llvm::SmallString<16> CharBuffer;
851 CharBuffer.resize(Tok.getLength());
852 const char *ThisTokBegin = &CharBuffer[0];
853 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000854
Chris Lattner4b009652007-07-25 00:24:17 +0000855 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
856 Tok.getLocation(), PP);
857 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000858 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +0000859
860 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
861
Sebastian Redlcd883f72009-01-18 18:53:16 +0000862 return Owned(new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
863 Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000864}
865
Sebastian Redlcd883f72009-01-18 18:53:16 +0000866Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
867 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +0000868 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
869 if (Tok.getLength() == 1) {
Chris Lattnerfd5f1432009-01-16 07:10:29 +0000870 const char Val = PP.getSpelledCharacterAt(Tok.getLocation());
871 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000872 return Owned(new IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
873 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000874 }
Ted Kremenekdbde2282009-01-13 23:19:12 +0000875
Chris Lattner4b009652007-07-25 00:24:17 +0000876 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000877 // Add padding so that NumericLiteralParser can overread by one character.
878 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000879 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +0000880
Chris Lattner4b009652007-07-25 00:24:17 +0000881 // Get the spelling of the token, which eliminates trigraphs, etc.
882 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000883
Chris Lattner4b009652007-07-25 00:24:17 +0000884 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
885 Tok.getLocation(), PP);
886 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000887 return ExprError();
888
Chris Lattner1de66eb2007-08-26 03:42:43 +0000889 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000890
Chris Lattner1de66eb2007-08-26 03:42:43 +0000891 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000892 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000893 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000894 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000895 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000896 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000897 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000898 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000899
900 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
901
Ted Kremenekddedbe22007-11-29 00:56:49 +0000902 // isExact will be set by GetFloatValue().
903 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000904 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000905 Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +0000906
Chris Lattner1de66eb2007-08-26 03:42:43 +0000907 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000908 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +0000909 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000910 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000911
Neil Booth7421e9c2007-08-29 22:00:19 +0000912 // long long is a C99 feature.
913 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000914 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000915 Diag(Tok.getLocation(), diag::ext_longlong);
916
Chris Lattner4b009652007-07-25 00:24:17 +0000917 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000918 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000919
Chris Lattner4b009652007-07-25 00:24:17 +0000920 if (Literal.GetIntegerValue(ResultVal)) {
921 // If this value didn't fit into uintmax_t, warn and force to ull.
922 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000923 Ty = Context.UnsignedLongLongTy;
924 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000925 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000926 } else {
927 // If this value fits into a ULL, try to figure out what else it fits into
928 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000929
Chris Lattner4b009652007-07-25 00:24:17 +0000930 // Octal, Hexadecimal, and integers with a U suffix are allowed to
931 // be an unsigned int.
932 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
933
934 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000935 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000936 if (!Literal.isLong && !Literal.isLongLong) {
937 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000938 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000939
Chris Lattner4b009652007-07-25 00:24:17 +0000940 // Does it fit in a unsigned int?
941 if (ResultVal.isIntN(IntSize)) {
942 // Does it fit in a signed int?
943 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000944 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000945 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000946 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000947 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000948 }
Chris Lattner4b009652007-07-25 00:24:17 +0000949 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000950
Chris Lattner4b009652007-07-25 00:24:17 +0000951 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000952 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000953 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000954
Chris Lattner4b009652007-07-25 00:24:17 +0000955 // Does it fit in a unsigned long?
956 if (ResultVal.isIntN(LongSize)) {
957 // Does it fit in a signed long?
958 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000959 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000960 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000961 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000962 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000963 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000964 }
965
Chris Lattner4b009652007-07-25 00:24:17 +0000966 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000967 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000968 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000969
Chris Lattner4b009652007-07-25 00:24:17 +0000970 // Does it fit in a unsigned long long?
971 if (ResultVal.isIntN(LongLongSize)) {
972 // Does it fit in a signed long long?
973 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000974 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000975 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000976 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000977 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000978 }
979 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000980
Chris Lattner4b009652007-07-25 00:24:17 +0000981 // If we still couldn't decide a type, we probably have something that
982 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000983 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000984 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000985 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000986 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000987 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000988
Chris Lattnere4068872008-05-09 05:59:00 +0000989 if (ResultVal.getBitWidth() != Width)
990 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000991 }
992
Chris Lattner48d7f382008-04-02 04:24:33 +0000993 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000994 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000995
Chris Lattner1de66eb2007-08-26 03:42:43 +0000996 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
997 if (Literal.isImaginary)
998 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000999
1000 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001001}
1002
Sebastian Redlcd883f72009-01-18 18:53:16 +00001003Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1004 SourceLocation R, ExprArg Val) {
1005 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001006 assert((E != 0) && "ActOnParenExpr() missing expr");
Sebastian Redlcd883f72009-01-18 18:53:16 +00001007 return Owned(new ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001008}
1009
1010/// The UsualUnaryConversions() function is *not* called by this routine.
1011/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001012bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1013 SourceLocation OpLoc,
1014 const SourceRange &ExprRange,
1015 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +00001016 // C99 6.5.3.4p1:
1017 if (isa<FunctionType>(exprType) && isSizeof)
1018 // alignof(function) is allowed.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001019 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
Chris Lattner4b009652007-07-25 00:24:17 +00001020 else if (exprType->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001021 Diag(OpLoc, diag::ext_sizeof_void_type)
1022 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001023 else
1024 return DiagnoseIncompleteType(OpLoc, exprType,
1025 isSizeof ? diag::err_sizeof_incomplete_type :
1026 diag::err_alignof_incomplete_type,
1027 ExprRange);
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001028
1029 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001030}
1031
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001032/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1033/// the same for @c alignof and @c __alignof
1034/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001035Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001036Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1037 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001038 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001039 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001040
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001041 QualType ArgTy;
1042 SourceRange Range;
1043 if (isType) {
1044 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1045 Range = ArgRange;
1046 } else {
1047 // Get the end location.
1048 Expr *ArgEx = (Expr *)TyOrEx;
1049 Range = ArgEx->getSourceRange();
1050 ArgTy = ArgEx->getType();
1051 }
1052
1053 // Verify that the operand is valid.
Sebastian Redl8b769972009-01-19 00:08:26 +00001054 // FIXME: This might leak the expression.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001055 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Sebastian Redl8b769972009-01-19 00:08:26 +00001056 return ExprError();
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001057
1058 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Sebastian Redl8b769972009-01-19 00:08:26 +00001059 return Owned(new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
1060 Context.getSizeType(), OpLoc,
1061 Range.getEnd()));
Chris Lattner4b009652007-07-25 00:24:17 +00001062}
1063
Chris Lattner5110ad52007-08-24 21:41:10 +00001064QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +00001065 DefaultFunctionArrayConversion(V);
1066
Chris Lattnera16e42d2007-08-26 05:39:26 +00001067 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001068 if (const ComplexType *CT = V->getType()->getAsComplexType())
1069 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001070
1071 // Otherwise they pass through real integer and floating point types here.
1072 if (V->getType()->isArithmeticType())
1073 return V->getType();
1074
1075 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +00001076 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001077 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001078}
1079
1080
Chris Lattner4b009652007-07-25 00:24:17 +00001081
Sebastian Redl8b769972009-01-19 00:08:26 +00001082Action::OwningExprResult
1083Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1084 tok::TokenKind Kind, ExprArg Input) {
1085 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001086
Chris Lattner4b009652007-07-25 00:24:17 +00001087 UnaryOperator::Opcode Opc;
1088 switch (Kind) {
1089 default: assert(0 && "Unknown unary op!");
1090 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1091 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1092 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001093
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001094 if (getLangOptions().CPlusPlus &&
1095 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1096 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001097 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001098 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1099
1100 // C++ [over.inc]p1:
1101 //
1102 // [...] If the function is a member function with one
1103 // parameter (which shall be of type int) or a non-member
1104 // function with two parameters (the second of which shall be
1105 // of type int), it defines the postfix increment operator ++
1106 // for objects of that type. When the postfix increment is
1107 // called as a result of using the ++ operator, the int
1108 // argument will have value zero.
1109 Expr *Args[2] = {
1110 Arg,
1111 new IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1112 /*isSigned=*/true),
1113 Context.IntTy, SourceLocation())
1114 };
1115
1116 // Build the candidate set for overloading
1117 OverloadCandidateSet CandidateSet;
1118 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
1119
1120 // Perform overload resolution.
1121 OverloadCandidateSet::iterator Best;
1122 switch (BestViableFunction(CandidateSet, Best)) {
1123 case OR_Success: {
1124 // We found a built-in operator or an overloaded operator.
1125 FunctionDecl *FnDecl = Best->Function;
1126
1127 if (FnDecl) {
1128 // We matched an overloaded operator. Build a call to that
1129 // operator.
1130
1131 // Convert the arguments.
1132 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1133 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001134 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001135 } else {
1136 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001137 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001138 FnDecl->getParamDecl(0)->getType(),
1139 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001140 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001141 }
1142
1143 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001144 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001145 = FnDecl->getType()->getAsFunctionType()->getResultType();
1146 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001147
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001148 // Build the actual expression node.
Sebastian Redl8b769972009-01-19 00:08:26 +00001149 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001150 SourceLocation());
1151 UsualUnaryConversions(FnExpr);
1152
Sebastian Redl8b769972009-01-19 00:08:26 +00001153 Input.release();
1154 return Owned(new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001155 } else {
1156 // We matched a built-in operator. Convert the arguments, then
1157 // break out so that we will build the appropriate built-in
1158 // operator node.
1159 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1160 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001161 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001162
1163 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001164 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001165 }
1166
1167 case OR_No_Viable_Function:
1168 // No viable function; fall through to handling this as a
1169 // built-in operator, which will produce an error message for us.
1170 break;
1171
1172 case OR_Ambiguous:
1173 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1174 << UnaryOperator::getOpcodeStr(Opc)
1175 << Arg->getSourceRange();
1176 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001177 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001178 }
1179
1180 // Either we found no viable overloaded operator or we matched a
1181 // built-in operator. In either case, fall through to trying to
1182 // build a built-in operation.
1183 }
1184
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001185 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1186 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001187 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001188 return ExprError();
1189 Input.release();
1190 return Owned(new UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001191}
1192
Sebastian Redl8b769972009-01-19 00:08:26 +00001193Action::OwningExprResult
1194Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1195 ExprArg Idx, SourceLocation RLoc) {
1196 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1197 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001198
Douglas Gregor80723c52008-11-19 17:17:41 +00001199 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001200 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001201 LHSExp->getType()->isEnumeralType() ||
1202 RHSExp->getType()->isRecordType() ||
1203 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001204 // Add the appropriate overloaded operators (C++ [over.match.oper])
1205 // to the candidate set.
1206 OverloadCandidateSet CandidateSet;
1207 Expr *Args[2] = { LHSExp, RHSExp };
1208 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
Sebastian Redl8b769972009-01-19 00:08:26 +00001209
Douglas Gregor80723c52008-11-19 17:17:41 +00001210 // Perform overload resolution.
1211 OverloadCandidateSet::iterator Best;
1212 switch (BestViableFunction(CandidateSet, Best)) {
1213 case OR_Success: {
1214 // We found a built-in operator or an overloaded operator.
1215 FunctionDecl *FnDecl = Best->Function;
1216
1217 if (FnDecl) {
1218 // We matched an overloaded operator. Build a call to that
1219 // operator.
1220
1221 // Convert the arguments.
1222 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1223 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1224 PerformCopyInitialization(RHSExp,
1225 FnDecl->getParamDecl(0)->getType(),
1226 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001227 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001228 } else {
1229 // Convert the arguments.
1230 if (PerformCopyInitialization(LHSExp,
1231 FnDecl->getParamDecl(0)->getType(),
1232 "passing") ||
1233 PerformCopyInitialization(RHSExp,
1234 FnDecl->getParamDecl(1)->getType(),
1235 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001236 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001237 }
1238
1239 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001240 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001241 = FnDecl->getType()->getAsFunctionType()->getResultType();
1242 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001243
Douglas Gregor80723c52008-11-19 17:17:41 +00001244 // Build the actual expression node.
1245 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
1246 SourceLocation());
1247 UsualUnaryConversions(FnExpr);
1248
Sebastian Redl8b769972009-01-19 00:08:26 +00001249 Base.release();
1250 Idx.release();
1251 return Owned(new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001252 } else {
1253 // We matched a built-in operator. Convert the arguments, then
1254 // break out so that we will build the appropriate built-in
1255 // operator node.
1256 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1257 "passing") ||
1258 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1259 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001260 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001261
1262 break;
1263 }
1264 }
1265
1266 case OR_No_Viable_Function:
1267 // No viable function; fall through to handling this as a
1268 // built-in operator, which will produce an error message for us.
1269 break;
1270
1271 case OR_Ambiguous:
1272 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1273 << "[]"
1274 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1275 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001276 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001277 }
1278
1279 // Either we found no viable overloaded operator or we matched a
1280 // built-in operator. In either case, fall through to trying to
1281 // build a built-in operation.
1282 }
1283
Chris Lattner4b009652007-07-25 00:24:17 +00001284 // Perform default conversions.
1285 DefaultFunctionArrayConversion(LHSExp);
1286 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001287
Chris Lattner4b009652007-07-25 00:24:17 +00001288 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1289
1290 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001291 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001292 // in the subscript position. As a result, we need to derive the array base
1293 // and index from the expression types.
1294 Expr *BaseExpr, *IndexExpr;
1295 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001296 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001297 BaseExpr = LHSExp;
1298 IndexExpr = RHSExp;
1299 // FIXME: need to deal with const...
1300 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001301 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001302 // Handle the uncommon case of "123[Ptr]".
1303 BaseExpr = RHSExp;
1304 IndexExpr = LHSExp;
1305 // FIXME: need to deal with const...
1306 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001307 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1308 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001309 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001310
Chris Lattner4b009652007-07-25 00:24:17 +00001311 // FIXME: need to deal with const...
1312 ResultType = VTy->getElementType();
1313 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001314 return ExprError(Diag(LHSExp->getLocStart(),
1315 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1316 }
Chris Lattner4b009652007-07-25 00:24:17 +00001317 // C99 6.5.2.1p1
1318 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001319 return ExprError(Diag(IndexExpr->getLocStart(),
1320 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001321
1322 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1323 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001324 // void (*)(int)) and pointers to incomplete types. Functions are not
1325 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001326 if (!ResultType->isObjectType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001327 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001328 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001329 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001330
Sebastian Redl8b769972009-01-19 00:08:26 +00001331 Base.release();
1332 Idx.release();
1333 return Owned(new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001334}
1335
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001336QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001337CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001338 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001339 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001340
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001341 // The vector accessor can't exceed the number of elements.
1342 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001343
1344 // This flag determines whether or not the component is one of the four
1345 // special names that indicate a subset of exactly half the elements are
1346 // to be selected.
1347 bool HalvingSwizzle = false;
1348
1349 // This flag determines whether or not CompName has an 's' char prefix,
1350 // indicating that it is a string of hex values to be used as vector indices.
1351 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001352
1353 // Check that we've found one of the special components, or that the component
1354 // names must come from the same set.
1355 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001356 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1357 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001358 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001359 do
1360 compStr++;
1361 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001362 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001363 do
1364 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001365 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001366 }
Nate Begeman1486b502009-01-18 01:47:54 +00001367
1368 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001369 // We didn't get to the end of the string. This means the component names
1370 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001371 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1372 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001373 return QualType();
1374 }
Nate Begeman1486b502009-01-18 01:47:54 +00001375
1376 // Ensure no component accessor exceeds the width of the vector type it
1377 // operates on.
1378 if (!HalvingSwizzle) {
1379 compStr = CompName.getName();
1380
1381 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001382 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001383
1384 while (*compStr) {
1385 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1386 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1387 << baseType << SourceRange(CompLoc);
1388 return QualType();
1389 }
1390 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001391 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001392
Nate Begeman1486b502009-01-18 01:47:54 +00001393 // If this is a halving swizzle, verify that the base type has an even
1394 // number of elements.
1395 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001396 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001397 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001398 return QualType();
1399 }
1400
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001401 // The component accessor looks fine - now we need to compute the actual type.
1402 // The vector type is implied by the component accessor. For example,
1403 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001404 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001405 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001406 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1407 : CompName.getLength();
1408 if (HexSwizzle)
1409 CompSize--;
1410
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001411 if (CompSize == 1)
1412 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001413
Nate Begemanaf6ed502008-04-18 23:10:10 +00001414 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001415 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001416 // diagostics look bad. We want extended vector types to appear built-in.
1417 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1418 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1419 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001420 }
1421 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001422}
1423
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001424/// constructSetterName - Return the setter name for the given
1425/// identifier, i.e. "set" + Name where the initial character of Name
1426/// has been capitalized.
1427// FIXME: Merge with same routine in Parser. But where should this
1428// live?
1429static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1430 const IdentifierInfo *Name) {
1431 llvm::SmallString<100> SelectorName;
1432 SelectorName = "set";
1433 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1434 SelectorName[3] = toupper(SelectorName[3]);
1435 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1436}
1437
Sebastian Redl8b769972009-01-19 00:08:26 +00001438Action::OwningExprResult
1439Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1440 tok::TokenKind OpKind, SourceLocation MemberLoc,
1441 IdentifierInfo &Member) {
1442 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001443 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001444
1445 // Perform default conversions.
1446 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001447
Steve Naroff2cb66382007-07-26 03:11:44 +00001448 QualType BaseType = BaseExpr->getType();
1449 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001450
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001451 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1452 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001453 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001454 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001455 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001456 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001457 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1458 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001459 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001460 return ExprError(Diag(MemberLoc,
1461 diag::err_typecheck_member_reference_arrow)
1462 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001463 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001464
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001465 // Handle field access to simple records. This also handles access to fields
1466 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001467 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001468 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001469 if (DiagnoseIncompleteType(OpLoc, BaseType,
1470 diag::err_typecheck_incomplete_tag,
1471 BaseExpr->getSourceRange()))
1472 return ExprError();
1473
Steve Naroff2cb66382007-07-26 03:11:44 +00001474 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001475 // FIXME: Qualified name lookup for C++ is a bit more complicated
1476 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001477 LookupResult Result
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001478 = LookupQualifiedName(RDecl, DeclarationName(&Member),
1479 LookupCriteria(LookupCriteria::Member,
1480 /*RedeclarationOnly=*/false,
1481 getLangOptions().CPlusPlus));
1482
1483 Decl *MemberDecl = 0;
1484 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001485 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1486 << &Member << BaseExpr->getSourceRange());
1487 else if (Result.isAmbiguous()) {
1488 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1489 MemberLoc, BaseExpr->getSourceRange());
1490 return ExprError();
1491 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001492 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001493
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001494 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001495 // We may have found a field within an anonymous union or struct
1496 // (C++ [class.union]).
1497 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001498 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001499 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001500
Douglas Gregor82d44772008-12-20 23:49:58 +00001501 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1502 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001503 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001504 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1505 MemberType = Ref->getPointeeType();
1506 else {
1507 unsigned combinedQualifiers =
1508 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001509 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001510 combinedQualifiers &= ~QualType::Const;
1511 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1512 }
Eli Friedman76b49832008-02-06 22:48:16 +00001513
Sebastian Redl8b769972009-01-19 00:08:26 +00001514 return Owned(new MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1515 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001516 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001517 return Owned(new MemberExpr(BaseExpr, OpKind == tok::arrow,
1518 Var, MemberLoc,
1519 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001520 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001521 return Owned(new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberFn,
1522 MemberLoc, MemberFn->getType()));
1523 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001524 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001525 return Owned(new MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
1526 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001527 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001528 return Owned(new MemberExpr(BaseExpr, OpKind == tok::arrow, Enum,
1529 MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001530 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001531 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1532 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001533
Douglas Gregor82d44772008-12-20 23:49:58 +00001534 // We found a declaration kind that we didn't expect. This is a
1535 // generic error message that tells the user that she can't refer
1536 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001537 return ExprError(Diag(MemberLoc,
1538 diag::err_typecheck_member_reference_unknown)
1539 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001540 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001541
Chris Lattnere9d71612008-07-21 04:59:05 +00001542 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1543 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001544 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001545 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001546 ObjCIvarRefExpr *MRef= new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc,
1547 BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001548 OpKind == tok::arrow);
1549 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001550 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001551 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001552 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1553 << IFTy->getDecl()->getDeclName() << &Member
1554 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001555 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001556
Chris Lattnere9d71612008-07-21 04:59:05 +00001557 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1558 // pointer to a (potentially qualified) interface type.
1559 const PointerType *PTy;
1560 const ObjCInterfaceType *IFTy;
1561 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1562 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1563 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001564
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001565 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001566 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
Sebastian Redl8b769972009-01-19 00:08:26 +00001567 return Owned(new ObjCPropertyRefExpr(PD, PD->getType(),
1568 MemberLoc, BaseExpr));
1569
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001570 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001571 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1572 E = IFTy->qual_end(); I != E; ++I)
1573 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Sebastian Redl8b769972009-01-19 00:08:26 +00001574 return Owned(new ObjCPropertyRefExpr(PD, PD->getType(),
1575 MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001576
1577 // If that failed, look for an "implicit" property by seeing if the nullary
1578 // selector is implemented.
1579
1580 // FIXME: The logic for looking up nullary and unary selectors should be
1581 // shared with the code in ActOnInstanceMessage.
1582
1583 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1584 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001585
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001586 // If this reference is in an @implementation, check for 'private' methods.
1587 if (!Getter)
1588 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1589 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1590 if (ObjCImplementationDecl *ImpDecl =
1591 ObjCImplementations[ClassDecl->getIdentifier()])
1592 Getter = ImpDecl->getInstanceMethod(Sel);
1593
Steve Naroff04151f32008-10-22 19:16:27 +00001594 // Look through local category implementations associated with the class.
1595 if (!Getter) {
1596 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1597 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1598 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1599 }
1600 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001601 if (Getter) {
1602 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001603 // will look for the matching setter, in case it is needed.
1604 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1605 &Member);
1606 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1607 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1608 if (!Setter) {
1609 // If this reference is in an @implementation, also check for 'private'
1610 // methods.
1611 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1612 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1613 if (ObjCImplementationDecl *ImpDecl =
1614 ObjCImplementations[ClassDecl->getIdentifier()])
1615 Setter = ImpDecl->getInstanceMethod(SetterSel);
1616 }
1617 // Look through local category implementations associated with the class.
1618 if (!Setter) {
1619 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1620 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1621 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1622 }
1623 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001624
1625 // FIXME: we must check that the setter has property type.
1626 return Owned(new ObjCKVCRefExpr(Getter, Getter->getResultType(), Setter,
1627 MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001628 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001629
1630 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1631 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001632 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001633 // Handle properties on qualified "id" protocols.
1634 const ObjCQualifiedIdType *QIdTy;
1635 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1636 // Check protocols on qualified interfaces.
1637 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001638 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroffd1d44402008-10-20 22:53:06 +00001639 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
Sebastian Redl8b769972009-01-19 00:08:26 +00001640 return Owned(new ObjCPropertyRefExpr(PD, PD->getType(),
1641 MemberLoc, BaseExpr));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001642 // Also must look for a getter name which uses property syntax.
1643 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1644 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001645 return Owned(new ObjCMessageExpr(BaseExpr, Sel, OMD->getResultType(),
1646 OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001647 }
1648 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001649
1650 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1651 << &Member << BaseType);
1652 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001653 // Handle 'field access' to vectors, such as 'V.xx'.
1654 if (BaseType->isExtVectorType() && OpKind == tok::period) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001655 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1656 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001657 return ExprError();
1658 return Owned(new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001659 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001660
1661 return ExprError(Diag(MemberLoc,
1662 diag::err_typecheck_member_reference_struct_union)
1663 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001664}
1665
Douglas Gregor3257fb52008-12-22 05:46:06 +00001666/// ConvertArgumentsForCall - Converts the arguments specified in
1667/// Args/NumArgs to the parameter types of the function FDecl with
1668/// function prototype Proto. Call is the call expression itself, and
1669/// Fn is the function expression. For a C++ member function, this
1670/// routine does not attempt to convert the object argument. Returns
1671/// true if the call is ill-formed.
1672bool
1673Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1674 FunctionDecl *FDecl,
1675 const FunctionTypeProto *Proto,
1676 Expr **Args, unsigned NumArgs,
1677 SourceLocation RParenLoc) {
1678 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1679 // assignment, to the types of the corresponding parameter, ...
1680 unsigned NumArgsInProto = Proto->getNumArgs();
1681 unsigned NumArgsToCheck = NumArgs;
1682
1683 // If too few arguments are available (and we don't have default
1684 // arguments for the remaining parameters), don't make the call.
1685 if (NumArgs < NumArgsInProto) {
1686 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1687 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1688 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1689 // Use default arguments for missing arguments
1690 NumArgsToCheck = NumArgsInProto;
1691 Call->setNumArgs(NumArgsInProto);
1692 }
1693
1694 // If too many are passed and not variadic, error on the extras and drop
1695 // them.
1696 if (NumArgs > NumArgsInProto) {
1697 if (!Proto->isVariadic()) {
1698 Diag(Args[NumArgsInProto]->getLocStart(),
1699 diag::err_typecheck_call_too_many_args)
1700 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1701 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1702 Args[NumArgs-1]->getLocEnd());
1703 // This deletes the extra arguments.
1704 Call->setNumArgs(NumArgsInProto);
1705 }
1706 NumArgsToCheck = NumArgsInProto;
1707 }
1708
1709 // Continue to check argument types (even if we have too few/many args).
1710 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1711 QualType ProtoArgType = Proto->getArgType(i);
1712
1713 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001714 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001715 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001716
1717 // Pass the argument.
1718 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1719 return true;
1720 } else
1721 // We already type-checked the argument, so we know it works.
Douglas Gregor3257fb52008-12-22 05:46:06 +00001722 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
1723 QualType ArgType = Arg->getType();
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001724
Douglas Gregor3257fb52008-12-22 05:46:06 +00001725 Call->setArg(i, Arg);
1726 }
1727
1728 // If this is a variadic call, handle args passed through "...".
1729 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001730 VariadicCallType CallType = VariadicFunction;
1731 if (Fn->getType()->isBlockPointerType())
1732 CallType = VariadicBlock; // Block
1733 else if (isa<MemberExpr>(Fn))
1734 CallType = VariadicMethod;
1735
Douglas Gregor3257fb52008-12-22 05:46:06 +00001736 // Promote the arguments (C99 6.5.2.2p7).
1737 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1738 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001739 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001740 Call->setArg(i, Arg);
1741 }
1742 }
1743
1744 return false;
1745}
1746
Steve Naroff87d58b42007-09-16 03:34:24 +00001747/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001748/// This provides the location of the left/right parens and a list of comma
1749/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00001750Action::OwningExprResult
1751Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1752 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001753 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001754 unsigned NumArgs = args.size();
1755 Expr *Fn = static_cast<Expr *>(fn.release());
1756 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00001757 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001758 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001759 OverloadedFunctionDecl *Ovl = NULL;
1760
Douglas Gregora133e262008-12-06 00:22:45 +00001761 // Determine whether this is a dependent call inside a C++ template,
1762 // in which case we won't do any semantic analysis now.
1763 bool Dependent = false;
1764 if (Fn->isTypeDependent()) {
1765 if (CXXDependentNameExpr *FnName = dyn_cast<CXXDependentNameExpr>(Fn)) {
1766 if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1767 Dependent = true;
1768 else {
1769 // Resolve the CXXDependentNameExpr to an actual identifier;
1770 // it wasn't really a dependent name after all.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001771 OwningExprResult Resolved
1772 = ActOnDeclarationNameExpr(S, FnName->getLocation(),
1773 FnName->getName(),
Douglas Gregora133e262008-12-06 00:22:45 +00001774 /*HasTrailingLParen=*/true,
1775 /*SS=*/0,
1776 /*ForceResolution=*/true);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001777 if (Resolved.isInvalid())
Sebastian Redl8b769972009-01-19 00:08:26 +00001778 return ExprError();
Douglas Gregora133e262008-12-06 00:22:45 +00001779 else {
1780 delete Fn;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001781 Fn = (Expr *)Resolved.release();
Douglas Gregora133e262008-12-06 00:22:45 +00001782 }
1783 }
1784 } else
1785 Dependent = true;
1786 } else
1787 Dependent = Expr::hasAnyTypeDependentArguments(Args, NumArgs);
1788
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001789 // FIXME: Will need to cache the results of name lookup (including
1790 // ADL) in Fn.
Douglas Gregora133e262008-12-06 00:22:45 +00001791 if (Dependent)
Sebastian Redl8b769972009-01-19 00:08:26 +00001792 return Owned(new CallExpr(Fn, Args, NumArgs,
1793 Context.DependentTy, RParenLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001794
Douglas Gregor3257fb52008-12-22 05:46:06 +00001795 // Determine whether this is a call to an object (C++ [over.call.object]).
1796 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001797 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1798 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001799
1800 // Determine whether this is a call to a member function.
1801 if (getLangOptions().CPlusPlus) {
1802 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1803 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1804 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00001805 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1806 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001807 }
1808
Douglas Gregord2baafd2008-10-21 16:13:35 +00001809 // If we're directly calling a function or a set of overloaded
1810 // functions, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00001811 DeclRefExpr *DRExpr = NULL;
1812 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1813 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1814 else
1815 DRExpr = dyn_cast<DeclRefExpr>(Fn);
Sebastian Redl8b769972009-01-19 00:08:26 +00001816
Douglas Gregor566782a2009-01-06 05:10:23 +00001817 if (DRExpr) {
1818 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1819 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
Douglas Gregord2baafd2008-10-21 16:13:35 +00001820 }
1821
Douglas Gregord2baafd2008-10-21 16:13:35 +00001822 if (Ovl) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001823 FDecl = ResolveOverloadedCallFn(Fn, Ovl, LParenLoc, Args, NumArgs,
1824 CommaLocs, RParenLoc);
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001825 if (!FDecl)
Sebastian Redl8b769972009-01-19 00:08:26 +00001826 return ExprError();
Douglas Gregord2baafd2008-10-21 16:13:35 +00001827
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001828 // Update Fn to refer to the actual function selected.
Douglas Gregor566782a2009-01-06 05:10:23 +00001829 Expr *NewFn = 0;
1830 if (QualifiedDeclRefExpr *QDRExpr = dyn_cast<QualifiedDeclRefExpr>(DRExpr))
1831 NewFn = new QualifiedDeclRefExpr(FDecl, FDecl->getType(),
1832 QDRExpr->getLocation(), false, false,
1833 QDRExpr->getSourceRange().getBegin());
1834 else
1835 NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1836 Fn->getSourceRange().getBegin());
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001837 Fn->Destroy(Context);
1838 Fn = NewFn;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001839 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001840
1841 // Promote the function operand.
1842 UsualUnaryConversions(Fn);
1843
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001844 // Make the call expr early, before semantic checks. This guarantees cleanup
1845 // of arguments and function on error.
Sebastian Redl8b769972009-01-19 00:08:26 +00001846 // FIXME: Except that llvm::OwningPtr uses delete, when it really must be
1847 // Destroy(), or nothing gets cleaned up.
Chris Lattner97316c02008-04-10 02:22:51 +00001848 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001849 Context.BoolTy, RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001850
Steve Naroffd6163f32008-09-05 22:11:13 +00001851 const FunctionType *FuncT;
1852 if (!Fn->getType()->isBlockPointerType()) {
1853 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1854 // have type pointer to function".
1855 const PointerType *PT = Fn->getType()->getAsPointerType();
1856 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00001857 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1858 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00001859 FuncT = PT->getPointeeType()->getAsFunctionType();
1860 } else { // This is a block call.
1861 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1862 getAsFunctionType();
1863 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001864 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00001865 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1866 << Fn->getType() << Fn->getSourceRange());
1867
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001868 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001869 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00001870
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001871 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001872 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
1873 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00001874 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001875 } else {
1876 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00001877
Steve Naroffdb65e052007-08-28 23:30:39 +00001878 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001879 for (unsigned i = 0; i != NumArgs; i++) {
1880 Expr *Arg = Args[i];
1881 DefaultArgumentPromotion(Arg);
1882 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001883 }
Chris Lattner4b009652007-07-25 00:24:17 +00001884 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001885
Douglas Gregor3257fb52008-12-22 05:46:06 +00001886 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
1887 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00001888 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
1889 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00001890
Chris Lattner2e64c072007-08-10 20:18:51 +00001891 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001892 if (FDecl)
1893 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001894
Sebastian Redl8b769972009-01-19 00:08:26 +00001895 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00001896}
1897
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001898Action::OwningExprResult
1899Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
1900 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001901 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001902 QualType literalType = QualType::getFromOpaquePtr(Ty);
1903 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001904 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001905 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00001906
Eli Friedman8c2173d2008-05-20 05:22:08 +00001907 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001908 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001909 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
1910 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001911 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
1912 diag::err_typecheck_decl_incomplete_type,
1913 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001914 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00001915
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001916 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001917 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001918 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00001919
Chris Lattnere5cb5862008-12-04 23:50:19 +00001920 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001921 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001922 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001923 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00001924 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001925 InitExpr.release();
1926 return Owned(new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1927 isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00001928}
1929
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001930Action::OwningExprResult
1931Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
1932 InitListDesignations &Designators,
1933 SourceLocation RBraceLoc) {
1934 unsigned NumInit = initlist.size();
1935 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00001936
Steve Naroff0acc9c92007-09-15 18:49:24 +00001937 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001938 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001939
Chris Lattner71ca8c82008-10-26 23:43:26 +00001940 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1941 Designators.hasAnyDesignators());
Chris Lattner48d7f382008-04-02 04:24:33 +00001942 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00001943 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00001944}
1945
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001946/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001947bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001948 UsualUnaryConversions(castExpr);
1949
1950 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1951 // type needs to be scalar.
1952 if (castType->isVoidType()) {
1953 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001954 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
1955 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001956 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00001957 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
1958 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
1959 (castType->isStructureType() || castType->isUnionType())) {
1960 // GCC struct/union extension: allow cast to self.
1961 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
1962 << castType << castExpr->getSourceRange();
1963 } else if (castType->isUnionType()) {
1964 // GCC cast to union extension
1965 RecordDecl *RD = castType->getAsRecordType()->getDecl();
1966 RecordDecl::field_iterator Field, FieldEnd;
1967 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1968 Field != FieldEnd; ++Field) {
1969 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
1970 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
1971 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
1972 << castExpr->getSourceRange();
1973 break;
1974 }
1975 }
1976 if (Field == FieldEnd)
1977 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
1978 << castExpr->getType() << castExpr->getSourceRange();
1979 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001980 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001981 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001982 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001983 }
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001984 } else if (!castExpr->getType()->isScalarType() &&
1985 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001986 return Diag(castExpr->getLocStart(),
1987 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001988 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001989 } else if (castExpr->getType()->isVectorType()) {
1990 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1991 return true;
1992 } else if (castType->isVectorType()) {
1993 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1994 return true;
1995 }
1996 return false;
1997}
1998
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001999bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002000 assert(VectorTy->isVectorType() && "Not a vector type!");
2001
2002 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002003 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002004 return Diag(R.getBegin(),
2005 Ty->isVectorType() ?
2006 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002007 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002008 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002009 } else
2010 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002011 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002012 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002013
2014 return false;
2015}
2016
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002017Action::OwningExprResult
2018Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2019 SourceLocation RParenLoc, ExprArg Op) {
2020 assert((Ty != 0) && (Op.get() != 0) &&
2021 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002022
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002023 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002024 QualType castType = QualType::getFromOpaquePtr(Ty);
2025
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002026 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002027 return ExprError();
2028 return Owned(new CStyleCastExpr(castType, castExpr, castType,
2029 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002030}
2031
Chris Lattner98a425c2007-11-26 01:40:58 +00002032/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2033/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00002034inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
2035 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
2036 UsualUnaryConversions(cond);
2037 UsualUnaryConversions(lex);
2038 UsualUnaryConversions(rex);
2039 QualType condT = cond->getType();
2040 QualType lexT = lex->getType();
2041 QualType rexT = rex->getType();
2042
2043 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002044 if (!cond->isTypeDependent()) {
2045 if (!condT->isScalarType()) { // C99 6.5.15p2
2046 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
2047 return QualType();
2048 }
Chris Lattner4b009652007-07-25 00:24:17 +00002049 }
Chris Lattner992ae932008-01-06 22:42:25 +00002050
2051 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002052 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
2053 return Context.DependentTy;
2054
Chris Lattner992ae932008-01-06 22:42:25 +00002055 // If both operands have arithmetic type, do the usual arithmetic conversions
2056 // to find a common type: C99 6.5.15p3,5.
2057 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002058 UsualArithmeticConversions(lex, rex);
2059 return lex->getType();
2060 }
Chris Lattner992ae932008-01-06 22:42:25 +00002061
2062 // If both operands are the same structure or union type, the result is that
2063 // type.
Chris Lattner71225142007-07-31 21:27:01 +00002064 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00002065 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002066 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00002067 // "If both the operands have structure or union type, the result has
2068 // that type." This implies that CV qualifiers are dropped.
2069 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002070 }
Chris Lattner992ae932008-01-06 22:42:25 +00002071
2072 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002073 // The following || allows only one side to be void (a GCC-ism).
2074 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00002075 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002076 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2077 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00002078 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002079 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2080 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00002081 ImpCastExprToType(lex, Context.VoidTy);
2082 ImpCastExprToType(rex, Context.VoidTy);
2083 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002084 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002085 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2086 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002087 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2088 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002089 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002090 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002091 return lexT;
2092 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002093 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2094 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002095 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002096 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002097 return rexT;
2098 }
Chris Lattner0ac51632008-01-06 22:50:31 +00002099 // Handle the case where both operands are pointers before we handle null
2100 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00002101 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2102 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2103 // get the "pointed to" types
2104 QualType lhptee = LHSPT->getPointeeType();
2105 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002106
Chris Lattner71225142007-07-31 21:27:01 +00002107 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2108 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002109 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002110 // Figure out necessary qualifiers (C99 6.5.15p6)
2111 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002112 QualType destType = Context.getPointerType(destPointee);
2113 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2114 ImpCastExprToType(rex, destType); // promote to void*
2115 return destType;
2116 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002117 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002118 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002119 QualType destType = Context.getPointerType(destPointee);
2120 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2121 ImpCastExprToType(rex, destType); // promote to void*
2122 return destType;
2123 }
Chris Lattner4b009652007-07-25 00:24:17 +00002124
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002125 QualType compositeType = lexT;
2126
2127 // If either type is an Objective-C object type then check
2128 // compatibility according to Objective-C.
2129 if (Context.isObjCObjectPointerType(lexT) ||
2130 Context.isObjCObjectPointerType(rexT)) {
2131 // If both operands are interfaces and either operand can be
2132 // assigned to the other, use that type as the composite
2133 // type. This allows
2134 // xxx ? (A*) a : (B*) b
2135 // where B is a subclass of A.
2136 //
2137 // Additionally, as for assignment, if either type is 'id'
2138 // allow silent coercion. Finally, if the types are
2139 // incompatible then make sure to use 'id' as the composite
2140 // type so the result is acceptable for sending messages to.
2141
2142 // FIXME: This code should not be localized to here. Also this
2143 // should use a compatible check instead of abusing the
2144 // canAssignObjCInterfaces code.
2145 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2146 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2147 if (LHSIface && RHSIface &&
2148 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2149 compositeType = lexT;
2150 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002151 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002152 compositeType = rexT;
2153 } else if (Context.isObjCIdType(lhptee) ||
2154 Context.isObjCIdType(rhptee)) {
2155 // FIXME: This code looks wrong, because isObjCIdType checks
2156 // the struct but getObjCIdType returns the pointer to
2157 // struct. This is horrible and should be fixed.
2158 compositeType = Context.getObjCIdType();
2159 } else {
2160 QualType incompatTy = Context.getObjCIdType();
2161 ImpCastExprToType(lex, incompatTy);
2162 ImpCastExprToType(rex, incompatTy);
2163 return incompatTy;
2164 }
2165 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2166 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002167 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002168 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002169 // In this situation, we assume void* type. No especially good
2170 // reason, but this is what gcc does, and we do have to pick
2171 // to get a consistent AST.
2172 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002173 ImpCastExprToType(lex, incompatTy);
2174 ImpCastExprToType(rex, incompatTy);
2175 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002176 }
2177 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002178 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2179 // differently qualified versions of compatible types, the result type is
2180 // a pointer to an appropriately qualified version of the *composite*
2181 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002182 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002183 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00002184 ImpCastExprToType(lex, compositeType);
2185 ImpCastExprToType(rex, compositeType);
2186 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002187 }
Chris Lattner4b009652007-07-25 00:24:17 +00002188 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002189 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2190 // evaluates to "struct objc_object *" (and is handled above when comparing
2191 // id with statically typed objects).
2192 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2193 // GCC allows qualified id and any Objective-C type to devolve to
2194 // id. Currently localizing to here until clear this should be
2195 // part of ObjCQualifiedIdTypesAreCompatible.
2196 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2197 (lexT->isObjCQualifiedIdType() &&
2198 Context.isObjCObjectPointerType(rexT)) ||
2199 (rexT->isObjCQualifiedIdType() &&
2200 Context.isObjCObjectPointerType(lexT))) {
2201 // FIXME: This is not the correct composite type. This only
2202 // happens to work because id can more or less be used anywhere,
2203 // however this may change the type of method sends.
2204 // FIXME: gcc adds some type-checking of the arguments and emits
2205 // (confusing) incompatible comparison warnings in some
2206 // cases. Investigate.
2207 QualType compositeType = Context.getObjCIdType();
2208 ImpCastExprToType(lex, compositeType);
2209 ImpCastExprToType(rex, compositeType);
2210 return compositeType;
2211 }
2212 }
2213
Steve Naroff3eac7692008-09-10 19:17:48 +00002214 // Selection between block pointer types is ok as long as they are the same.
2215 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2216 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2217 return lexT;
2218
Chris Lattner992ae932008-01-06 22:42:25 +00002219 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00002220 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002221 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002222 return QualType();
2223}
2224
Steve Naroff87d58b42007-09-16 03:34:24 +00002225/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002226/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002227Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2228 SourceLocation ColonLoc,
2229 ExprArg Cond, ExprArg LHS,
2230 ExprArg RHS) {
2231 Expr *CondExpr = (Expr *) Cond.get();
2232 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002233
2234 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2235 // was the condition.
2236 bool isLHSNull = LHSExpr == 0;
2237 if (isLHSNull)
2238 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002239
2240 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002241 RHSExpr, QuestionLoc);
2242 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002243 return ExprError();
2244
2245 Cond.release();
2246 LHS.release();
2247 RHS.release();
2248 return Owned(new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
2249 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002250}
2251
Chris Lattner4b009652007-07-25 00:24:17 +00002252
2253// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2254// being closely modeled after the C99 spec:-). The odd characteristic of this
2255// routine is it effectively iqnores the qualifiers on the top level pointee.
2256// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2257// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00002258Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002259Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2260 QualType lhptee, rhptee;
2261
2262 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002263 lhptee = lhsType->getAsPointerType()->getPointeeType();
2264 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002265
2266 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002267 lhptee = Context.getCanonicalType(lhptee);
2268 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002269
Chris Lattner005ed752008-01-04 18:04:52 +00002270 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002271
2272 // C99 6.5.16.1p1: This following citation is common to constraints
2273 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2274 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00002275 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002276 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002277 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002278
2279 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2280 // incomplete type and the other is a pointer to a qualified or unqualified
2281 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002282 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002283 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002284 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002285
2286 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002287 assert(rhptee->isFunctionType());
2288 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002289 }
2290
2291 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002292 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002293 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002294
2295 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002296 assert(lhptee->isFunctionType());
2297 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002298 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002299
2300 // Check for ObjC interfaces
2301 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2302 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2303 if (LHSIface && RHSIface &&
2304 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2305 return ConvTy;
2306
2307 // ID acts sort of like void* for ObjC interfaces
2308 if (LHSIface && Context.isObjCIdType(rhptee))
2309 return ConvTy;
2310 if (RHSIface && Context.isObjCIdType(lhptee))
2311 return ConvTy;
2312
Chris Lattner4b009652007-07-25 00:24:17 +00002313 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2314 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002315 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2316 rhptee.getUnqualifiedType()))
2317 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002318 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002319}
2320
Steve Naroff3454b6c2008-09-04 15:10:53 +00002321/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2322/// block pointer types are compatible or whether a block and normal pointer
2323/// are compatible. It is more restrict than comparing two function pointer
2324// types.
2325Sema::AssignConvertType
2326Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2327 QualType rhsType) {
2328 QualType lhptee, rhptee;
2329
2330 // get the "pointed to" type (ignoring qualifiers at the top level)
2331 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2332 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2333
2334 // make sure we operate on the canonical type
2335 lhptee = Context.getCanonicalType(lhptee);
2336 rhptee = Context.getCanonicalType(rhptee);
2337
2338 AssignConvertType ConvTy = Compatible;
2339
2340 // For blocks we enforce that qualifiers are identical.
2341 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2342 ConvTy = CompatiblePointerDiscardsQualifiers;
2343
2344 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2345 return IncompatibleBlockPointer;
2346 return ConvTy;
2347}
2348
Chris Lattner4b009652007-07-25 00:24:17 +00002349/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2350/// has code to accommodate several GCC extensions when type checking
2351/// pointers. Here are some objectionable examples that GCC considers warnings:
2352///
2353/// int a, *pint;
2354/// short *pshort;
2355/// struct foo *pfoo;
2356///
2357/// pint = pshort; // warning: assignment from incompatible pointer type
2358/// a = pint; // warning: assignment makes integer from pointer without a cast
2359/// pint = a; // warning: assignment makes pointer from integer without a cast
2360/// pint = pfoo; // warning: assignment from incompatible pointer type
2361///
2362/// As a result, the code for dealing with pointers is more complex than the
2363/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002364///
Chris Lattner005ed752008-01-04 18:04:52 +00002365Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002366Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002367 // Get canonical types. We're not formatting these types, just comparing
2368 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002369 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2370 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002371
2372 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002373 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002374
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002375 // If the left-hand side is a reference type, then we are in a
2376 // (rare!) case where we've allowed the use of references in C,
2377 // e.g., as a parameter type in a built-in function. In this case,
2378 // just make sure that the type referenced is compatible with the
2379 // right-hand side type. The caller is responsible for adjusting
2380 // lhsType so that the resulting expression does not have reference
2381 // type.
2382 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2383 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002384 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002385 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002386 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002387
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002388 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2389 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002390 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002391 // Relax integer conversions like we do for pointers below.
2392 if (rhsType->isIntegerType())
2393 return IntToPointer;
2394 if (lhsType->isIntegerType())
2395 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002396 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002397 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002398
Nate Begemanc5f0f652008-07-14 18:02:46 +00002399 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002400 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002401 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2402 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002403 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002404
Nate Begemanc5f0f652008-07-14 18:02:46 +00002405 // If we are allowing lax vector conversions, and LHS and RHS are both
2406 // vectors, the total size only needs to be the same. This is a bitcast;
2407 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002408 if (getLangOptions().LaxVectorConversions &&
2409 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002410 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2411 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002412 }
2413 return Incompatible;
2414 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002415
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002416 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002417 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002418
Chris Lattner390564e2008-04-07 06:49:41 +00002419 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002420 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002421 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002422
Chris Lattner390564e2008-04-07 06:49:41 +00002423 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002424 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002425
Steve Naroffa982c712008-09-29 18:10:17 +00002426 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002427 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002428 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002429
2430 // Treat block pointers as objects.
2431 if (getLangOptions().ObjC1 &&
2432 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2433 return Compatible;
2434 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002435 return Incompatible;
2436 }
2437
2438 if (isa<BlockPointerType>(lhsType)) {
2439 if (rhsType->isIntegerType())
2440 return IntToPointer;
2441
Steve Naroffa982c712008-09-29 18:10:17 +00002442 // Treat block pointers as objects.
2443 if (getLangOptions().ObjC1 &&
2444 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2445 return Compatible;
2446
Steve Naroff3454b6c2008-09-04 15:10:53 +00002447 if (rhsType->isBlockPointerType())
2448 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2449
2450 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2451 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002452 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002453 }
Chris Lattner1853da22008-01-04 23:18:45 +00002454 return Incompatible;
2455 }
2456
Chris Lattner390564e2008-04-07 06:49:41 +00002457 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002458 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002459 if (lhsType == Context.BoolTy)
2460 return Compatible;
2461
2462 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002463 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002464
Chris Lattner390564e2008-04-07 06:49:41 +00002465 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002466 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002467
2468 if (isa<BlockPointerType>(lhsType) &&
2469 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002470 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002471 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002472 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002473
Chris Lattner1853da22008-01-04 23:18:45 +00002474 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002475 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002476 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002477 }
2478 return Incompatible;
2479}
2480
Chris Lattner005ed752008-01-04 18:04:52 +00002481Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002482Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002483 if (getLangOptions().CPlusPlus) {
2484 if (!lhsType->isRecordType()) {
2485 // C++ 5.17p3: If the left operand is not of class type, the
2486 // expression is implicitly converted (C++ 4) to the
2487 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002488 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2489 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002490 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002491 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002492 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002493 }
2494
2495 // FIXME: Currently, we fall through and treat C++ classes like C
2496 // structures.
2497 }
2498
Steve Naroffcdee22d2007-11-27 17:58:44 +00002499 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2500 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002501 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2502 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002503 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002504 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002505 return Compatible;
2506 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002507
2508 // We don't allow conversion of non-null-pointer constants to integers.
2509 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2510 return IntToBlockPointer;
2511
Chris Lattner5f505bf2007-10-16 02:55:40 +00002512 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002513 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002514 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002515 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002516 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002517 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002518 if (!lhsType->isReferenceType())
2519 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002520
Chris Lattner005ed752008-01-04 18:04:52 +00002521 Sema::AssignConvertType result =
2522 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002523
2524 // C99 6.5.16.1p2: The value of the right operand is converted to the
2525 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002526 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2527 // so that we can use references in built-in functions even in C.
2528 // The getNonReferenceType() call makes sure that the resulting expression
2529 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002530 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002531 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002532 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002533}
2534
Chris Lattner005ed752008-01-04 18:04:52 +00002535Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002536Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2537 return CheckAssignmentConstraints(lhsType, rhsType);
2538}
2539
Chris Lattner1eafdea2008-11-18 01:30:42 +00002540QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002541 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002542 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002543 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002544 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002545}
2546
Chris Lattner1eafdea2008-11-18 01:30:42 +00002547inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002548 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002549 // For conversion purposes, we ignore any qualifiers.
2550 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002551 QualType lhsType =
2552 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2553 QualType rhsType =
2554 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002555
Nate Begemanc5f0f652008-07-14 18:02:46 +00002556 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002557 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002558 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002559
Nate Begemanc5f0f652008-07-14 18:02:46 +00002560 // Handle the case of a vector & extvector type of the same size and element
2561 // type. It would be nice if we only had one vector type someday.
2562 if (getLangOptions().LaxVectorConversions)
2563 if (const VectorType *LV = lhsType->getAsVectorType())
2564 if (const VectorType *RV = rhsType->getAsVectorType())
2565 if (LV->getElementType() == RV->getElementType() &&
2566 LV->getNumElements() == RV->getNumElements())
2567 return lhsType->isExtVectorType() ? lhsType : rhsType;
2568
2569 // If the lhs is an extended vector and the rhs is a scalar of the same type
2570 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002571 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002572 QualType eltType = V->getElementType();
2573
2574 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2575 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2576 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002577 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002578 return lhsType;
2579 }
2580 }
2581
Nate Begemanc5f0f652008-07-14 18:02:46 +00002582 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002583 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002584 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002585 QualType eltType = V->getElementType();
2586
2587 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2588 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2589 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002590 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002591 return rhsType;
2592 }
2593 }
2594
Chris Lattner4b009652007-07-25 00:24:17 +00002595 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002596 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002597 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002598 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002599 return QualType();
2600}
2601
2602inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002603 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002604{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002605 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002606 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002607
Steve Naroff8f708362007-08-24 19:07:16 +00002608 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002609
Chris Lattner4b009652007-07-25 00:24:17 +00002610 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002611 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002612 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002613}
2614
2615inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002616 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002617{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002618 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2619 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2620 return CheckVectorOperands(Loc, lex, rex);
2621 return InvalidOperands(Loc, lex, rex);
2622 }
Chris Lattner4b009652007-07-25 00:24:17 +00002623
Steve Naroff8f708362007-08-24 19:07:16 +00002624 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002625
Chris Lattner4b009652007-07-25 00:24:17 +00002626 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002627 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002628 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002629}
2630
2631inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002632 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002633{
2634 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002635 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002636
Steve Naroff8f708362007-08-24 19:07:16 +00002637 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002638
Chris Lattner4b009652007-07-25 00:24:17 +00002639 // handle the common case first (both operands are arithmetic).
2640 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002641 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002642
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002643 // Put any potential pointer into PExp
2644 Expr* PExp = lex, *IExp = rex;
2645 if (IExp->getType()->isPointerType())
2646 std::swap(PExp, IExp);
2647
2648 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2649 if (IExp->getType()->isIntegerType()) {
2650 // Check for arithmetic on pointers to incomplete types
2651 if (!PTy->getPointeeType()->isObjectType()) {
2652 if (PTy->getPointeeType()->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002653 Diag(Loc, diag::ext_gnu_void_ptr)
2654 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002655 } else if (PTy->getPointeeType()->isFunctionType()) {
2656 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002657 << lex->getType() << lex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002658 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002659 } else {
2660 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2661 diag::err_typecheck_arithmetic_incomplete_type,
2662 lex->getSourceRange(), SourceRange(),
2663 lex->getType());
2664 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002665 }
2666 }
2667 return PExp->getType();
2668 }
2669 }
2670
Chris Lattner1eafdea2008-11-18 01:30:42 +00002671 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002672}
2673
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002674// C99 6.5.6
2675QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002676 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002677 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002678 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002679
Steve Naroff8f708362007-08-24 19:07:16 +00002680 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002681
Chris Lattnerf6da2912007-12-09 21:53:25 +00002682 // Enforce type constraints: C99 6.5.6p3.
2683
2684 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002685 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002686 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002687
2688 // Either ptr - int or ptr - ptr.
2689 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002690 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002691
Chris Lattnerf6da2912007-12-09 21:53:25 +00002692 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002693 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002694 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002695 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002696 Diag(Loc, diag::ext_gnu_void_ptr)
2697 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002698 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002699 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002700 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002701 return QualType();
2702 }
2703 }
2704
2705 // The result type of a pointer-int computation is the pointer type.
2706 if (rex->getType()->isIntegerType())
2707 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002708
Chris Lattnerf6da2912007-12-09 21:53:25 +00002709 // Handle pointer-pointer subtractions.
2710 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002711 QualType rpointee = RHSPTy->getPointeeType();
2712
Chris Lattnerf6da2912007-12-09 21:53:25 +00002713 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002714 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002715 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002716 if (rpointee->isVoidType()) {
2717 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002718 Diag(Loc, diag::ext_gnu_void_ptr)
2719 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002720 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002721 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002722 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002723 return QualType();
2724 }
2725 }
2726
2727 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002728 if (!Context.typesAreCompatible(
2729 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2730 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002731 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002732 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002733 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002734 return QualType();
2735 }
2736
2737 return Context.getPointerDiffType();
2738 }
2739 }
2740
Chris Lattner1eafdea2008-11-18 01:30:42 +00002741 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002742}
2743
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002744// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002745QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002746 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002747 // C99 6.5.7p2: Each of the operands shall have integer type.
2748 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002749 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002750
Chris Lattner2c8bff72007-12-12 05:47:28 +00002751 // Shifts don't perform usual arithmetic conversions, they just do integer
2752 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002753 if (!isCompAssign)
2754 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002755 UsualUnaryConversions(rex);
2756
2757 // "The type of the result is that of the promoted left operand."
2758 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002759}
2760
Eli Friedman0d9549b2008-08-22 00:56:42 +00002761static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2762 ASTContext& Context) {
2763 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2764 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2765 // ID acts sort of like void* for ObjC interfaces
2766 if (LHSIface && Context.isObjCIdType(RHS))
2767 return true;
2768 if (RHSIface && Context.isObjCIdType(LHS))
2769 return true;
2770 if (!LHSIface || !RHSIface)
2771 return false;
2772 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2773 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2774}
2775
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002776// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002777QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002778 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002779 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002780 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002781
Chris Lattner254f3bc2007-08-26 01:18:55 +00002782 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002783 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2784 UsualArithmeticConversions(lex, rex);
2785 else {
2786 UsualUnaryConversions(lex);
2787 UsualUnaryConversions(rex);
2788 }
Chris Lattner4b009652007-07-25 00:24:17 +00002789 QualType lType = lex->getType();
2790 QualType rType = rex->getType();
2791
Ted Kremenek486509e2007-10-29 17:13:39 +00002792 // For non-floating point types, check for self-comparisons of the form
2793 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2794 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002795 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002796 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2797 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002798 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002799 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002800 }
2801
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002802 // The result of comparisons is 'bool' in C++, 'int' in C.
2803 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2804
Chris Lattner254f3bc2007-08-26 01:18:55 +00002805 if (isRelational) {
2806 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002807 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002808 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002809 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002810 if (lType->isFloatingType()) {
2811 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002812 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002813 }
2814
Chris Lattner254f3bc2007-08-26 01:18:55 +00002815 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002816 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002817 }
Chris Lattner4b009652007-07-25 00:24:17 +00002818
Chris Lattner22be8422007-08-26 01:10:14 +00002819 bool LHSIsNull = lex->isNullPointerConstant(Context);
2820 bool RHSIsNull = rex->isNullPointerConstant(Context);
2821
Chris Lattner254f3bc2007-08-26 01:18:55 +00002822 // All of the following pointer related warnings are GCC extensions, except
2823 // when handling null pointer constants. One day, we can consider making them
2824 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002825 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002826 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002827 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002828 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002829 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002830
Steve Naroff3b435622007-11-13 14:57:38 +00002831 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002832 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2833 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002834 RCanPointeeTy.getUnqualifiedType()) &&
2835 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002836 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002837 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002838 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002839 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002840 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002841 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002842 // Handle block pointer types.
2843 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2844 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2845 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2846
2847 if (!LHSIsNull && !RHSIsNull &&
2848 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002849 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002850 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00002851 }
2852 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002853 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002854 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002855 // Allow block pointers to be compared with null pointer constants.
2856 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2857 (lType->isPointerType() && rType->isBlockPointerType())) {
2858 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002859 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002860 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00002861 }
2862 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002863 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00002864 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002865
Steve Naroff936c4362008-06-03 14:04:54 +00002866 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002867 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00002868 const PointerType *LPT = lType->getAsPointerType();
2869 const PointerType *RPT = rType->getAsPointerType();
2870 bool LPtrToVoid = LPT ?
2871 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2872 bool RPtrToVoid = RPT ?
2873 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2874
2875 if (!LPtrToVoid && !RPtrToVoid &&
2876 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002877 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002878 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00002879 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002880 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00002881 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002882 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002883 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002884 }
Steve Naroff936c4362008-06-03 14:04:54 +00002885 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2886 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002887 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002888 } else {
2889 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002890 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00002891 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002892 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002893 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002894 }
Steve Naroff936c4362008-06-03 14:04:54 +00002895 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002896 }
Steve Naroff936c4362008-06-03 14:04:54 +00002897 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2898 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002899 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002900 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002901 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002902 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002903 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002904 }
Steve Naroff936c4362008-06-03 14:04:54 +00002905 if (lType->isIntegerType() &&
2906 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002907 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002908 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002909 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002910 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002911 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002912 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002913 // Handle block pointers.
2914 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2915 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002916 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002917 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002918 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002919 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002920 }
2921 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2922 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002923 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002924 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002925 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002926 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002927 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00002928 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002929}
2930
Nate Begemanc5f0f652008-07-14 18:02:46 +00002931/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2932/// operates on extended vector types. Instead of producing an IntTy result,
2933/// like a scalar comparison, a vector comparison produces a vector of integer
2934/// types.
2935QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002936 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00002937 bool isRelational) {
2938 // Check to make sure we're operating on vectors of the same type and width,
2939 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002940 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002941 if (vType.isNull())
2942 return vType;
2943
2944 QualType lType = lex->getType();
2945 QualType rType = rex->getType();
2946
2947 // For non-floating point types, check for self-comparisons of the form
2948 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2949 // often indicate logic errors in the program.
2950 if (!lType->isFloatingType()) {
2951 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2952 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2953 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002954 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002955 }
2956
2957 // Check for comparisons of floating point operands using != and ==.
2958 if (!isRelational && lType->isFloatingType()) {
2959 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002960 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002961 }
2962
2963 // Return the type for the comparison, which is the same as vector type for
2964 // integer vectors, or an integer type of identical size and number of
2965 // elements for floating point vectors.
2966 if (lType->isIntegerType())
2967 return lType;
2968
2969 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00002970 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00002971 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00002972 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00002973 else if (TypeSize == Context.getTypeSize(Context.LongTy))
2974 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
2975
2976 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
2977 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00002978 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2979}
2980
Chris Lattner4b009652007-07-25 00:24:17 +00002981inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002982 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002983{
2984 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002985 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002986
Steve Naroff8f708362007-08-24 19:07:16 +00002987 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002988
2989 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002990 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002991 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002992}
2993
2994inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00002995 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00002996{
2997 UsualUnaryConversions(lex);
2998 UsualUnaryConversions(rex);
2999
Eli Friedmanbea3f842008-05-13 20:16:47 +00003000 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003001 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003002 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003003}
3004
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003005/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3006/// is a read-only property; return true if so. A readonly property expression
3007/// depends on various declarations and thus must be treated specially.
3008///
3009static bool IsReadonlyProperty(Expr *E, Sema &S)
3010{
3011 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3012 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3013 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3014 QualType BaseType = PropExpr->getBase()->getType();
3015 if (const PointerType *PTy = BaseType->getAsPointerType())
3016 if (const ObjCInterfaceType *IFTy =
3017 PTy->getPointeeType()->getAsObjCInterfaceType())
3018 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3019 if (S.isPropertyReadonly(PDecl, IFace))
3020 return true;
3021 }
3022 }
3023 return false;
3024}
3025
Chris Lattner4c2642c2008-11-18 01:22:49 +00003026/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3027/// emit an error and return true. If so, return false.
3028static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003029 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3030 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3031 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003032 if (IsLV == Expr::MLV_Valid)
3033 return false;
3034
3035 unsigned Diag = 0;
3036 bool NeedType = false;
3037 switch (IsLV) { // C99 6.5.16p2
3038 default: assert(0 && "Unknown result from isModifiableLvalue!");
3039 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00003040 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003041 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3042 NeedType = true;
3043 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003044 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003045 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3046 NeedType = true;
3047 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003048 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003049 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3050 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003051 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003052 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3053 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003054 case Expr::MLV_IncompleteType:
3055 case Expr::MLV_IncompleteVoidType:
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003056 return S.DiagnoseIncompleteType(Loc, E->getType(),
3057 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3058 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003059 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003060 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3061 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003062 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003063 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3064 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003065 case Expr::MLV_ReadonlyProperty:
3066 Diag = diag::error_readonly_property_assignment;
3067 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003068 case Expr::MLV_NoSetterProperty:
3069 Diag = diag::error_nosetter_property_assignment;
3070 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003071 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003072
Chris Lattner4c2642c2008-11-18 01:22:49 +00003073 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003074 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003075 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003076 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003077 return true;
3078}
3079
3080
3081
3082// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003083QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3084 SourceLocation Loc,
3085 QualType CompoundType) {
3086 // Verify that LHS is a modifiable lvalue, and emit error if not.
3087 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003088 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003089
3090 QualType LHSType = LHS->getType();
3091 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003092
Chris Lattner005ed752008-01-04 18:04:52 +00003093 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003094 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003095 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003096 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003097 // Special case of NSObject attributes on c-style pointer types.
3098 if (ConvTy == IncompatiblePointer &&
3099 ((Context.isObjCNSObjectType(LHSType) &&
3100 Context.isObjCObjectPointerType(RHSType)) ||
3101 (Context.isObjCNSObjectType(RHSType) &&
3102 Context.isObjCObjectPointerType(LHSType))))
3103 ConvTy = Compatible;
3104
Chris Lattner34c85082008-08-21 18:04:13 +00003105 // If the RHS is a unary plus or minus, check to see if they = and + are
3106 // right next to each other. If so, the user may have typo'd "x =+ 4"
3107 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003108 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003109 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3110 RHSCheck = ICE->getSubExpr();
3111 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3112 if ((UO->getOpcode() == UnaryOperator::Plus ||
3113 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003114 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003115 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003116 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003117 Diag(Loc, diag::warn_not_compound_assign)
3118 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3119 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003120 }
3121 } else {
3122 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003123 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003124 }
Chris Lattner005ed752008-01-04 18:04:52 +00003125
Chris Lattner1eafdea2008-11-18 01:30:42 +00003126 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3127 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003128 return QualType();
3129
Chris Lattner4b009652007-07-25 00:24:17 +00003130 // C99 6.5.16p3: The type of an assignment expression is the type of the
3131 // left operand unless the left operand has qualified type, in which case
3132 // it is the unqualified version of the type of the left operand.
3133 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3134 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003135 // C++ 5.17p1: the type of the assignment expression is that of its left
3136 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003137 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003138}
3139
Chris Lattner1eafdea2008-11-18 01:30:42 +00003140// C99 6.5.17
3141QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3142 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00003143
3144 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003145 DefaultFunctionArrayConversion(RHS);
3146 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003147}
3148
3149/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3150/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003151QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3152 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003153 QualType ResType = Op->getType();
3154 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003155
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003156 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3157 // Decrement of bool is not allowed.
3158 if (!isInc) {
3159 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3160 return QualType();
3161 }
3162 // Increment of bool sets it to true, but is deprecated.
3163 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3164 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003165 // OK!
3166 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3167 // C99 6.5.2.4p2, 6.5.6p2
3168 if (PT->getPointeeType()->isObjectType()) {
3169 // Pointer to object is ok!
3170 } else if (PT->getPointeeType()->isVoidType()) {
3171 // Pointer to void is extension.
3172 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003173 } else if (PT->getPointeeType()->isFunctionType()) {
3174 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003175 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003176 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003177 } else {
3178 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3179 diag::err_typecheck_arithmetic_incomplete_type,
3180 Op->getSourceRange(), SourceRange(),
3181 ResType);
3182 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003183 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003184 } else if (ResType->isComplexType()) {
3185 // C99 does not support ++/-- on complex types, we allow as an extension.
3186 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003187 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003188 } else {
3189 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003190 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003191 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003192 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00003193 // At this point, we know we have a real, complex or pointer type.
3194 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003195 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003196 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003197 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003198}
3199
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003200/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003201/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003202/// where the declaration is needed for type checking. We only need to
3203/// handle cases when the expression references a function designator
3204/// or is an lvalue. Here are some examples:
3205/// - &(x) => x
3206/// - &*****f => f for f a function designator.
3207/// - &s.xx => s
3208/// - &s.zz[1].yy -> s, if zz is an array
3209/// - *(x + 1) -> x, if x is an array
3210/// - &"123"[2] -> 0
3211/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003212static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003213 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003214 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003215 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003216 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003217 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003218 // Fields cannot be declared with a 'register' storage class.
3219 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003220 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003221 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003222 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003223 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003224 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003225
Douglas Gregord2baafd2008-10-21 16:13:35 +00003226 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003227 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003228 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003229 return 0;
3230 else
3231 return VD;
3232 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003233 case Stmt::UnaryOperatorClass: {
3234 UnaryOperator *UO = cast<UnaryOperator>(E);
3235
3236 switch(UO->getOpcode()) {
3237 case UnaryOperator::Deref: {
3238 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003239 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3240 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3241 if (!VD || VD->getType()->isPointerType())
3242 return 0;
3243 return VD;
3244 }
3245 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003246 }
3247 case UnaryOperator::Real:
3248 case UnaryOperator::Imag:
3249 case UnaryOperator::Extension:
3250 return getPrimaryDecl(UO->getSubExpr());
3251 default:
3252 return 0;
3253 }
3254 }
3255 case Stmt::BinaryOperatorClass: {
3256 BinaryOperator *BO = cast<BinaryOperator>(E);
3257
3258 // Handle cases involving pointer arithmetic. The result of an
3259 // Assign or AddAssign is not an lvalue so they can be ignored.
3260
3261 // (x + n) or (n + x) => x
3262 if (BO->getOpcode() == BinaryOperator::Add) {
3263 if (BO->getLHS()->getType()->isPointerType()) {
3264 return getPrimaryDecl(BO->getLHS());
3265 } else if (BO->getRHS()->getType()->isPointerType()) {
3266 return getPrimaryDecl(BO->getRHS());
3267 }
3268 }
3269
3270 return 0;
3271 }
Chris Lattner4b009652007-07-25 00:24:17 +00003272 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003273 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003274 case Stmt::ImplicitCastExprClass:
3275 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003276 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003277 default:
3278 return 0;
3279 }
3280}
3281
3282/// CheckAddressOfOperand - The operand of & must be either a function
3283/// designator or an lvalue designating an object. If it is an lvalue, the
3284/// object cannot be declared with storage class register or be a bit field.
3285/// Note: The usual conversions are *not* applied to the operand of the &
3286/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00003287/// In C++, the operand might be an overloaded function name, in which case
3288/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003289QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003290 if (op->isTypeDependent())
3291 return Context.DependentTy;
3292
Steve Naroff9c6c3592008-01-13 17:10:08 +00003293 if (getLangOptions().C99) {
3294 // Implement C99-only parts of addressof rules.
3295 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3296 if (uOp->getOpcode() == UnaryOperator::Deref)
3297 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3298 // (assuming the deref expression is valid).
3299 return uOp->getSubExpr()->getType();
3300 }
3301 // Technically, there should be a check for array subscript
3302 // expressions here, but the result of one is always an lvalue anyway.
3303 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003304 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003305 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003306
Chris Lattner4b009652007-07-25 00:24:17 +00003307 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003308 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3309 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003310 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3311 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003312 return QualType();
3313 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003314 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003315 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3316 if (Field->isBitField()) {
3317 Diag(OpLoc, diag::err_typecheck_address_of)
3318 << "bit-field" << op->getSourceRange();
3319 return QualType();
3320 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003321 }
3322 // Check for Apple extension for accessing vector components.
3323 } else if (isa<ArraySubscriptExpr>(op) &&
3324 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003325 Diag(OpLoc, diag::err_typecheck_address_of)
3326 << "vector" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003327 return QualType();
3328 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00003329 // We have an lvalue with a decl. Make sure the decl is not declared
3330 // with the register storage-class specifier.
3331 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3332 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003333 Diag(OpLoc, diag::err_typecheck_address_of)
3334 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003335 return QualType();
3336 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003337 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003338 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003339 } else if (isa<FieldDecl>(dcl)) {
3340 // Okay: we can take the address of a field.
Nuno Lopesdf239522008-12-16 22:58:26 +00003341 } else if (isa<FunctionDecl>(dcl)) {
3342 // Okay: we can take the address of a function.
Douglas Gregor5b82d612008-12-10 21:26:49 +00003343 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003344 else
Chris Lattner4b009652007-07-25 00:24:17 +00003345 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003346 }
Chris Lattnera55e3212008-07-27 00:48:22 +00003347
Chris Lattner4b009652007-07-25 00:24:17 +00003348 // If the operand has type "type", the result has type "pointer to type".
3349 return Context.getPointerType(op->getType());
3350}
3351
Chris Lattnerda5c0872008-11-23 09:13:29 +00003352QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3353 UsualUnaryConversions(Op);
3354 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003355
Chris Lattnerda5c0872008-11-23 09:13:29 +00003356 // Note that per both C89 and C99, this is always legal, even if ptype is an
3357 // incomplete type or void. It would be possible to warn about dereferencing
3358 // a void pointer, but it's completely well-defined, and such a warning is
3359 // unlikely to catch any mistakes.
3360 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003361 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00003362
Chris Lattner77d52da2008-11-20 06:06:08 +00003363 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003364 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003365 return QualType();
3366}
3367
3368static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3369 tok::TokenKind Kind) {
3370 BinaryOperator::Opcode Opc;
3371 switch (Kind) {
3372 default: assert(0 && "Unknown binop!");
3373 case tok::star: Opc = BinaryOperator::Mul; break;
3374 case tok::slash: Opc = BinaryOperator::Div; break;
3375 case tok::percent: Opc = BinaryOperator::Rem; break;
3376 case tok::plus: Opc = BinaryOperator::Add; break;
3377 case tok::minus: Opc = BinaryOperator::Sub; break;
3378 case tok::lessless: Opc = BinaryOperator::Shl; break;
3379 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3380 case tok::lessequal: Opc = BinaryOperator::LE; break;
3381 case tok::less: Opc = BinaryOperator::LT; break;
3382 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3383 case tok::greater: Opc = BinaryOperator::GT; break;
3384 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3385 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3386 case tok::amp: Opc = BinaryOperator::And; break;
3387 case tok::caret: Opc = BinaryOperator::Xor; break;
3388 case tok::pipe: Opc = BinaryOperator::Or; break;
3389 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3390 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3391 case tok::equal: Opc = BinaryOperator::Assign; break;
3392 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3393 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3394 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3395 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3396 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3397 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3398 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3399 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3400 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3401 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3402 case tok::comma: Opc = BinaryOperator::Comma; break;
3403 }
3404 return Opc;
3405}
3406
3407static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3408 tok::TokenKind Kind) {
3409 UnaryOperator::Opcode Opc;
3410 switch (Kind) {
3411 default: assert(0 && "Unknown unary op!");
3412 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3413 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3414 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3415 case tok::star: Opc = UnaryOperator::Deref; break;
3416 case tok::plus: Opc = UnaryOperator::Plus; break;
3417 case tok::minus: Opc = UnaryOperator::Minus; break;
3418 case tok::tilde: Opc = UnaryOperator::Not; break;
3419 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003420 case tok::kw___real: Opc = UnaryOperator::Real; break;
3421 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3422 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3423 }
3424 return Opc;
3425}
3426
Douglas Gregord7f915e2008-11-06 23:29:22 +00003427/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3428/// operator @p Opc at location @c TokLoc. This routine only supports
3429/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003430Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3431 unsigned Op,
3432 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003433 QualType ResultTy; // Result type of the binary operator.
3434 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3435 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3436
3437 switch (Opc) {
3438 default:
3439 assert(0 && "Unknown binary expr!");
3440 case BinaryOperator::Assign:
3441 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3442 break;
3443 case BinaryOperator::Mul:
3444 case BinaryOperator::Div:
3445 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3446 break;
3447 case BinaryOperator::Rem:
3448 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3449 break;
3450 case BinaryOperator::Add:
3451 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3452 break;
3453 case BinaryOperator::Sub:
3454 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3455 break;
3456 case BinaryOperator::Shl:
3457 case BinaryOperator::Shr:
3458 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3459 break;
3460 case BinaryOperator::LE:
3461 case BinaryOperator::LT:
3462 case BinaryOperator::GE:
3463 case BinaryOperator::GT:
3464 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3465 break;
3466 case BinaryOperator::EQ:
3467 case BinaryOperator::NE:
3468 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3469 break;
3470 case BinaryOperator::And:
3471 case BinaryOperator::Xor:
3472 case BinaryOperator::Or:
3473 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3474 break;
3475 case BinaryOperator::LAnd:
3476 case BinaryOperator::LOr:
3477 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3478 break;
3479 case BinaryOperator::MulAssign:
3480 case BinaryOperator::DivAssign:
3481 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3482 if (!CompTy.isNull())
3483 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3484 break;
3485 case BinaryOperator::RemAssign:
3486 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3487 if (!CompTy.isNull())
3488 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3489 break;
3490 case BinaryOperator::AddAssign:
3491 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3492 if (!CompTy.isNull())
3493 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3494 break;
3495 case BinaryOperator::SubAssign:
3496 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3497 if (!CompTy.isNull())
3498 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3499 break;
3500 case BinaryOperator::ShlAssign:
3501 case BinaryOperator::ShrAssign:
3502 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3503 if (!CompTy.isNull())
3504 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3505 break;
3506 case BinaryOperator::AndAssign:
3507 case BinaryOperator::XorAssign:
3508 case BinaryOperator::OrAssign:
3509 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3510 if (!CompTy.isNull())
3511 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3512 break;
3513 case BinaryOperator::Comma:
3514 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3515 break;
3516 }
3517 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003518 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003519 if (CompTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003520 return Owned(new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003521 else
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003522 return Owned(new CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
3523 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003524}
3525
Chris Lattner4b009652007-07-25 00:24:17 +00003526// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003527Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3528 tok::TokenKind Kind,
3529 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003530 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003531 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003532
Steve Naroff87d58b42007-09-16 03:34:24 +00003533 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3534 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003535
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003536 // If either expression is type-dependent, just build the AST.
3537 // FIXME: We'll need to perform some caching of the result of name
3538 // lookup for operator+.
3539 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
3540 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003541 return Owned(new CompoundAssignOperator(lhs, rhs, Opc,
3542 Context.DependentTy,
3543 Context.DependentTy, TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003544 else
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003545 return Owned(new BinaryOperator(lhs, rhs, Opc, Context.DependentTy,
3546 TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003547 }
3548
Douglas Gregord7f915e2008-11-06 23:29:22 +00003549 if (getLangOptions().CPlusPlus &&
3550 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3551 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003552 // If this is one of the assignment operators, we only perform
3553 // overload resolution if the left-hand side is a class or
3554 // enumeration type (C++ [expr.ass]p3).
3555 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3556 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3557 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3558 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003559
Douglas Gregord7f915e2008-11-06 23:29:22 +00003560 // Determine which overloaded operator we're dealing with.
3561 static const OverloadedOperatorKind OverOps[] = {
3562 OO_Star, OO_Slash, OO_Percent,
3563 OO_Plus, OO_Minus,
3564 OO_LessLess, OO_GreaterGreater,
3565 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3566 OO_EqualEqual, OO_ExclaimEqual,
3567 OO_Amp,
3568 OO_Caret,
3569 OO_Pipe,
3570 OO_AmpAmp,
3571 OO_PipePipe,
3572 OO_Equal, OO_StarEqual,
3573 OO_SlashEqual, OO_PercentEqual,
3574 OO_PlusEqual, OO_MinusEqual,
3575 OO_LessLessEqual, OO_GreaterGreaterEqual,
3576 OO_AmpEqual, OO_CaretEqual,
3577 OO_PipeEqual,
3578 OO_Comma
3579 };
3580 OverloadedOperatorKind OverOp = OverOps[Opc];
3581
Douglas Gregor5ed15042008-11-18 23:14:02 +00003582 // Add the appropriate overloaded operators (C++ [over.match.oper])
3583 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003584 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003585 Expr *Args[2] = { lhs, rhs };
Douglas Gregor5ed15042008-11-18 23:14:02 +00003586 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregord7f915e2008-11-06 23:29:22 +00003587
3588 // Perform overload resolution.
3589 OverloadCandidateSet::iterator Best;
3590 switch (BestViableFunction(CandidateSet, Best)) {
3591 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003592 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003593 FunctionDecl *FnDecl = Best->Function;
3594
Douglas Gregor70d26122008-11-12 17:17:38 +00003595 if (FnDecl) {
3596 // We matched an overloaded operator. Build a call to that
3597 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003598
Douglas Gregor70d26122008-11-12 17:17:38 +00003599 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003600 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3601 if (PerformObjectArgumentInitialization(lhs, Method) ||
3602 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3603 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003604 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003605 } else {
3606 // Convert the arguments.
3607 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3608 "passing") ||
3609 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3610 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003611 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003612 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003613
Douglas Gregor70d26122008-11-12 17:17:38 +00003614 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003615 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003616 = FnDecl->getType()->getAsFunctionType()->getResultType();
3617 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003618
Douglas Gregor70d26122008-11-12 17:17:38 +00003619 // Build the actual expression node.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003620 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003621 SourceLocation());
3622 UsualUnaryConversions(FnExpr);
3623
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003624 return Owned(new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy,TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003625 } else {
3626 // We matched a built-in operator. Convert the arguments, then
3627 // break out so that we will build the appropriate built-in
3628 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003629 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3630 Best->Conversions[0], "passing") ||
3631 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3632 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003633 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003634
3635 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003636 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003637 }
3638
3639 case OR_No_Viable_Function:
3640 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003641 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003642 break;
3643
3644 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003645 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3646 << BinaryOperator::getOpcodeStr(Opc)
3647 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003648 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003649 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003650 }
3651
Douglas Gregor70d26122008-11-12 17:17:38 +00003652 // Either we found no viable overloaded operator or we matched a
3653 // built-in operator. In either case, fall through to trying to
3654 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003655 }
3656
Douglas Gregord7f915e2008-11-06 23:29:22 +00003657 // Build a built-in binary operation.
3658 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003659}
3660
3661// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00003662Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3663 tok::TokenKind Op, ExprArg input) {
3664 // FIXME: Input is modified later, but smart pointer not reassigned.
3665 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00003666 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003667
3668 if (getLangOptions().CPlusPlus &&
3669 (Input->getType()->isRecordType()
3670 || Input->getType()->isEnumeralType())) {
3671 // Determine which overloaded operator we're dealing with.
3672 static const OverloadedOperatorKind OverOps[] = {
3673 OO_None, OO_None,
3674 OO_PlusPlus, OO_MinusMinus,
3675 OO_Amp, OO_Star,
3676 OO_Plus, OO_Minus,
3677 OO_Tilde, OO_Exclaim,
3678 OO_None, OO_None,
3679 OO_None,
3680 OO_None
3681 };
3682 OverloadedOperatorKind OverOp = OverOps[Opc];
3683
3684 // Add the appropriate overloaded operators (C++ [over.match.oper])
3685 // to the candidate set.
3686 OverloadCandidateSet CandidateSet;
3687 if (OverOp != OO_None)
3688 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3689
3690 // Perform overload resolution.
3691 OverloadCandidateSet::iterator Best;
3692 switch (BestViableFunction(CandidateSet, Best)) {
3693 case OR_Success: {
3694 // We found a built-in operator or an overloaded operator.
3695 FunctionDecl *FnDecl = Best->Function;
3696
3697 if (FnDecl) {
3698 // We matched an overloaded operator. Build a call to that
3699 // operator.
3700
3701 // Convert the arguments.
3702 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3703 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00003704 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003705 } else {
3706 // Convert the arguments.
3707 if (PerformCopyInitialization(Input,
3708 FnDecl->getParamDecl(0)->getType(),
3709 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003710 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003711 }
3712
3713 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00003714 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003715 = FnDecl->getType()->getAsFunctionType()->getResultType();
3716 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00003717
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003718 // Build the actual expression node.
3719 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3720 SourceLocation());
3721 UsualUnaryConversions(FnExpr);
3722
Sebastian Redl8b769972009-01-19 00:08:26 +00003723 input.release();
3724 return Owned(new CXXOperatorCallExpr(FnExpr, &Input, 1,
3725 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003726 } else {
3727 // We matched a built-in operator. Convert the arguments, then
3728 // break out so that we will build the appropriate built-in
3729 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003730 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3731 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003732 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003733
3734 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00003735 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003736 }
3737
3738 case OR_No_Viable_Function:
3739 // No viable function; fall through to handling this as a
3740 // built-in operator, which will produce an error message for us.
3741 break;
3742
3743 case OR_Ambiguous:
3744 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3745 << UnaryOperator::getOpcodeStr(Opc)
3746 << Input->getSourceRange();
3747 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00003748 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003749 }
3750
3751 // Either we found no viable overloaded operator or we matched a
3752 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00003753 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003754 }
3755
Chris Lattner4b009652007-07-25 00:24:17 +00003756 QualType resultType;
3757 switch (Opc) {
3758 default:
3759 assert(0 && "Unimplemented unary expr!");
3760 case UnaryOperator::PreInc:
3761 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003762 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3763 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00003764 break;
3765 case UnaryOperator::AddrOf:
3766 resultType = CheckAddressOfOperand(Input, OpLoc);
3767 break;
3768 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00003769 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00003770 resultType = CheckIndirectionOperand(Input, OpLoc);
3771 break;
3772 case UnaryOperator::Plus:
3773 case UnaryOperator::Minus:
3774 UsualUnaryConversions(Input);
3775 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003776 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3777 break;
3778 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3779 resultType->isEnumeralType())
3780 break;
3781 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3782 Opc == UnaryOperator::Plus &&
3783 resultType->isPointerType())
3784 break;
3785
Sebastian Redl8b769972009-01-19 00:08:26 +00003786 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3787 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003788 case UnaryOperator::Not: // bitwise complement
3789 UsualUnaryConversions(Input);
3790 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00003791 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3792 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3793 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00003794 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003795 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00003796 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00003797 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3798 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003799 break;
3800 case UnaryOperator::LNot: // logical negation
3801 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
3802 DefaultFunctionArrayConversion(Input);
3803 resultType = Input->getType();
3804 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00003805 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3806 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00003807 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00003808 // In C++, it's bool. C++ 5.3.1p8
3809 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003810 break;
Chris Lattner03931a72007-08-24 21:16:53 +00003811 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00003812 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00003813 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00003814 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003815 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00003816 resultType = Input->getType();
3817 break;
3818 }
3819 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00003820 return ExprError();
3821 input.release();
3822 return Owned(new UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00003823}
3824
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003825/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3826Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00003827 SourceLocation LabLoc,
3828 IdentifierInfo *LabelII) {
3829 // Look up the record for this label identifier.
3830 LabelStmt *&LabelDecl = LabelMap[LabelII];
3831
Daniel Dunbar879788d2008-08-04 16:51:22 +00003832 // If we haven't seen this label yet, create a forward reference. It
3833 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00003834 if (LabelDecl == 0)
3835 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
3836
3837 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00003838 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3839 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00003840}
3841
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003842Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00003843 SourceLocation RPLoc) { // "({..})"
3844 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3845 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3846 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3847
3848 // FIXME: there are a variety of strange constraints to enforce here, for
3849 // example, it is not possible to goto into a stmt expression apparently.
3850 // More semantic analysis is needed.
3851
3852 // FIXME: the last statement in the compount stmt has its value used. We
3853 // should not warn about it being unused.
3854
3855 // If there are sub stmts in the compound stmt, take the type of the last one
3856 // as the type of the stmtexpr.
3857 QualType Ty = Context.VoidTy;
3858
Chris Lattner200964f2008-07-26 19:51:01 +00003859 if (!Compound->body_empty()) {
3860 Stmt *LastStmt = Compound->body_back();
3861 // If LastStmt is a label, skip down through into the body.
3862 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3863 LastStmt = Label->getSubStmt();
3864
3865 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00003866 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00003867 }
Chris Lattner4b009652007-07-25 00:24:17 +00003868
3869 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
3870}
Steve Naroff63bad2d2007-08-01 22:05:33 +00003871
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003872Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
3873 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003874 SourceLocation TypeLoc,
3875 TypeTy *argty,
3876 OffsetOfComponent *CompPtr,
3877 unsigned NumComponents,
3878 SourceLocation RPLoc) {
3879 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3880 assert(!ArgTy.isNull() && "Missing type argument!");
3881
3882 // We must have at least one component that refers to the type, and the first
3883 // one is known to be a field designator. Verify that the ArgTy represents
3884 // a struct/union/class.
3885 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00003886 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003887
3888 // Otherwise, create a compound literal expression as the base, and
3889 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00003890 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003891
Chris Lattnerb37522e2007-08-31 21:49:13 +00003892 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3893 // GCC extension, diagnose them.
3894 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003895 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3896 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00003897
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003898 for (unsigned i = 0; i != NumComponents; ++i) {
3899 const OffsetOfComponent &OC = CompPtr[i];
3900 if (OC.isBrackets) {
3901 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00003902 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003903 if (!AT) {
3904 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003905 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003906 }
3907
Chris Lattner2af6a802007-08-30 17:59:59 +00003908 // FIXME: C++: Verify that operator[] isn't overloaded.
3909
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003910 // C99 6.5.2.1p1
3911 Expr *Idx = static_cast<Expr*>(OC.U.E);
3912 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00003913 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
3914 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003915
3916 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3917 continue;
3918 }
3919
3920 const RecordType *RC = Res->getType()->getAsRecordType();
3921 if (!RC) {
3922 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003923 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003924 }
3925
3926 // Get the decl corresponding to this.
3927 RecordDecl *RD = RC->getDecl();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003928 FieldDecl *MemberDecl
3929 = dyn_cast_or_null<FieldDecl>(LookupDecl(OC.U.IdentInfo,
3930 Decl::IDNS_Ordinary,
Douglas Gregor78d70132009-01-14 22:20:51 +00003931 S, RD, false, false).getAsDecl());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003932 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00003933 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
3934 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00003935
3936 // FIXME: C++: Verify that MemberDecl isn't a static field.
3937 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00003938 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3939 // matter here.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003940 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3941 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003942 }
3943
3944 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3945 BuiltinLoc);
3946}
3947
3948
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003949Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00003950 TypeTy *arg1, TypeTy *arg2,
3951 SourceLocation RPLoc) {
3952 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3953 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3954
3955 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3956
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003957 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00003958}
3959
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003960Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00003961 ExprTy *expr1, ExprTy *expr2,
3962 SourceLocation RPLoc) {
3963 Expr *CondExpr = static_cast<Expr*>(cond);
3964 Expr *LHSExpr = static_cast<Expr*>(expr1);
3965 Expr *RHSExpr = static_cast<Expr*>(expr2);
3966
3967 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3968
3969 // The conditional expression is required to be a constant expression.
3970 llvm::APSInt condEval(32);
3971 SourceLocation ExpLoc;
3972 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003973 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
3974 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00003975
3976 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3977 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3978 RHSExpr->getType();
3979 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3980}
3981
Steve Naroff52a81c02008-09-03 18:15:37 +00003982//===----------------------------------------------------------------------===//
3983// Clang Extensions.
3984//===----------------------------------------------------------------------===//
3985
3986/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00003987void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003988 // Analyze block parameters.
3989 BlockSemaInfo *BSI = new BlockSemaInfo();
3990
3991 // Add BSI to CurBlock.
3992 BSI->PrevBlockInfo = CurBlock;
3993 CurBlock = BSI;
3994
3995 BSI->ReturnType = 0;
3996 BSI->TheScope = BlockScope;
3997
Steve Naroff52059382008-10-10 01:28:17 +00003998 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00003999 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004000}
4001
4002void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004003 // Analyze arguments to block.
4004 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4005 "Not a function declarator!");
4006 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
4007
Steve Naroff52059382008-10-10 01:28:17 +00004008 CurBlock->hasPrototype = FTI.hasPrototype;
4009 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00004010
4011 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4012 // no arguments, not a function that takes a single void argument.
4013 if (FTI.hasPrototype &&
4014 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4015 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4016 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4017 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004018 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004019 } else if (FTI.hasPrototype) {
4020 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004021 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4022 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00004023 }
Steve Naroff52059382008-10-10 01:28:17 +00004024 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4025
4026 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4027 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4028 // If this has an identifier, add it to the scope stack.
4029 if ((*AI)->getIdentifier())
4030 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004031}
4032
4033/// ActOnBlockError - If there is an error parsing a block, this callback
4034/// is invoked to pop the information about the block from the action impl.
4035void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4036 // Ensure that CurBlock is deleted.
4037 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4038
4039 // Pop off CurBlock, handle nested blocks.
4040 CurBlock = CurBlock->PrevBlockInfo;
4041
4042 // FIXME: Delete the ParmVarDecl objects as well???
4043
4044}
4045
4046/// ActOnBlockStmtExpr - This is called when the body of a block statement
4047/// literal was successfully completed. ^(int x){...}
4048Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4049 Scope *CurScope) {
4050 // Ensure that CurBlock is deleted.
4051 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
4052 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
4053
Steve Naroff52059382008-10-10 01:28:17 +00004054 PopDeclContext();
4055
Steve Naroff52a81c02008-09-03 18:15:37 +00004056 // Pop off CurBlock, handle nested blocks.
4057 CurBlock = CurBlock->PrevBlockInfo;
4058
4059 QualType RetTy = Context.VoidTy;
4060 if (BSI->ReturnType)
4061 RetTy = QualType(BSI->ReturnType, 0);
4062
4063 llvm::SmallVector<QualType, 8> ArgTypes;
4064 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4065 ArgTypes.push_back(BSI->Params[i]->getType());
4066
4067 QualType BlockTy;
4068 if (!BSI->hasPrototype)
4069 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4070 else
4071 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004072 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00004073
4074 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00004075
Steve Naroff95029d92008-10-08 18:44:00 +00004076 BSI->TheDecl->setBody(Body.take());
4077 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004078}
4079
Nate Begemanbd881ef2008-01-30 20:50:20 +00004080/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004081/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00004082/// The number of arguments has already been validated to match the number of
4083/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004084static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4085 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004086 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00004087 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004088 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4089 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00004090
4091 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004092 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00004093 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004094 return true;
4095}
4096
4097Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4098 SourceLocation *CommaLocs,
4099 SourceLocation BuiltinLoc,
4100 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004101 // __builtin_overload requires at least 2 arguments
4102 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004103 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4104 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004105
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004106 // The first argument is required to be a constant expression. It tells us
4107 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00004108 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004109 Expr *NParamsExpr = Args[0];
4110 llvm::APSInt constEval(32);
4111 SourceLocation ExpLoc;
4112 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004113 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4114 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004115
4116 // Verify that the number of parameters is > 0
4117 unsigned NumParams = constEval.getZExtValue();
4118 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004119 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4120 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004121 // Verify that we have at least 1 + NumParams arguments to the builtin.
4122 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004123 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4124 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004125
4126 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00004127 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00004128 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004129 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4130 // UsualUnaryConversions will convert the function DeclRefExpr into a
4131 // pointer to function.
4132 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004133 const FunctionTypeProto *FnType = 0;
4134 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4135 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004136
4137 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4138 // parameters, and the number of parameters must match the value passed to
4139 // the builtin.
4140 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004141 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4142 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004143
4144 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00004145 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004146 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004147 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004148 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004149 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4150 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00004151 // Remember our match, and continue processing the remaining arguments
4152 // to catch any errors.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004153 OE = new OverloadExpr(Args, NumArgs, i,
4154 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00004155 BuiltinLoc, RParenLoc);
4156 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004157 }
Nate Begemanc6078c92008-01-31 05:38:29 +00004158 // Return the newly created OverloadExpr node, if we succeded in matching
4159 // exactly one of the candidate functions.
4160 if (OE)
4161 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004162
4163 // If we didn't find a matching function Expr in the __builtin_overload list
4164 // the return an error.
4165 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00004166 for (unsigned i = 0; i != NumParams; ++i) {
4167 if (i != 0) typeNames += ", ";
4168 typeNames += Args[i+1]->getType().getAsString();
4169 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004170
Chris Lattner77d52da2008-11-20 06:06:08 +00004171 return Diag(BuiltinLoc, diag::err_overload_no_match)
4172 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004173}
4174
Anders Carlsson36760332007-10-15 20:28:48 +00004175Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4176 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004177 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004178 Expr *E = static_cast<Expr*>(expr);
4179 QualType T = QualType::getFromOpaquePtr(type);
4180
4181 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004182
4183 // Get the va_list type
4184 QualType VaListType = Context.getBuiltinVaListType();
4185 // Deal with implicit array decay; for example, on x86-64,
4186 // va_list is an array, but it's supposed to decay to
4187 // a pointer for va_arg.
4188 if (VaListType->isArrayType())
4189 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004190 // Make sure the input expression also decays appropriately.
4191 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004192
4193 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004194 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004195 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004196 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00004197
4198 // FIXME: Warn if a non-POD type is passed in.
4199
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004200 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004201}
4202
Douglas Gregorad4b3792008-11-29 04:51:27 +00004203Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4204 // The type of __null will be int or long, depending on the size of
4205 // pointers on the target.
4206 QualType Ty;
4207 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4208 Ty = Context.IntTy;
4209 else
4210 Ty = Context.LongTy;
4211
4212 return new GNUNullExpr(Ty, TokenLoc);
4213}
4214
Chris Lattner005ed752008-01-04 18:04:52 +00004215bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4216 SourceLocation Loc,
4217 QualType DstType, QualType SrcType,
4218 Expr *SrcExpr, const char *Flavor) {
4219 // Decode the result (notice that AST's are still created for extensions).
4220 bool isInvalid = false;
4221 unsigned DiagKind;
4222 switch (ConvTy) {
4223 default: assert(0 && "Unknown conversion type");
4224 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004225 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004226 DiagKind = diag::ext_typecheck_convert_pointer_int;
4227 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004228 case IntToPointer:
4229 DiagKind = diag::ext_typecheck_convert_int_pointer;
4230 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004231 case IncompatiblePointer:
4232 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4233 break;
4234 case FunctionVoidPointer:
4235 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4236 break;
4237 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004238 // If the qualifiers lost were because we were applying the
4239 // (deprecated) C++ conversion from a string literal to a char*
4240 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4241 // Ideally, this check would be performed in
4242 // CheckPointerTypesForAssignment. However, that would require a
4243 // bit of refactoring (so that the second argument is an
4244 // expression, rather than a type), which should be done as part
4245 // of a larger effort to fix CheckPointerTypesForAssignment for
4246 // C++ semantics.
4247 if (getLangOptions().CPlusPlus &&
4248 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4249 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004250 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4251 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004252 case IntToBlockPointer:
4253 DiagKind = diag::err_int_to_block_pointer;
4254 break;
4255 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004256 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004257 break;
Steve Naroff19608432008-10-14 22:18:38 +00004258 case IncompatibleObjCQualifiedId:
4259 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4260 // it can give a more specific diagnostic.
4261 DiagKind = diag::warn_incompatible_qualified_id;
4262 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004263 case Incompatible:
4264 DiagKind = diag::err_typecheck_convert_incompatible;
4265 isInvalid = true;
4266 break;
4267 }
4268
Chris Lattner271d4c22008-11-24 05:29:24 +00004269 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4270 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004271 return isInvalid;
4272}
Anders Carlssond5201b92008-11-30 19:50:32 +00004273
4274bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4275{
4276 Expr::EvalResult EvalResult;
4277
4278 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4279 EvalResult.HasSideEffects) {
4280 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4281
4282 if (EvalResult.Diag) {
4283 // We only show the note if it's not the usual "invalid subexpression"
4284 // or if it's actually in a subexpression.
4285 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4286 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4287 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4288 }
4289
4290 return true;
4291 }
4292
4293 if (EvalResult.Diag) {
4294 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4295 E->getSourceRange();
4296
4297 // Print the reason it's not a constant.
4298 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4299 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4300 }
4301
4302 if (Result)
4303 *Result = EvalResult.Val.getInt();
4304 return false;
4305}