blob: bf2d7b1489a03df2f84d09f49dd5759244bf405a [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
Chris Lattner299b8842008-07-25 21:10:04 +000090/// UsualArithmeticConversions - Performs various conversions that are common to
91/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
92/// routine returns the first non-arithmetic type found. The client is
93/// responsible for emitting appropriate error diagnostics.
94/// FIXME: verify the conversion rules for "complex int" are consistent with
95/// GCC.
96QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
97 bool isCompAssign) {
98 if (!isCompAssign) {
99 UsualUnaryConversions(lhsExpr);
100 UsualUnaryConversions(rhsExpr);
101 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000102
Chris Lattner299b8842008-07-25 21:10:04 +0000103 // For conversion purposes, we ignore any qualifiers.
104 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000105 QualType lhs =
106 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
107 QualType rhs =
108 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000109
110 // If both types are identical, no conversion is needed.
111 if (lhs == rhs)
112 return lhs;
113
114 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
115 // The caller can deal with this (e.g. pointer + int).
116 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
117 return lhs;
118
119 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
120 if (!isCompAssign) {
121 ImpCastExprToType(lhsExpr, destType);
122 ImpCastExprToType(rhsExpr, destType);
123 }
124 return destType;
125}
126
127QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
128 // Perform the usual unary conversions. We do this early so that
129 // integral promotions to "int" can allow us to exit early, in the
130 // lhs == rhs check. Also, for conversion purposes, we ignore any
131 // qualifiers. For example, "const float" and "float" are
132 // equivalent.
Douglas Gregor3d4492e2008-11-13 20:12:29 +0000133 if (lhs->isPromotableIntegerType()) lhs = Context.IntTy;
134 else lhs = lhs.getUnqualifiedType();
135 if (rhs->isPromotableIntegerType()) rhs = Context.IntTy;
136 else rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000137
Chris Lattner299b8842008-07-25 21:10:04 +0000138 // If both types are identical, no conversion is needed.
139 if (lhs == rhs)
140 return lhs;
141
142 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
143 // The caller can deal with this (e.g. pointer + int).
144 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
145 return lhs;
146
147 // At this point, we have two different arithmetic types.
148
149 // Handle complex types first (C99 6.3.1.8p1).
150 if (lhs->isComplexType() || rhs->isComplexType()) {
151 // if we have an integer operand, the result is the complex type.
152 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
153 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000154 return lhs;
155 }
156 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
157 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000158 return rhs;
159 }
160 // This handles complex/complex, complex/float, or float/complex.
161 // When both operands are complex, the shorter operand is converted to the
162 // type of the longer, and that is the type of the result. This corresponds
163 // to what is done when combining two real floating-point operands.
164 // The fun begins when size promotion occur across type domains.
165 // From H&S 6.3.4: When one operand is complex and the other is a real
166 // floating-point type, the less precise type is converted, within it's
167 // real or complex domain, to the precision of the other type. For example,
168 // when combining a "long double" with a "double _Complex", the
169 // "double _Complex" is promoted to "long double _Complex".
170 int result = Context.getFloatingTypeOrder(lhs, rhs);
171
172 if (result > 0) { // The left side is bigger, convert rhs.
173 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000174 } else if (result < 0) { // The right side is bigger, convert lhs.
175 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000176 }
177 // At this point, lhs and rhs have the same rank/size. Now, make sure the
178 // domains match. This is a requirement for our implementation, C99
179 // does not require this promotion.
180 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
181 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000182 return rhs;
183 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000184 return lhs;
185 }
186 }
187 return lhs; // The domain/size match exactly.
188 }
189 // Now handle "real" floating types (i.e. float, double, long double).
190 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
191 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000192 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000193 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000194 return lhs;
195 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000196 if (rhs->isComplexIntegerType()) {
197 // convert rhs to the complex floating point type.
198 return Context.getComplexType(lhs);
199 }
200 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000201 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000202 return rhs;
203 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000204 if (lhs->isComplexIntegerType()) {
205 // convert lhs to the complex floating point type.
206 return Context.getComplexType(rhs);
207 }
Chris Lattner299b8842008-07-25 21:10:04 +0000208 // We have two real floating types, float/complex combos were handled above.
209 // Convert the smaller operand to the bigger result.
210 int result = Context.getFloatingTypeOrder(lhs, rhs);
211
212 if (result > 0) { // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000213 return lhs;
214 }
215 if (result < 0) { // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000216 return rhs;
217 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000218 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
Chris Lattner299b8842008-07-25 21:10:04 +0000219 }
220 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
221 // Handle GCC complex int extension.
222 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
223 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
224
225 if (lhsComplexInt && rhsComplexInt) {
226 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
227 rhsComplexInt->getElementType()) >= 0) {
228 // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000229 return lhs;
230 }
Chris Lattner299b8842008-07-25 21:10:04 +0000231 return rhs;
232 } else if (lhsComplexInt && rhs->isIntegerType()) {
233 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000234 return lhs;
235 } else if (rhsComplexInt && lhs->isIntegerType()) {
236 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000237 return rhs;
238 }
239 }
240 // Finally, we have two differing integer types.
241 // The rules for this case are in C99 6.3.1.8
242 int compare = Context.getIntegerTypeOrder(lhs, rhs);
243 bool lhsSigned = lhs->isSignedIntegerType(),
244 rhsSigned = rhs->isSignedIntegerType();
245 QualType destType;
246 if (lhsSigned == rhsSigned) {
247 // Same signedness; use the higher-ranked type
248 destType = compare >= 0 ? lhs : rhs;
249 } else if (compare != (lhsSigned ? 1 : -1)) {
250 // The unsigned type has greater than or equal rank to the
251 // signed type, so use the unsigned type
252 destType = lhsSigned ? rhs : lhs;
253 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
254 // The two types are different widths; if we are here, that
255 // means the signed type is larger than the unsigned type, so
256 // use the signed type.
257 destType = lhsSigned ? lhs : rhs;
258 } else {
259 // The signed type is higher-ranked than the unsigned type,
260 // but isn't actually any bigger (like unsigned int and long
261 // on most 32-bit systems). Use the unsigned type corresponding
262 // to the signed type.
263 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
264 }
Chris Lattner299b8842008-07-25 21:10:04 +0000265 return destType;
266}
267
268//===----------------------------------------------------------------------===//
269// Semantic Analysis for various Expression Types
270//===----------------------------------------------------------------------===//
271
272
Steve Naroff87d58b42007-09-16 03:34:24 +0000273/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000274/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
275/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
276/// multiple tokens. However, the common case is that StringToks points to one
277/// string.
278///
279Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000280Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000281 assert(NumStringToks && "Must have at least one string!");
282
283 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
284 if (Literal.hadError)
285 return ExprResult(true);
286
287 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
288 for (unsigned i = 0; i != NumStringToks; ++i)
289 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000290
291 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000292 if (Literal.Pascal && Literal.GetStringLength() > 256)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000293 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long)
294 << SourceRange(StringToks[0].getLocation(),
295 StringToks[NumStringToks-1].getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000296
Chris Lattnera6dcce32008-02-11 00:02:17 +0000297 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000298 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000299 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000300
301 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
302 if (getLangOptions().CPlusPlus)
303 StrTy.addConst();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000304
305 // Get an array type for the string, according to C99 6.4.5. This includes
306 // the nul terminator character as well as the string length for pascal
307 // strings.
308 StrTy = Context.getConstantArrayType(StrTy,
309 llvm::APInt(32, Literal.GetStringLength()+1),
310 ArrayType::Normal, 0);
311
Chris Lattner4b009652007-07-25 00:24:17 +0000312 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
313 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000314 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000315 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000316 StringToks[NumStringToks-1].getLocation());
317}
318
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000319/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
320/// CurBlock to VD should cause it to be snapshotted (as we do for auto
321/// variables defined outside the block) or false if this is not needed (e.g.
322/// for values inside the block or for globals).
323///
324/// FIXME: This will create BlockDeclRefExprs for global variables,
325/// function references, etc which is suboptimal :) and breaks
326/// things like "integer constant expression" tests.
327static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
328 ValueDecl *VD) {
329 // If the value is defined inside the block, we couldn't snapshot it even if
330 // we wanted to.
331 if (CurBlock->TheDecl == VD->getDeclContext())
332 return false;
333
334 // If this is an enum constant or function, it is constant, don't snapshot.
335 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
336 return false;
337
338 // If this is a reference to an extern, static, or global variable, no need to
339 // snapshot it.
340 // FIXME: What about 'const' variables in C++?
341 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
342 return Var->hasLocalStorage();
343
344 return true;
345}
346
347
348
Steve Naroff0acc9c92007-09-15 18:49:24 +0000349/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000350/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000351/// identifier is used in a function call context.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000352/// LookupCtx is only used for a C++ qualified-id (foo::bar) to indicate the
353/// class or namespace that the identifier must be a member of.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000354Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000355 IdentifierInfo &II,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000356 bool HasTrailingLParen,
357 const CXXScopeSpec *SS) {
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000358 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS);
359}
360
Douglas Gregor566782a2009-01-06 05:10:23 +0000361/// BuildDeclRefExpr - Build either a DeclRefExpr or a
362/// QualifiedDeclRefExpr based on whether or not SS is a
363/// nested-name-specifier.
364DeclRefExpr *Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
365 bool TypeDependent, bool ValueDependent,
366 const CXXScopeSpec *SS) {
367 if (SS && !SS->isEmpty())
368 return new QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent,
369 SS->getRange().getBegin());
370 else
371 return new DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
372}
373
Douglas Gregor723d3332009-01-07 00:43:41 +0000374/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
375/// variable corresponding to the anonymous union or struct whose type
376/// is Record.
377static ScopedDecl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
378 assert(Record->isAnonymousStructOrUnion() &&
379 "Record must be an anonymous struct or union!");
380
381 // FIXME: Once ScopedDecls are directly linked together, this will
382 // be an O(1) operation rather than a slow walk through DeclContext's
383 // vector (which itself will be eliminated). DeclGroups might make
384 // this even better.
385 DeclContext *Ctx = Record->getDeclContext();
386 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
387 DEnd = Ctx->decls_end();
388 D != DEnd; ++D) {
389 if (*D == Record) {
390 // The object for the anonymous struct/union directly
391 // follows its type in the list of declarations.
392 ++D;
393 assert(D != DEnd && "Missing object for anonymous record");
394 assert(!cast<ScopedDecl>(*D)->getDeclName() && "Decl should be unnamed");
395 return *D;
396 }
397 }
398
399 assert(false && "Missing object for anonymous record");
400 return 0;
401}
402
403Sema::ExprResult
404Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
405 FieldDecl *Field,
406 Expr *BaseObjectExpr,
407 SourceLocation OpLoc) {
408 assert(Field->getDeclContext()->isRecord() &&
409 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
410 && "Field must be stored inside an anonymous struct or union");
411
412 // Construct the sequence of field member references
413 // we'll have to perform to get to the field in the anonymous
414 // union/struct. The list of members is built from the field
415 // outward, so traverse it backwards to go from an object in
416 // the current context to the field we found.
417 llvm::SmallVector<FieldDecl *, 4> AnonFields;
418 AnonFields.push_back(Field);
419 VarDecl *BaseObject = 0;
420 DeclContext *Ctx = Field->getDeclContext();
421 do {
422 RecordDecl *Record = cast<RecordDecl>(Ctx);
423 ScopedDecl *AnonObject = getObjectForAnonymousRecordDecl(Record);
424 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
425 AnonFields.push_back(AnonField);
426 else {
427 BaseObject = cast<VarDecl>(AnonObject);
428 break;
429 }
430 Ctx = Ctx->getParent();
431 } while (Ctx->isRecord() &&
432 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
433
434 // Build the expression that refers to the base object, from
435 // which we will build a sequence of member references to each
436 // of the anonymous union objects and, eventually, the field we
437 // found via name lookup.
438 bool BaseObjectIsPointer = false;
439 unsigned ExtraQuals = 0;
440 if (BaseObject) {
441 // BaseObject is an anonymous struct/union variable (and is,
442 // therefore, not part of another non-anonymous record).
443 delete BaseObjectExpr;
444
445 BaseObjectExpr = new DeclRefExpr(BaseObject, BaseObject->getType(),
446 SourceLocation());
447 ExtraQuals
448 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
449 } else if (BaseObjectExpr) {
450 // The caller provided the base object expression. Determine
451 // whether its a pointer and whether it adds any qualifiers to the
452 // anonymous struct/union fields we're looking into.
453 QualType ObjectType = BaseObjectExpr->getType();
454 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
455 BaseObjectIsPointer = true;
456 ObjectType = ObjectPtr->getPointeeType();
457 }
458 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
459 } else {
460 // We've found a member of an anonymous struct/union that is
461 // inside a non-anonymous struct/union, so in a well-formed
462 // program our base object expression is "this".
463 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
464 if (!MD->isStatic()) {
465 QualType AnonFieldType
466 = Context.getTagDeclType(
467 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
468 QualType ThisType = Context.getTagDeclType(MD->getParent());
469 if ((Context.getCanonicalType(AnonFieldType)
470 == Context.getCanonicalType(ThisType)) ||
471 IsDerivedFrom(ThisType, AnonFieldType)) {
472 // Our base object expression is "this".
473 BaseObjectExpr = new CXXThisExpr(SourceLocation(),
474 MD->getThisType(Context));
475 BaseObjectIsPointer = true;
476 }
477 } else {
478 return Diag(Loc, diag::err_invalid_member_use_in_static_method)
479 << Field->getDeclName();
480 }
481 ExtraQuals = MD->getTypeQualifiers();
482 }
483
484 if (!BaseObjectExpr)
485 return Diag(Loc, diag::err_invalid_non_static_member_use)
486 << Field->getDeclName();
487 }
488
489 // Build the implicit member references to the field of the
490 // anonymous struct/union.
491 Expr *Result = BaseObjectExpr;
492 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
493 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
494 FI != FIEnd; ++FI) {
495 QualType MemberType = (*FI)->getType();
496 if (!(*FI)->isMutable()) {
497 unsigned combinedQualifiers
498 = MemberType.getCVRQualifiers() | ExtraQuals;
499 MemberType = MemberType.getQualifiedType(combinedQualifiers);
500 }
501 Result = new MemberExpr(Result, BaseObjectIsPointer, *FI,
502 OpLoc, MemberType);
503 BaseObjectIsPointer = false;
504 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
505 OpLoc = SourceLocation();
506 }
507
508 return Result;
509}
510
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000511/// ActOnDeclarationNameExpr - The parser has read some kind of name
512/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
513/// performs lookup on that name and returns an expression that refers
514/// to that name. This routine isn't directly called from the parser,
515/// because the parser doesn't know about DeclarationName. Rather,
516/// this routine is called by ActOnIdentifierExpr,
517/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
518/// which form the DeclarationName from the corresponding syntactic
519/// forms.
520///
521/// HasTrailingLParen indicates whether this identifier is used in a
522/// function call context. LookupCtx is only used for a C++
523/// qualified-id (foo::bar) to indicate the class or namespace that
524/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000525///
526/// If ForceResolution is true, then we will attempt to resolve the
527/// name even if it looks like a dependent name. This option is off by
528/// default.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000529Sema::ExprResult Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
530 DeclarationName Name,
531 bool HasTrailingLParen,
Douglas Gregora133e262008-12-06 00:22:45 +0000532 const CXXScopeSpec *SS,
533 bool ForceResolution) {
534 if (S->getTemplateParamParent() && Name.getAsIdentifierInfo() &&
535 HasTrailingLParen && !SS && !ForceResolution) {
536 // We've seen something of the form
537 // identifier(
538 // and we are in a template, so it is likely that 's' is a
539 // dependent name. However, we won't know until we've parsed all
540 // of the call arguments. So, build a CXXDependentNameExpr node
541 // to represent this name. Then, if it turns out that none of the
542 // arguments are type-dependent, we'll force the resolution of the
543 // dependent name at that point.
544 return new CXXDependentNameExpr(Name.getAsIdentifierInfo(),
545 Context.DependentTy, Loc);
546 }
547
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000548 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000549 Decl *D = 0;
550 LookupResult Lookup;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000551 if (SS && !SS->isEmpty()) {
552 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
553 if (DC == 0)
554 return true;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000555 Lookup = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000556 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000557 Lookup = LookupDecl(Name, Decl::IDNS_Ordinary, S);
558
559 if (Lookup.isAmbiguous())
560 return DiagnoseAmbiguousLookup(Lookup, Name, Loc,
561 SS && SS->isSet()? SS->getRange()
562 : SourceRange());
563 else
564 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000565
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000566 // If this reference is in an Objective-C method, then ivar lookup happens as
567 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000568 IdentifierInfo *II = Name.getAsIdentifierInfo();
569 if (II && getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000570 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000571 // There are two cases to handle here. 1) scoped lookup could have failed,
572 // in which case we should look for an ivar. 2) scoped lookup could have
573 // found a decl, but that decl is outside the current method (i.e. a global
574 // variable). In these two cases, we do a lookup for an ivar with this
575 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000576 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000577 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000578 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000579 // FIXME: This should use a new expr for a direct reference, don't turn
580 // this into Self->ivar, just return a BareIVarExpr or something.
581 IdentifierInfo &II = Context.Idents.get("self");
582 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000583 ObjCIvarRefExpr *MRef= new ObjCIvarRefExpr(IV, IV->getType(), Loc,
584 static_cast<Expr*>(SelfExpr.Val), true, true);
585 Context.setFieldDecl(IFace, IV, MRef);
586 return MRef;
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000587 }
588 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000589 // Needed to implement property "super.method" notation.
Chris Lattner87fada82008-11-20 05:35:30 +0000590 if (SD == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000591 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000592 getCurMethodDecl()->getClassInterface()));
Douglas Gregord8606632008-11-04 14:56:14 +0000593 return new ObjCSuperExpr(Loc, T);
Steve Naroff6f786252008-06-02 23:03:37 +0000594 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000595 }
Chris Lattner4b009652007-07-25 00:24:17 +0000596 if (D == 0) {
597 // Otherwise, this could be an implicitly declared function reference (legal
598 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000599 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000600 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000601 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000602 else {
603 // If this name wasn't predeclared and if this is not a function call,
604 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000605 if (SS && !SS->isEmpty())
Chris Lattner77d52da2008-11-20 06:06:08 +0000606 return Diag(Loc, diag::err_typecheck_no_member)
Chris Lattnerb1753422008-11-23 21:45:46 +0000607 << Name << SS->getRange();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000608 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
609 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000610 return Diag(Loc, diag::err_undeclared_use) << Name.getAsString();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000611 else
Chris Lattnerb1753422008-11-23 21:45:46 +0000612 return Diag(Loc, diag::err_undeclared_var_use) << Name;
Chris Lattner4b009652007-07-25 00:24:17 +0000613 }
614 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000615
616 // We may have found a field within an anonymous union or struct
617 // (C++ [class.union]).
618 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
619 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
620 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000621
Douglas Gregor3257fb52008-12-22 05:46:06 +0000622 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
623 if (!MD->isStatic()) {
624 // C++ [class.mfct.nonstatic]p2:
625 // [...] if name lookup (3.4.1) resolves the name in the
626 // id-expression to a nonstatic nontype member of class X or of
627 // a base class of X, the id-expression is transformed into a
628 // class member access expression (5.2.5) using (*this) (9.3.2)
629 // as the postfix-expression to the left of the '.' operator.
630 DeclContext *Ctx = 0;
631 QualType MemberType;
632 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
633 Ctx = FD->getDeclContext();
634 MemberType = FD->getType();
635
636 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
637 MemberType = RefType->getPointeeType();
638 else if (!FD->isMutable()) {
639 unsigned combinedQualifiers
640 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
641 MemberType = MemberType.getQualifiedType(combinedQualifiers);
642 }
643 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
644 if (!Method->isStatic()) {
645 Ctx = Method->getParent();
646 MemberType = Method->getType();
647 }
648 } else if (OverloadedFunctionDecl *Ovl
649 = dyn_cast<OverloadedFunctionDecl>(D)) {
650 for (OverloadedFunctionDecl::function_iterator
651 Func = Ovl->function_begin(),
652 FuncEnd = Ovl->function_end();
653 Func != FuncEnd; ++Func) {
654 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
655 if (!DMethod->isStatic()) {
656 Ctx = Ovl->getDeclContext();
657 MemberType = Context.OverloadTy;
658 break;
659 }
660 }
661 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000662
663 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000664 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
665 QualType ThisType = Context.getTagDeclType(MD->getParent());
666 if ((Context.getCanonicalType(CtxType)
667 == Context.getCanonicalType(ThisType)) ||
668 IsDerivedFrom(ThisType, CtxType)) {
669 // Build the implicit member access expression.
670 Expr *This = new CXXThisExpr(SourceLocation(),
671 MD->getThisType(Context));
672 return new MemberExpr(This, true, cast<NamedDecl>(D),
673 SourceLocation(), MemberType);
674 }
675 }
676 }
677 }
678
Douglas Gregor8acb7272008-12-11 16:49:14 +0000679 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000680 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
681 if (MD->isStatic())
682 // "invalid use of member 'x' in static member function"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000683 return Diag(Loc, diag::err_invalid_member_use_in_static_method)
Chris Lattner271d4c22008-11-24 05:29:24 +0000684 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000685 }
686
Douglas Gregor3257fb52008-12-22 05:46:06 +0000687 // Any other ways we could have found the field in a well-formed
688 // program would have been turned into implicit member expressions
689 // above.
Chris Lattner271d4c22008-11-24 05:29:24 +0000690 return Diag(Loc, diag::err_invalid_non_static_member_use)
691 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000692 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000693
Chris Lattner4b009652007-07-25 00:24:17 +0000694 if (isa<TypedefDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000695 return Diag(Loc, diag::err_unexpected_typedef) << Name;
Ted Kremenek42730c52008-01-07 19:49:32 +0000696 if (isa<ObjCInterfaceDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000697 return Diag(Loc, diag::err_unexpected_interface) << Name;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000698 if (isa<NamespaceDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000699 return Diag(Loc, diag::err_unexpected_namespace) << Name;
Chris Lattner4b009652007-07-25 00:24:17 +0000700
Steve Naroffd6163f32008-09-05 22:11:13 +0000701 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000702 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Douglas Gregor566782a2009-01-06 05:10:23 +0000703 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc, false, false, SS);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000704
Steve Naroffd6163f32008-09-05 22:11:13 +0000705 ValueDecl *VD = cast<ValueDecl>(D);
706
707 // check if referencing an identifier with __attribute__((deprecated)).
708 if (VD->getAttr<DeprecatedAttr>())
Chris Lattner271d4c22008-11-24 05:29:24 +0000709 Diag(Loc, diag::warn_deprecated) << VD->getDeclName();
Douglas Gregor48840c72008-12-10 23:01:14 +0000710
711 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
712 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
713 Scope *CheckS = S;
714 while (CheckS) {
715 if (CheckS->isWithinElse() &&
716 CheckS->getControlParent()->isDeclScope(Var)) {
717 if (Var->getType()->isBooleanType())
718 Diag(Loc, diag::warn_value_always_false) << Var->getDeclName();
719 else
720 Diag(Loc, diag::warn_value_always_zero) << Var->getDeclName();
721 break;
722 }
723
724 // Move up one more control parent to check again.
725 CheckS = CheckS->getControlParent();
726 if (CheckS)
727 CheckS = CheckS->getParent();
728 }
729 }
730 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000731
732 // Only create DeclRefExpr's for valid Decl's.
733 if (VD->isInvalidDecl())
734 return true;
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000735
736 // If the identifier reference is inside a block, and it refers to a value
737 // that is outside the block, create a BlockDeclRefExpr instead of a
738 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
739 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000740 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000741 // We do not do this for things like enum constants, global variables, etc,
742 // as they do not get snapshotted.
743 //
744 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000745 // The BlocksAttr indicates the variable is bound by-reference.
746 if (VD->getAttr<BlocksAttr>())
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000747 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
748 Loc, true);
Steve Naroff52059382008-10-10 01:28:17 +0000749
750 // Variable will be bound by-copy, make it const within the closure.
751 VD->getType().addConst();
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000752 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
753 Loc, false);
Steve Naroff52059382008-10-10 01:28:17 +0000754 }
755 // If this reference is not in a block or if the referenced variable is
756 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000757
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000758 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000759 bool ValueDependent = false;
760 if (getLangOptions().CPlusPlus) {
761 // C++ [temp.dep.expr]p3:
762 // An id-expression is type-dependent if it contains:
763 // - an identifier that was declared with a dependent type,
764 if (VD->getType()->isDependentType())
765 TypeDependent = true;
766 // - FIXME: a template-id that is dependent,
767 // - a conversion-function-id that specifies a dependent type,
768 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
769 Name.getCXXNameType()->isDependentType())
770 TypeDependent = true;
771 // - a nested-name-specifier that contains a class-name that
772 // names a dependent type.
773 else if (SS && !SS->isEmpty()) {
774 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
775 DC; DC = DC->getParent()) {
776 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000777 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000778 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
779 if (Context.getTypeDeclType(Record)->isDependentType()) {
780 TypeDependent = true;
781 break;
782 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000783 }
784 }
785 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000786
Douglas Gregora5d84612008-12-10 20:57:37 +0000787 // C++ [temp.dep.constexpr]p2:
788 //
789 // An identifier is value-dependent if it is:
790 // - a name declared with a dependent type,
791 if (TypeDependent)
792 ValueDependent = true;
793 // - the name of a non-type template parameter,
794 else if (isa<NonTypeTemplateParmDecl>(VD))
795 ValueDependent = true;
796 // - a constant with integral or enumeration type and is
797 // initialized with an expression that is value-dependent
798 // (FIXME!).
799 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000800
Douglas Gregor566782a2009-01-06 05:10:23 +0000801 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
802 TypeDependent, ValueDependent, SS);
Chris Lattner4b009652007-07-25 00:24:17 +0000803}
804
Chris Lattner69909292008-08-10 01:53:14 +0000805Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000806 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000807 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000808
809 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000810 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000811 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
812 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
813 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000814 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000815
Chris Lattner7e637512008-01-12 08:14:25 +0000816 // Pre-defined identifiers are of type char[x], where x is the length of the
817 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000818 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000819 if (FunctionDecl *FD = getCurFunctionDecl())
820 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000821 else if (ObjCMethodDecl *MD = getCurMethodDecl())
822 Length = MD->getSynthesizedMethodSize();
823 else {
824 Diag(Loc, diag::ext_predef_outside_function);
825 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
826 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
827 }
828
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000829
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000830 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000831 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000832 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000833 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000834}
835
Steve Naroff87d58b42007-09-16 03:34:24 +0000836Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000837 llvm::SmallString<16> CharBuffer;
838 CharBuffer.resize(Tok.getLength());
839 const char *ThisTokBegin = &CharBuffer[0];
840 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
841
842 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
843 Tok.getLocation(), PP);
844 if (Literal.hadError())
845 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000846
847 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
848
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000849 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
850 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000851}
852
Steve Naroff87d58b42007-09-16 03:34:24 +0000853Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattnerfd5f1432009-01-16 07:10:29 +0000854 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +0000855 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
856 if (Tok.getLength() == 1) {
Chris Lattnerfd5f1432009-01-16 07:10:29 +0000857 const char Val = PP.getSpelledCharacterAt(Tok.getLocation());
858 unsigned IntSize = Context.Target.getIntWidth();
859 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000860 Context.IntTy,
861 Tok.getLocation()));
862 }
Ted Kremenekdbde2282009-01-13 23:19:12 +0000863
Chris Lattner4b009652007-07-25 00:24:17 +0000864 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000865 // Add padding so that NumericLiteralParser can overread by one character.
866 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000867 const char *ThisTokBegin = &IntegerBuffer[0];
868
869 // Get the spelling of the token, which eliminates trigraphs, etc.
870 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner2e6b4bf2008-09-30 20:51:14 +0000871
Chris Lattner4b009652007-07-25 00:24:17 +0000872 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
873 Tok.getLocation(), PP);
874 if (Literal.hadError)
875 return ExprResult(true);
876
Chris Lattner1de66eb2007-08-26 03:42:43 +0000877 Expr *Res;
878
879 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000880 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000881 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000882 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000883 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000884 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000885 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000886 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000887
888 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
889
Ted Kremenekddedbe22007-11-29 00:56:49 +0000890 // isExact will be set by GetFloatValue().
891 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000892 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000893 Ty, Tok.getLocation());
894
Chris Lattner1de66eb2007-08-26 03:42:43 +0000895 } else if (!Literal.isIntegerLiteral()) {
896 return ExprResult(true);
897 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000898 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000899
Neil Booth7421e9c2007-08-29 22:00:19 +0000900 // long long is a C99 feature.
901 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000902 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000903 Diag(Tok.getLocation(), diag::ext_longlong);
904
Chris Lattner4b009652007-07-25 00:24:17 +0000905 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000906 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000907
908 if (Literal.GetIntegerValue(ResultVal)) {
909 // If this value didn't fit into uintmax_t, warn and force to ull.
910 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000911 Ty = Context.UnsignedLongLongTy;
912 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000913 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000914 } else {
915 // If this value fits into a ULL, try to figure out what else it fits into
916 // according to the rules of C99 6.4.4.1p5.
917
918 // Octal, Hexadecimal, and integers with a U suffix are allowed to
919 // be an unsigned int.
920 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
921
922 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000923 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000924 if (!Literal.isLong && !Literal.isLongLong) {
925 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000926 unsigned IntSize = Context.Target.getIntWidth();
927
Chris Lattner4b009652007-07-25 00:24:17 +0000928 // Does it fit in a unsigned int?
929 if (ResultVal.isIntN(IntSize)) {
930 // Does it fit in a signed int?
931 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000932 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000933 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000934 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000935 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000936 }
Chris Lattner4b009652007-07-25 00:24:17 +0000937 }
938
939 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000940 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000941 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000942
943 // Does it fit in a unsigned long?
944 if (ResultVal.isIntN(LongSize)) {
945 // Does it fit in a signed long?
946 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000947 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000948 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000949 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000950 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000951 }
Chris Lattner4b009652007-07-25 00:24:17 +0000952 }
953
954 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000955 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000956 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000957
958 // Does it fit in a unsigned long long?
959 if (ResultVal.isIntN(LongLongSize)) {
960 // Does it fit in a signed long long?
961 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000962 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000963 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000964 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000965 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000966 }
967 }
968
969 // If we still couldn't decide a type, we probably have something that
970 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000971 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000972 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000973 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000974 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000975 }
Chris Lattnere4068872008-05-09 05:59:00 +0000976
977 if (ResultVal.getBitWidth() != Width)
978 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000979 }
980
Chris Lattner48d7f382008-04-02 04:24:33 +0000981 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000982 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000983
984 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
985 if (Literal.isImaginary)
986 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
987
988 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000989}
990
Steve Naroff87d58b42007-09-16 03:34:24 +0000991Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000992 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000993 Expr *E = (Expr *)Val;
994 assert((E != 0) && "ActOnParenExpr() missing expr");
995 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000996}
997
998/// The UsualUnaryConversions() function is *not* called by this routine.
999/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001000bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1001 SourceLocation OpLoc,
1002 const SourceRange &ExprRange,
1003 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +00001004 // C99 6.5.3.4p1:
1005 if (isa<FunctionType>(exprType) && isSizeof)
1006 // alignof(function) is allowed.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001007 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
Chris Lattner4b009652007-07-25 00:24:17 +00001008 else if (exprType->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001009 Diag(OpLoc, diag::ext_sizeof_void_type)
1010 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
1011 else if (exprType->isIncompleteType())
1012 return Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
1013 diag::err_alignof_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001014 << exprType << ExprRange;
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001015
1016 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001017}
1018
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001019/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1020/// the same for @c alignof and @c __alignof
1021/// Note that the ArgRange is invalid if isType is false.
1022Action::ExprResult
1023Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1024 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001025 // If error parsing type, ignore.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001026 if (TyOrEx == 0) return true;
Chris Lattner4b009652007-07-25 00:24:17 +00001027
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001028 QualType ArgTy;
1029 SourceRange Range;
1030 if (isType) {
1031 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1032 Range = ArgRange;
1033 } else {
1034 // Get the end location.
1035 Expr *ArgEx = (Expr *)TyOrEx;
1036 Range = ArgEx->getSourceRange();
1037 ArgTy = ArgEx->getType();
1038 }
1039
1040 // Verify that the operand is valid.
1041 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Chris Lattner4b009652007-07-25 00:24:17 +00001042 return true;
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001043
1044 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1045 return new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, Context.getSizeType(),
1046 OpLoc, Range.getEnd());
Chris Lattner4b009652007-07-25 00:24:17 +00001047}
1048
Chris Lattner5110ad52007-08-24 21:41:10 +00001049QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +00001050 DefaultFunctionArrayConversion(V);
1051
Chris Lattnera16e42d2007-08-26 05:39:26 +00001052 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001053 if (const ComplexType *CT = V->getType()->getAsComplexType())
1054 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001055
1056 // Otherwise they pass through real integer and floating point types here.
1057 if (V->getType()->isArithmeticType())
1058 return V->getType();
1059
1060 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +00001061 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001062 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001063}
1064
1065
Chris Lattner4b009652007-07-25 00:24:17 +00001066
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001067Action::ExprResult Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001068 tok::TokenKind Kind,
1069 ExprTy *Input) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001070 Expr *Arg = (Expr *)Input;
1071
Chris Lattner4b009652007-07-25 00:24:17 +00001072 UnaryOperator::Opcode Opc;
1073 switch (Kind) {
1074 default: assert(0 && "Unknown unary op!");
1075 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1076 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1077 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001078
1079 if (getLangOptions().CPlusPlus &&
1080 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1081 // Which overloaded operator?
1082 OverloadedOperatorKind OverOp =
1083 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1084
1085 // C++ [over.inc]p1:
1086 //
1087 // [...] If the function is a member function with one
1088 // parameter (which shall be of type int) or a non-member
1089 // function with two parameters (the second of which shall be
1090 // of type int), it defines the postfix increment operator ++
1091 // for objects of that type. When the postfix increment is
1092 // called as a result of using the ++ operator, the int
1093 // argument will have value zero.
1094 Expr *Args[2] = {
1095 Arg,
1096 new IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1097 /*isSigned=*/true),
1098 Context.IntTy, SourceLocation())
1099 };
1100
1101 // Build the candidate set for overloading
1102 OverloadCandidateSet CandidateSet;
1103 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
1104
1105 // Perform overload resolution.
1106 OverloadCandidateSet::iterator Best;
1107 switch (BestViableFunction(CandidateSet, Best)) {
1108 case OR_Success: {
1109 // We found a built-in operator or an overloaded operator.
1110 FunctionDecl *FnDecl = Best->Function;
1111
1112 if (FnDecl) {
1113 // We matched an overloaded operator. Build a call to that
1114 // operator.
1115
1116 // Convert the arguments.
1117 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1118 if (PerformObjectArgumentInitialization(Arg, Method))
1119 return true;
1120 } else {
1121 // Convert the arguments.
1122 if (PerformCopyInitialization(Arg,
1123 FnDecl->getParamDecl(0)->getType(),
1124 "passing"))
1125 return true;
1126 }
1127
1128 // Determine the result type
1129 QualType ResultTy
1130 = FnDecl->getType()->getAsFunctionType()->getResultType();
1131 ResultTy = ResultTy.getNonReferenceType();
1132
1133 // Build the actual expression node.
1134 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
1135 SourceLocation());
1136 UsualUnaryConversions(FnExpr);
1137
1138 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, OpLoc);
1139 } else {
1140 // We matched a built-in operator. Convert the arguments, then
1141 // break out so that we will build the appropriate built-in
1142 // operator node.
1143 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1144 "passing"))
1145 return true;
1146
1147 break;
1148 }
1149 }
1150
1151 case OR_No_Viable_Function:
1152 // No viable function; fall through to handling this as a
1153 // built-in operator, which will produce an error message for us.
1154 break;
1155
1156 case OR_Ambiguous:
1157 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1158 << UnaryOperator::getOpcodeStr(Opc)
1159 << Arg->getSourceRange();
1160 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1161 return true;
1162 }
1163
1164 // Either we found no viable overloaded operator or we matched a
1165 // built-in operator. In either case, fall through to trying to
1166 // build a built-in operation.
1167 }
1168
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001169 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1170 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001171 if (result.isNull())
1172 return true;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001173 return new UnaryOperator(Arg, Opc, result, OpLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001174}
1175
1176Action::ExprResult Sema::
Douglas Gregor80723c52008-11-19 17:17:41 +00001177ActOnArraySubscriptExpr(Scope *S, ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001178 ExprTy *Idx, SourceLocation RLoc) {
1179 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
1180
Douglas Gregor80723c52008-11-19 17:17:41 +00001181 if (getLangOptions().CPlusPlus &&
Eli Friedmane658bf52008-12-15 22:34:21 +00001182 (LHSExp->getType()->isRecordType() ||
1183 LHSExp->getType()->isEnumeralType() ||
1184 RHSExp->getType()->isRecordType() ||
1185 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001186 // Add the appropriate overloaded operators (C++ [over.match.oper])
1187 // to the candidate set.
1188 OverloadCandidateSet CandidateSet;
1189 Expr *Args[2] = { LHSExp, RHSExp };
1190 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
1191
1192 // Perform overload resolution.
1193 OverloadCandidateSet::iterator Best;
1194 switch (BestViableFunction(CandidateSet, Best)) {
1195 case OR_Success: {
1196 // We found a built-in operator or an overloaded operator.
1197 FunctionDecl *FnDecl = Best->Function;
1198
1199 if (FnDecl) {
1200 // We matched an overloaded operator. Build a call to that
1201 // operator.
1202
1203 // Convert the arguments.
1204 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1205 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1206 PerformCopyInitialization(RHSExp,
1207 FnDecl->getParamDecl(0)->getType(),
1208 "passing"))
1209 return true;
1210 } else {
1211 // Convert the arguments.
1212 if (PerformCopyInitialization(LHSExp,
1213 FnDecl->getParamDecl(0)->getType(),
1214 "passing") ||
1215 PerformCopyInitialization(RHSExp,
1216 FnDecl->getParamDecl(1)->getType(),
1217 "passing"))
1218 return true;
1219 }
1220
1221 // Determine the result type
1222 QualType ResultTy
1223 = FnDecl->getType()->getAsFunctionType()->getResultType();
1224 ResultTy = ResultTy.getNonReferenceType();
1225
1226 // Build the actual expression node.
1227 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
1228 SourceLocation());
1229 UsualUnaryConversions(FnExpr);
1230
1231 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, LLoc);
1232 } else {
1233 // We matched a built-in operator. Convert the arguments, then
1234 // break out so that we will build the appropriate built-in
1235 // operator node.
1236 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1237 "passing") ||
1238 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1239 "passing"))
1240 return true;
1241
1242 break;
1243 }
1244 }
1245
1246 case OR_No_Viable_Function:
1247 // No viable function; fall through to handling this as a
1248 // built-in operator, which will produce an error message for us.
1249 break;
1250
1251 case OR_Ambiguous:
1252 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1253 << "[]"
1254 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1255 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1256 return true;
1257 }
1258
1259 // Either we found no viable overloaded operator or we matched a
1260 // built-in operator. In either case, fall through to trying to
1261 // build a built-in operation.
1262 }
1263
Chris Lattner4b009652007-07-25 00:24:17 +00001264 // Perform default conversions.
1265 DefaultFunctionArrayConversion(LHSExp);
1266 DefaultFunctionArrayConversion(RHSExp);
1267
1268 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1269
1270 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001271 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001272 // in the subscript position. As a result, we need to derive the array base
1273 // and index from the expression types.
1274 Expr *BaseExpr, *IndexExpr;
1275 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001276 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001277 BaseExpr = LHSExp;
1278 IndexExpr = RHSExp;
1279 // FIXME: need to deal with const...
1280 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001281 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001282 // Handle the uncommon case of "123[Ptr]".
1283 BaseExpr = RHSExp;
1284 IndexExpr = LHSExp;
1285 // FIXME: need to deal with const...
1286 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001287 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1288 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001289 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +00001290
1291 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +00001292 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1293 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner8ba580c2008-11-19 05:08:23 +00001294 return Diag(LLoc, diag::err_ext_vector_component_access)
1295 << SourceRange(LLoc, RLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001296 // FIXME: need to deal with const...
1297 ResultType = VTy->getElementType();
1298 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001299 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value)
1300 << RHSExp->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001301 }
1302 // C99 6.5.2.1p1
1303 if (!IndexExpr->getType()->isIntegerType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001304 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript)
1305 << IndexExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001306
1307 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1308 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001309 // void (*)(int)) and pointers to incomplete types. Functions are not
1310 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001311 if (!ResultType->isObjectType())
1312 return Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001313 diag::err_typecheck_subscript_not_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001314 << BaseExpr->getType() << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001315
1316 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
1317}
1318
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001319QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001320CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001321 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001322 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001323
1324 // This flag determines whether or not the component is to be treated as a
1325 // special name, or a regular GLSL-style component access.
1326 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001327
1328 // The vector accessor can't exceed the number of elements.
1329 const char *compStr = CompName.getName();
1330 if (strlen(compStr) > vecType->getNumElements()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001331 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001332 << baseType << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001333 return QualType();
1334 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001335
1336 // Check that we've found one of the special components, or that the component
1337 // names must come from the same set.
1338 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1339 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
1340 SpecialComponent = true;
1341 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001342 do
1343 compStr++;
1344 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1345 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
1346 do
1347 compStr++;
1348 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
1349 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
1350 do
1351 compStr++;
1352 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
1353 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001354
Nate Begemanc8e51f82008-05-09 06:41:27 +00001355 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001356 // We didn't get to the end of the string. This means the component names
1357 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001358 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1359 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001360 return QualType();
1361 }
1362 // Each component accessor can't exceed the vector type.
1363 compStr = CompName.getName();
1364 while (*compStr) {
1365 if (vecType->isAccessorWithinNumElements(*compStr))
1366 compStr++;
1367 else
1368 break;
1369 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001370 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001371 // We didn't get to the end of the string. This means a component accessor
1372 // exceeds the number of elements in the vector.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001373 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001374 << baseType << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001375 return QualType();
1376 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001377
1378 // If we have a special component name, verify that the current vector length
1379 // is an even number, since all special component names return exactly half
1380 // the elements.
1381 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001382 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001383 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001384 return QualType();
1385 }
1386
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001387 // The component accessor looks fine - now we need to compute the actual type.
1388 // The vector type is implied by the component accessor. For example,
1389 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001390 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1391 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
Chris Lattner65cae292008-11-19 08:23:25 +00001392 : CompName.getLength();
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001393 if (CompSize == 1)
1394 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001395
Nate Begemanaf6ed502008-04-18 23:10:10 +00001396 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001397 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001398 // diagostics look bad. We want extended vector types to appear built-in.
1399 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1400 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1401 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001402 }
1403 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001404}
1405
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001406/// constructSetterName - Return the setter name for the given
1407/// identifier, i.e. "set" + Name where the initial character of Name
1408/// has been capitalized.
1409// FIXME: Merge with same routine in Parser. But where should this
1410// live?
1411static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1412 const IdentifierInfo *Name) {
1413 llvm::SmallString<100> SelectorName;
1414 SelectorName = "set";
1415 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1416 SelectorName[3] = toupper(SelectorName[3]);
1417 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1418}
1419
Chris Lattner4b009652007-07-25 00:24:17 +00001420Action::ExprResult Sema::
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001421ActOnMemberReferenceExpr(Scope *S, ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001422 tok::TokenKind OpKind, SourceLocation MemberLoc,
1423 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001424 Expr *BaseExpr = static_cast<Expr *>(Base);
1425 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001426
1427 // Perform default conversions.
1428 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +00001429
Steve Naroff2cb66382007-07-26 03:11:44 +00001430 QualType BaseType = BaseExpr->getType();
1431 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001432
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001433 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1434 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001435 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001436 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001437 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001438 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001439 return BuildOverloadedArrowExpr(S, BaseExpr, OpLoc, MemberLoc, Member);
Steve Naroff2cb66382007-07-26 03:11:44 +00001440 else
Chris Lattner8ba580c2008-11-19 05:08:23 +00001441 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001442 << BaseType << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001443 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001444
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001445 // Handle field access to simple records. This also handles access to fields
1446 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001447 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001448 RecordDecl *RDecl = RTy->getDecl();
1449 if (RTy->isIncompleteType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001450 return Diag(OpLoc, diag::err_typecheck_incomplete_tag)
Chris Lattner271d4c22008-11-24 05:29:24 +00001451 << RDecl->getDeclName() << BaseExpr->getSourceRange();
Steve Naroff2cb66382007-07-26 03:11:44 +00001452 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001453 // FIXME: Qualified name lookup for C++ is a bit more complicated
1454 // than this.
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001455 LookupResult Result
1456 = LookupQualifiedName(RDecl, DeclarationName(&Member),
1457 LookupCriteria(LookupCriteria::Member,
1458 /*RedeclarationOnly=*/false,
1459 getLangOptions().CPlusPlus));
1460
1461 Decl *MemberDecl = 0;
1462 if (!Result)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001463 return Diag(MemberLoc, diag::err_typecheck_no_member)
Chris Lattner65cae292008-11-19 08:23:25 +00001464 << &Member << BaseExpr->getSourceRange();
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001465 else if (Result.isAmbiguous())
1466 return DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1467 MemberLoc, BaseExpr->getSourceRange());
1468 else
1469 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001470
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001471 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001472 // We may have found a field within an anonymous union or struct
1473 // (C++ [class.union]).
1474 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
1475 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
1476 BaseExpr, OpLoc);
1477
Douglas Gregor82d44772008-12-20 23:49:58 +00001478 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1479 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001480 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001481 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1482 MemberType = Ref->getPointeeType();
1483 else {
1484 unsigned combinedQualifiers =
1485 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001486 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001487 combinedQualifiers &= ~QualType::Const;
1488 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1489 }
Eli Friedman76b49832008-02-06 22:48:16 +00001490
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001491 return new MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
Douglas Gregor82d44772008-12-20 23:49:58 +00001492 MemberLoc, MemberType);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001493 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001494 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Var, MemberLoc,
1495 Var->getType().getNonReferenceType());
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001496 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001497 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberFn, MemberLoc,
1498 MemberFn->getType());
1499 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001500 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001501 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl, MemberLoc,
1502 Context.OverloadTy);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001503 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001504 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Enum, MemberLoc,
1505 Enum->getType());
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001506 else if (isa<TypeDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001507 return Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1508 << DeclarationName(&Member) << int(OpKind == tok::arrow);
Eli Friedman76b49832008-02-06 22:48:16 +00001509
Douglas Gregor82d44772008-12-20 23:49:58 +00001510 // We found a declaration kind that we didn't expect. This is a
1511 // generic error message that tells the user that she can't refer
1512 // to this member with '.' or '->'.
1513 return Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1514 << DeclarationName(&Member) << int(OpKind == tok::arrow);
Chris Lattnera57cf472008-07-21 04:28:12 +00001515 }
1516
Chris Lattnere9d71612008-07-21 04:59:05 +00001517 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1518 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001519 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001520 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Fariborz Jahanianea944842008-12-18 17:29:46 +00001521 ObjCIvarRefExpr *MRef= new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc,
1522 BaseExpr,
1523 OpKind == tok::arrow);
1524 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
1525 return MRef;
Fariborz Jahanian09772392008-12-13 22:20:28 +00001526 }
Chris Lattner8ba580c2008-11-19 05:08:23 +00001527 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Chris Lattner271d4c22008-11-24 05:29:24 +00001528 << IFTy->getDecl()->getDeclName() << &Member
Chris Lattner8ba580c2008-11-19 05:08:23 +00001529 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001530 }
1531
Chris Lattnere9d71612008-07-21 04:59:05 +00001532 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1533 // pointer to a (potentially qualified) interface type.
1534 const PointerType *PTy;
1535 const ObjCInterfaceType *IFTy;
1536 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1537 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1538 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001539
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001540 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001541 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
1542 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1543
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001544 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001545 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1546 E = IFTy->qual_end(); I != E; ++I)
1547 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1548 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001549
1550 // If that failed, look for an "implicit" property by seeing if the nullary
1551 // selector is implemented.
1552
1553 // FIXME: The logic for looking up nullary and unary selectors should be
1554 // shared with the code in ActOnInstanceMessage.
1555
1556 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1557 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1558
1559 // If this reference is in an @implementation, check for 'private' methods.
1560 if (!Getter)
1561 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1562 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1563 if (ObjCImplementationDecl *ImpDecl =
1564 ObjCImplementations[ClassDecl->getIdentifier()])
1565 Getter = ImpDecl->getInstanceMethod(Sel);
1566
Steve Naroff04151f32008-10-22 19:16:27 +00001567 // Look through local category implementations associated with the class.
1568 if (!Getter) {
1569 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1570 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1571 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1572 }
1573 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001574 if (Getter) {
1575 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001576 // will look for the matching setter, in case it is needed.
1577 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1578 &Member);
1579 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1580 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1581 if (!Setter) {
1582 // If this reference is in an @implementation, also check for 'private'
1583 // methods.
1584 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1585 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1586 if (ObjCImplementationDecl *ImpDecl =
1587 ObjCImplementations[ClassDecl->getIdentifier()])
1588 Setter = ImpDecl->getInstanceMethod(SetterSel);
1589 }
1590 // Look through local category implementations associated with the class.
1591 if (!Setter) {
1592 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1593 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1594 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1595 }
1596 }
1597
1598 // FIXME: we must check that the setter has property type.
1599 return new ObjCKVCRefExpr(Getter, Getter->getResultType(), Setter,
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00001600 MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001601 }
Anders Carlsson96095fc2008-12-19 17:27:57 +00001602
1603 return Diag(MemberLoc, diag::err_property_not_found) <<
1604 &Member << BaseType;
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001605 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001606 // Handle properties on qualified "id" protocols.
1607 const ObjCQualifiedIdType *QIdTy;
1608 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1609 // Check protocols on qualified interfaces.
1610 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001611 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroffd1d44402008-10-20 22:53:06 +00001612 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1613 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001614 // Also must look for a getter name which uses property syntax.
1615 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1616 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1617 return new ObjCMessageExpr(BaseExpr, Sel, OMD->getResultType(), OMD,
1618 OpLoc, MemberLoc, NULL, 0);
1619 }
1620 }
Anders Carlsson96095fc2008-12-19 17:27:57 +00001621
1622 return Diag(MemberLoc, diag::err_property_not_found) <<
1623 &Member << BaseType;
Steve Naroffd1d44402008-10-20 22:53:06 +00001624 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001625 // Handle 'field access' to vectors, such as 'V.xx'.
1626 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1627 // Component access limited to variables (reject vec4.rg.g).
1628 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1629 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner8ba580c2008-11-19 05:08:23 +00001630 return Diag(MemberLoc, diag::err_ext_vector_component_access)
1631 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001632 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1633 if (ret.isNull())
1634 return true;
1635 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1636 }
1637
Chris Lattner8ba580c2008-11-19 05:08:23 +00001638 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001639 << BaseType << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001640}
1641
Douglas Gregor3257fb52008-12-22 05:46:06 +00001642/// ConvertArgumentsForCall - Converts the arguments specified in
1643/// Args/NumArgs to the parameter types of the function FDecl with
1644/// function prototype Proto. Call is the call expression itself, and
1645/// Fn is the function expression. For a C++ member function, this
1646/// routine does not attempt to convert the object argument. Returns
1647/// true if the call is ill-formed.
1648bool
1649Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1650 FunctionDecl *FDecl,
1651 const FunctionTypeProto *Proto,
1652 Expr **Args, unsigned NumArgs,
1653 SourceLocation RParenLoc) {
1654 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1655 // assignment, to the types of the corresponding parameter, ...
1656 unsigned NumArgsInProto = Proto->getNumArgs();
1657 unsigned NumArgsToCheck = NumArgs;
1658
1659 // If too few arguments are available (and we don't have default
1660 // arguments for the remaining parameters), don't make the call.
1661 if (NumArgs < NumArgsInProto) {
1662 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1663 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1664 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1665 // Use default arguments for missing arguments
1666 NumArgsToCheck = NumArgsInProto;
1667 Call->setNumArgs(NumArgsInProto);
1668 }
1669
1670 // If too many are passed and not variadic, error on the extras and drop
1671 // them.
1672 if (NumArgs > NumArgsInProto) {
1673 if (!Proto->isVariadic()) {
1674 Diag(Args[NumArgsInProto]->getLocStart(),
1675 diag::err_typecheck_call_too_many_args)
1676 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1677 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1678 Args[NumArgs-1]->getLocEnd());
1679 // This deletes the extra arguments.
1680 Call->setNumArgs(NumArgsInProto);
1681 }
1682 NumArgsToCheck = NumArgsInProto;
1683 }
1684
1685 // Continue to check argument types (even if we have too few/many args).
1686 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1687 QualType ProtoArgType = Proto->getArgType(i);
1688
1689 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001690 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001691 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001692
1693 // Pass the argument.
1694 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1695 return true;
1696 } else
1697 // We already type-checked the argument, so we know it works.
Douglas Gregor3257fb52008-12-22 05:46:06 +00001698 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
1699 QualType ArgType = Arg->getType();
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001700
Douglas Gregor3257fb52008-12-22 05:46:06 +00001701 Call->setArg(i, Arg);
1702 }
1703
1704 // If this is a variadic call, handle args passed through "...".
1705 if (Proto->isVariadic()) {
1706 // Promote the arguments (C99 6.5.2.2p7).
1707 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1708 Expr *Arg = Args[i];
Anders Carlssonfde627e2009-01-13 05:48:52 +00001709 if (!Arg->getType()->isPODType()) {
1710 int CallType = 0;
1711 if (Fn->getType()->isBlockPointerType())
1712 CallType = 1; // Block
1713 else if (isa<MemberExpr>(Fn))
1714 CallType = 2;
1715
1716 Diag(Arg->getLocStart(),
1717 diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
1718 Arg->getType() << CallType;
1719 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00001720 DefaultArgumentPromotion(Arg);
1721 Call->setArg(i, Arg);
1722 }
1723 }
1724
1725 return false;
1726}
1727
Steve Naroff87d58b42007-09-16 03:34:24 +00001728/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001729/// This provides the location of the left/right parens and a list of comma
1730/// locations.
Douglas Gregor3257fb52008-12-22 05:46:06 +00001731Action::ExprResult
1732Sema::ActOnCallExpr(Scope *S, ExprTy *fn, SourceLocation LParenLoc,
1733 ExprTy **args, unsigned NumArgs,
1734 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner4b009652007-07-25 00:24:17 +00001735 Expr *Fn = static_cast<Expr *>(fn);
1736 Expr **Args = reinterpret_cast<Expr**>(args);
1737 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001738 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001739 OverloadedFunctionDecl *Ovl = NULL;
1740
Douglas Gregora133e262008-12-06 00:22:45 +00001741 // Determine whether this is a dependent call inside a C++ template,
1742 // in which case we won't do any semantic analysis now.
1743 bool Dependent = false;
1744 if (Fn->isTypeDependent()) {
1745 if (CXXDependentNameExpr *FnName = dyn_cast<CXXDependentNameExpr>(Fn)) {
1746 if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1747 Dependent = true;
1748 else {
1749 // Resolve the CXXDependentNameExpr to an actual identifier;
1750 // it wasn't really a dependent name after all.
1751 ExprResult Resolved
1752 = ActOnDeclarationNameExpr(S, FnName->getLocation(), FnName->getName(),
1753 /*HasTrailingLParen=*/true,
1754 /*SS=*/0,
1755 /*ForceResolution=*/true);
1756 if (Resolved.isInvalid)
1757 return true;
1758 else {
1759 delete Fn;
1760 Fn = (Expr *)Resolved.Val;
1761 }
1762 }
1763 } else
1764 Dependent = true;
1765 } else
1766 Dependent = Expr::hasAnyTypeDependentArguments(Args, NumArgs);
1767
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001768 // FIXME: Will need to cache the results of name lookup (including
1769 // ADL) in Fn.
Douglas Gregora133e262008-12-06 00:22:45 +00001770 if (Dependent)
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001771 return new CallExpr(Fn, Args, NumArgs, Context.DependentTy, RParenLoc);
1772
Douglas Gregor3257fb52008-12-22 05:46:06 +00001773 // Determine whether this is a call to an object (C++ [over.call.object]).
1774 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
1775 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1776 CommaLocs, RParenLoc);
1777
1778 // Determine whether this is a call to a member function.
1779 if (getLangOptions().CPlusPlus) {
1780 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1781 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1782 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
1783 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1784 CommaLocs, RParenLoc);
1785 }
1786
Douglas Gregord2baafd2008-10-21 16:13:35 +00001787 // If we're directly calling a function or a set of overloaded
1788 // functions, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00001789 DeclRefExpr *DRExpr = NULL;
1790 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1791 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1792 else
1793 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1794
1795 if (DRExpr) {
1796 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1797 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
Douglas Gregord2baafd2008-10-21 16:13:35 +00001798 }
1799
Douglas Gregord2baafd2008-10-21 16:13:35 +00001800 if (Ovl) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001801 FDecl = ResolveOverloadedCallFn(Fn, Ovl, LParenLoc, Args, NumArgs, CommaLocs,
1802 RParenLoc);
1803 if (!FDecl)
Douglas Gregord2baafd2008-10-21 16:13:35 +00001804 return true;
1805
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001806 // Update Fn to refer to the actual function selected.
Douglas Gregor566782a2009-01-06 05:10:23 +00001807 Expr *NewFn = 0;
1808 if (QualifiedDeclRefExpr *QDRExpr = dyn_cast<QualifiedDeclRefExpr>(DRExpr))
1809 NewFn = new QualifiedDeclRefExpr(FDecl, FDecl->getType(),
1810 QDRExpr->getLocation(), false, false,
1811 QDRExpr->getSourceRange().getBegin());
1812 else
1813 NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1814 Fn->getSourceRange().getBegin());
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001815 Fn->Destroy(Context);
1816 Fn = NewFn;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001817 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001818
1819 // Promote the function operand.
1820 UsualUnaryConversions(Fn);
1821
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001822 // Make the call expr early, before semantic checks. This guarantees cleanup
1823 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +00001824 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001825 Context.BoolTy, RParenLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001826
Steve Naroffd6163f32008-09-05 22:11:13 +00001827 const FunctionType *FuncT;
1828 if (!Fn->getType()->isBlockPointerType()) {
1829 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1830 // have type pointer to function".
1831 const PointerType *PT = Fn->getType()->getAsPointerType();
1832 if (PT == 0)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001833 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001834 << Fn->getType() << Fn->getSourceRange();
Steve Naroffd6163f32008-09-05 22:11:13 +00001835 FuncT = PT->getPointeeType()->getAsFunctionType();
1836 } else { // This is a block call.
1837 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1838 getAsFunctionType();
1839 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001840 if (FuncT == 0)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001841 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001842 << Fn->getType() << Fn->getSourceRange();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001843
1844 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001845 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Chris Lattner4b009652007-07-25 00:24:17 +00001846
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001847 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001848 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
1849 RParenLoc))
1850 return true;
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001851 } else {
1852 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1853
Steve Naroffdb65e052007-08-28 23:30:39 +00001854 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001855 for (unsigned i = 0; i != NumArgs; i++) {
1856 Expr *Arg = Args[i];
1857 DefaultArgumentPromotion(Arg);
1858 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001859 }
Chris Lattner4b009652007-07-25 00:24:17 +00001860 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001861
Douglas Gregor3257fb52008-12-22 05:46:06 +00001862 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
1863 if (!Method->isStatic())
1864 return Diag(LParenLoc, diag::err_member_call_without_object)
1865 << Fn->getSourceRange();
1866
Chris Lattner2e64c072007-08-10 20:18:51 +00001867 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001868 if (FDecl)
1869 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001870
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001871 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001872}
1873
1874Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001875ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001876 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001877 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001878 QualType literalType = QualType::getFromOpaquePtr(Ty);
1879 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001880 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001881 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001882
Eli Friedman8c2173d2008-05-20 05:22:08 +00001883 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001884 if (literalType->isVariableArrayType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001885 return Diag(LParenLoc, diag::err_variable_object_no_init)
1886 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001887 } else if (literalType->isIncompleteType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001888 return Diag(LParenLoc, diag::err_typecheck_decl_incomplete_type)
Chris Lattner271d4c22008-11-24 05:29:24 +00001889 << literalType
Chris Lattner8ba580c2008-11-19 05:08:23 +00001890 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001891 }
1892
Douglas Gregor6428e762008-11-05 15:29:30 +00001893 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001894 DeclarationName(), /*FIXME:DirectInit=*/false))
Steve Naroff92590f92008-01-09 20:58:06 +00001895 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001896
Chris Lattnere5cb5862008-12-04 23:50:19 +00001897 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001898 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001899 if (CheckForConstantInitializer(literalExpr, literalType))
1900 return true;
1901 }
Chris Lattnerce236e72008-10-26 23:35:51 +00001902 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1903 isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001904}
1905
1906Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001907ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattnerce236e72008-10-26 23:35:51 +00001908 InitListDesignations &Designators,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001909 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001910 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001911
Steve Naroff0acc9c92007-09-15 18:49:24 +00001912 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001913 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001914
Chris Lattner71ca8c82008-10-26 23:43:26 +00001915 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1916 Designators.hasAnyDesignators());
Chris Lattner48d7f382008-04-02 04:24:33 +00001917 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1918 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001919}
1920
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001921/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001922bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001923 UsualUnaryConversions(castExpr);
1924
1925 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1926 // type needs to be scalar.
1927 if (castType->isVoidType()) {
1928 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001929 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
1930 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001931 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00001932 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
1933 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
1934 (castType->isStructureType() || castType->isUnionType())) {
1935 // GCC struct/union extension: allow cast to self.
1936 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
1937 << castType << castExpr->getSourceRange();
1938 } else if (castType->isUnionType()) {
1939 // GCC cast to union extension
1940 RecordDecl *RD = castType->getAsRecordType()->getDecl();
1941 RecordDecl::field_iterator Field, FieldEnd;
1942 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1943 Field != FieldEnd; ++Field) {
1944 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
1945 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
1946 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
1947 << castExpr->getSourceRange();
1948 break;
1949 }
1950 }
1951 if (Field == FieldEnd)
1952 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
1953 << castExpr->getType() << castExpr->getSourceRange();
1954 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001955 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001956 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001957 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001958 }
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001959 } else if (!castExpr->getType()->isScalarType() &&
1960 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001961 return Diag(castExpr->getLocStart(),
1962 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001963 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001964 } else if (castExpr->getType()->isVectorType()) {
1965 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1966 return true;
1967 } else if (castType->isVectorType()) {
1968 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1969 return true;
1970 }
1971 return false;
1972}
1973
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001974bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001975 assert(VectorTy->isVectorType() && "Not a vector type!");
1976
1977 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001978 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001979 return Diag(R.getBegin(),
1980 Ty->isVectorType() ?
1981 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00001982 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001983 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001984 } else
1985 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001986 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001987 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001988
1989 return false;
1990}
1991
Chris Lattner4b009652007-07-25 00:24:17 +00001992Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001993ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001994 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001995 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001996
1997 Expr *castExpr = static_cast<Expr*>(Op);
1998 QualType castType = QualType::getFromOpaquePtr(Ty);
1999
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002000 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
2001 return true;
Steve Naroff7f1412d2008-11-03 23:29:32 +00002002 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002003}
2004
Chris Lattner98a425c2007-11-26 01:40:58 +00002005/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2006/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00002007inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
2008 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
2009 UsualUnaryConversions(cond);
2010 UsualUnaryConversions(lex);
2011 UsualUnaryConversions(rex);
2012 QualType condT = cond->getType();
2013 QualType lexT = lex->getType();
2014 QualType rexT = rex->getType();
2015
2016 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002017 if (!cond->isTypeDependent()) {
2018 if (!condT->isScalarType()) { // C99 6.5.15p2
2019 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
2020 return QualType();
2021 }
Chris Lattner4b009652007-07-25 00:24:17 +00002022 }
Chris Lattner992ae932008-01-06 22:42:25 +00002023
2024 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002025 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
2026 return Context.DependentTy;
2027
Chris Lattner992ae932008-01-06 22:42:25 +00002028 // If both operands have arithmetic type, do the usual arithmetic conversions
2029 // to find a common type: C99 6.5.15p3,5.
2030 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002031 UsualArithmeticConversions(lex, rex);
2032 return lex->getType();
2033 }
Chris Lattner992ae932008-01-06 22:42:25 +00002034
2035 // If both operands are the same structure or union type, the result is that
2036 // type.
Chris Lattner71225142007-07-31 21:27:01 +00002037 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00002038 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002039 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00002040 // "If both the operands have structure or union type, the result has
2041 // that type." This implies that CV qualifiers are dropped.
2042 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002043 }
Chris Lattner992ae932008-01-06 22:42:25 +00002044
2045 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002046 // The following || allows only one side to be void (a GCC-ism).
2047 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00002048 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002049 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2050 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00002051 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002052 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2053 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00002054 ImpCastExprToType(lex, Context.VoidTy);
2055 ImpCastExprToType(rex, Context.VoidTy);
2056 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002057 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002058 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2059 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002060 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2061 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002062 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002063 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002064 return lexT;
2065 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002066 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2067 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002068 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002069 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002070 return rexT;
2071 }
Chris Lattner0ac51632008-01-06 22:50:31 +00002072 // Handle the case where both operands are pointers before we handle null
2073 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00002074 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2075 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2076 // get the "pointed to" types
2077 QualType lhptee = LHSPT->getPointeeType();
2078 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002079
Chris Lattner71225142007-07-31 21:27:01 +00002080 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2081 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002082 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002083 // Figure out necessary qualifiers (C99 6.5.15p6)
2084 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002085 QualType destType = Context.getPointerType(destPointee);
2086 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2087 ImpCastExprToType(rex, destType); // promote to void*
2088 return destType;
2089 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002090 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002091 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002092 QualType destType = Context.getPointerType(destPointee);
2093 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2094 ImpCastExprToType(rex, destType); // promote to void*
2095 return destType;
2096 }
Chris Lattner4b009652007-07-25 00:24:17 +00002097
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002098 QualType compositeType = lexT;
2099
2100 // If either type is an Objective-C object type then check
2101 // compatibility according to Objective-C.
2102 if (Context.isObjCObjectPointerType(lexT) ||
2103 Context.isObjCObjectPointerType(rexT)) {
2104 // If both operands are interfaces and either operand can be
2105 // assigned to the other, use that type as the composite
2106 // type. This allows
2107 // xxx ? (A*) a : (B*) b
2108 // where B is a subclass of A.
2109 //
2110 // Additionally, as for assignment, if either type is 'id'
2111 // allow silent coercion. Finally, if the types are
2112 // incompatible then make sure to use 'id' as the composite
2113 // type so the result is acceptable for sending messages to.
2114
2115 // FIXME: This code should not be localized to here. Also this
2116 // should use a compatible check instead of abusing the
2117 // canAssignObjCInterfaces code.
2118 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2119 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2120 if (LHSIface && RHSIface &&
2121 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2122 compositeType = lexT;
2123 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002124 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002125 compositeType = rexT;
2126 } else if (Context.isObjCIdType(lhptee) ||
2127 Context.isObjCIdType(rhptee)) {
2128 // FIXME: This code looks wrong, because isObjCIdType checks
2129 // the struct but getObjCIdType returns the pointer to
2130 // struct. This is horrible and should be fixed.
2131 compositeType = Context.getObjCIdType();
2132 } else {
2133 QualType incompatTy = Context.getObjCIdType();
2134 ImpCastExprToType(lex, incompatTy);
2135 ImpCastExprToType(rex, incompatTy);
2136 return incompatTy;
2137 }
2138 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2139 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002140 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002141 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002142 // In this situation, we assume void* type. No especially good
2143 // reason, but this is what gcc does, and we do have to pick
2144 // to get a consistent AST.
2145 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002146 ImpCastExprToType(lex, incompatTy);
2147 ImpCastExprToType(rex, incompatTy);
2148 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002149 }
2150 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002151 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2152 // differently qualified versions of compatible types, the result type is
2153 // a pointer to an appropriately qualified version of the *composite*
2154 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002155 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002156 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00002157 ImpCastExprToType(lex, compositeType);
2158 ImpCastExprToType(rex, compositeType);
2159 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002160 }
Chris Lattner4b009652007-07-25 00:24:17 +00002161 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002162 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2163 // evaluates to "struct objc_object *" (and is handled above when comparing
2164 // id with statically typed objects).
2165 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2166 // GCC allows qualified id and any Objective-C type to devolve to
2167 // id. Currently localizing to here until clear this should be
2168 // part of ObjCQualifiedIdTypesAreCompatible.
2169 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2170 (lexT->isObjCQualifiedIdType() &&
2171 Context.isObjCObjectPointerType(rexT)) ||
2172 (rexT->isObjCQualifiedIdType() &&
2173 Context.isObjCObjectPointerType(lexT))) {
2174 // FIXME: This is not the correct composite type. This only
2175 // happens to work because id can more or less be used anywhere,
2176 // however this may change the type of method sends.
2177 // FIXME: gcc adds some type-checking of the arguments and emits
2178 // (confusing) incompatible comparison warnings in some
2179 // cases. Investigate.
2180 QualType compositeType = Context.getObjCIdType();
2181 ImpCastExprToType(lex, compositeType);
2182 ImpCastExprToType(rex, compositeType);
2183 return compositeType;
2184 }
2185 }
2186
Steve Naroff3eac7692008-09-10 19:17:48 +00002187 // Selection between block pointer types is ok as long as they are the same.
2188 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2189 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2190 return lexT;
2191
Chris Lattner992ae932008-01-06 22:42:25 +00002192 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00002193 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002194 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002195 return QualType();
2196}
2197
Steve Naroff87d58b42007-09-16 03:34:24 +00002198/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002199/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00002200Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002201 SourceLocation ColonLoc,
2202 ExprTy *Cond, ExprTy *LHS,
2203 ExprTy *RHS) {
2204 Expr *CondExpr = (Expr *) Cond;
2205 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00002206
2207 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2208 // was the condition.
2209 bool isLHSNull = LHSExpr == 0;
2210 if (isLHSNull)
2211 LHSExpr = CondExpr;
2212
Chris Lattner4b009652007-07-25 00:24:17 +00002213 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
2214 RHSExpr, QuestionLoc);
2215 if (result.isNull())
2216 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00002217 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
2218 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00002219}
2220
Chris Lattner4b009652007-07-25 00:24:17 +00002221
2222// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2223// being closely modeled after the C99 spec:-). The odd characteristic of this
2224// routine is it effectively iqnores the qualifiers on the top level pointee.
2225// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2226// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00002227Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002228Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2229 QualType lhptee, rhptee;
2230
2231 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002232 lhptee = lhsType->getAsPointerType()->getPointeeType();
2233 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002234
2235 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002236 lhptee = Context.getCanonicalType(lhptee);
2237 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002238
Chris Lattner005ed752008-01-04 18:04:52 +00002239 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002240
2241 // C99 6.5.16.1p1: This following citation is common to constraints
2242 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2243 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00002244 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002245 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002246 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002247
2248 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2249 // incomplete type and the other is a pointer to a qualified or unqualified
2250 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002251 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002252 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002253 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002254
2255 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002256 assert(rhptee->isFunctionType());
2257 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002258 }
2259
2260 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002261 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002262 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002263
2264 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002265 assert(lhptee->isFunctionType());
2266 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002267 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002268
2269 // Check for ObjC interfaces
2270 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2271 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2272 if (LHSIface && RHSIface &&
2273 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2274 return ConvTy;
2275
2276 // ID acts sort of like void* for ObjC interfaces
2277 if (LHSIface && Context.isObjCIdType(rhptee))
2278 return ConvTy;
2279 if (RHSIface && Context.isObjCIdType(lhptee))
2280 return ConvTy;
2281
Chris Lattner4b009652007-07-25 00:24:17 +00002282 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2283 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002284 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2285 rhptee.getUnqualifiedType()))
2286 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002287 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002288}
2289
Steve Naroff3454b6c2008-09-04 15:10:53 +00002290/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2291/// block pointer types are compatible or whether a block and normal pointer
2292/// are compatible. It is more restrict than comparing two function pointer
2293// types.
2294Sema::AssignConvertType
2295Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2296 QualType rhsType) {
2297 QualType lhptee, rhptee;
2298
2299 // get the "pointed to" type (ignoring qualifiers at the top level)
2300 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2301 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2302
2303 // make sure we operate on the canonical type
2304 lhptee = Context.getCanonicalType(lhptee);
2305 rhptee = Context.getCanonicalType(rhptee);
2306
2307 AssignConvertType ConvTy = Compatible;
2308
2309 // For blocks we enforce that qualifiers are identical.
2310 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2311 ConvTy = CompatiblePointerDiscardsQualifiers;
2312
2313 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2314 return IncompatibleBlockPointer;
2315 return ConvTy;
2316}
2317
Chris Lattner4b009652007-07-25 00:24:17 +00002318/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2319/// has code to accommodate several GCC extensions when type checking
2320/// pointers. Here are some objectionable examples that GCC considers warnings:
2321///
2322/// int a, *pint;
2323/// short *pshort;
2324/// struct foo *pfoo;
2325///
2326/// pint = pshort; // warning: assignment from incompatible pointer type
2327/// a = pint; // warning: assignment makes integer from pointer without a cast
2328/// pint = a; // warning: assignment makes pointer from integer without a cast
2329/// pint = pfoo; // warning: assignment from incompatible pointer type
2330///
2331/// As a result, the code for dealing with pointers is more complex than the
2332/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002333///
Chris Lattner005ed752008-01-04 18:04:52 +00002334Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002335Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002336 // Get canonical types. We're not formatting these types, just comparing
2337 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002338 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2339 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002340
2341 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002342 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002343
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002344 // If the left-hand side is a reference type, then we are in a
2345 // (rare!) case where we've allowed the use of references in C,
2346 // e.g., as a parameter type in a built-in function. In this case,
2347 // just make sure that the type referenced is compatible with the
2348 // right-hand side type. The caller is responsible for adjusting
2349 // lhsType so that the resulting expression does not have reference
2350 // type.
2351 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2352 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002353 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002354 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002355 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002356
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002357 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2358 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002359 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002360 // Relax integer conversions like we do for pointers below.
2361 if (rhsType->isIntegerType())
2362 return IntToPointer;
2363 if (lhsType->isIntegerType())
2364 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002365 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002366 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002367
Nate Begemanc5f0f652008-07-14 18:02:46 +00002368 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002369 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002370 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2371 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002372 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002373
Nate Begemanc5f0f652008-07-14 18:02:46 +00002374 // If we are allowing lax vector conversions, and LHS and RHS are both
2375 // vectors, the total size only needs to be the same. This is a bitcast;
2376 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002377 if (getLangOptions().LaxVectorConversions &&
2378 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002379 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2380 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002381 }
2382 return Incompatible;
2383 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002384
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002385 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002386 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002387
Chris Lattner390564e2008-04-07 06:49:41 +00002388 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002389 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002390 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002391
Chris Lattner390564e2008-04-07 06:49:41 +00002392 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002393 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002394
Steve Naroffa982c712008-09-29 18:10:17 +00002395 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002396 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002397 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002398
2399 // Treat block pointers as objects.
2400 if (getLangOptions().ObjC1 &&
2401 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2402 return Compatible;
2403 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002404 return Incompatible;
2405 }
2406
2407 if (isa<BlockPointerType>(lhsType)) {
2408 if (rhsType->isIntegerType())
2409 return IntToPointer;
2410
Steve Naroffa982c712008-09-29 18:10:17 +00002411 // Treat block pointers as objects.
2412 if (getLangOptions().ObjC1 &&
2413 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2414 return Compatible;
2415
Steve Naroff3454b6c2008-09-04 15:10:53 +00002416 if (rhsType->isBlockPointerType())
2417 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2418
2419 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2420 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002421 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002422 }
Chris Lattner1853da22008-01-04 23:18:45 +00002423 return Incompatible;
2424 }
2425
Chris Lattner390564e2008-04-07 06:49:41 +00002426 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002427 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002428 if (lhsType == Context.BoolTy)
2429 return Compatible;
2430
2431 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002432 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002433
Chris Lattner390564e2008-04-07 06:49:41 +00002434 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002435 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002436
2437 if (isa<BlockPointerType>(lhsType) &&
2438 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002439 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002440 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002441 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002442
Chris Lattner1853da22008-01-04 23:18:45 +00002443 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002444 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002445 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002446 }
2447 return Incompatible;
2448}
2449
Chris Lattner005ed752008-01-04 18:04:52 +00002450Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002451Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002452 if (getLangOptions().CPlusPlus) {
2453 if (!lhsType->isRecordType()) {
2454 // C++ 5.17p3: If the left operand is not of class type, the
2455 // expression is implicitly converted (C++ 4) to the
2456 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002457 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2458 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002459 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002460 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002461 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002462 }
2463
2464 // FIXME: Currently, we fall through and treat C++ classes like C
2465 // structures.
2466 }
2467
Steve Naroffcdee22d2007-11-27 17:58:44 +00002468 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2469 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002470 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2471 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002472 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002473 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002474 return Compatible;
2475 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002476
2477 // We don't allow conversion of non-null-pointer constants to integers.
2478 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2479 return IntToBlockPointer;
2480
Chris Lattner5f505bf2007-10-16 02:55:40 +00002481 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002482 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002483 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002484 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002485 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002486 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002487 if (!lhsType->isReferenceType())
2488 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002489
Chris Lattner005ed752008-01-04 18:04:52 +00002490 Sema::AssignConvertType result =
2491 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002492
2493 // C99 6.5.16.1p2: The value of the right operand is converted to the
2494 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002495 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2496 // so that we can use references in built-in functions even in C.
2497 // The getNonReferenceType() call makes sure that the resulting expression
2498 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002499 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002500 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002501 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002502}
2503
Chris Lattner005ed752008-01-04 18:04:52 +00002504Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002505Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2506 return CheckAssignmentConstraints(lhsType, rhsType);
2507}
2508
Chris Lattner1eafdea2008-11-18 01:30:42 +00002509QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002510 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002511 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002512 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002513 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002514}
2515
Chris Lattner1eafdea2008-11-18 01:30:42 +00002516inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002517 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002518 // For conversion purposes, we ignore any qualifiers.
2519 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002520 QualType lhsType =
2521 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2522 QualType rhsType =
2523 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002524
Nate Begemanc5f0f652008-07-14 18:02:46 +00002525 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002526 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002527 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002528
Nate Begemanc5f0f652008-07-14 18:02:46 +00002529 // Handle the case of a vector & extvector type of the same size and element
2530 // type. It would be nice if we only had one vector type someday.
2531 if (getLangOptions().LaxVectorConversions)
2532 if (const VectorType *LV = lhsType->getAsVectorType())
2533 if (const VectorType *RV = rhsType->getAsVectorType())
2534 if (LV->getElementType() == RV->getElementType() &&
2535 LV->getNumElements() == RV->getNumElements())
2536 return lhsType->isExtVectorType() ? lhsType : rhsType;
2537
2538 // If the lhs is an extended vector and the rhs is a scalar of the same type
2539 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002540 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002541 QualType eltType = V->getElementType();
2542
2543 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2544 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2545 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002546 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002547 return lhsType;
2548 }
2549 }
2550
Nate Begemanc5f0f652008-07-14 18:02:46 +00002551 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002552 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002553 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002554 QualType eltType = V->getElementType();
2555
2556 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2557 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2558 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002559 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002560 return rhsType;
2561 }
2562 }
2563
Chris Lattner4b009652007-07-25 00:24:17 +00002564 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002565 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002566 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002567 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002568 return QualType();
2569}
2570
2571inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002572 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002573{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002574 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002575 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002576
Steve Naroff8f708362007-08-24 19:07:16 +00002577 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002578
Chris Lattner4b009652007-07-25 00:24:17 +00002579 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002580 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002581 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002582}
2583
2584inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002585 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002586{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002587 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2588 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2589 return CheckVectorOperands(Loc, lex, rex);
2590 return InvalidOperands(Loc, lex, rex);
2591 }
Chris Lattner4b009652007-07-25 00:24:17 +00002592
Steve Naroff8f708362007-08-24 19:07:16 +00002593 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002594
Chris Lattner4b009652007-07-25 00:24:17 +00002595 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002596 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002597 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002598}
2599
2600inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002601 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002602{
2603 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002604 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002605
Steve Naroff8f708362007-08-24 19:07:16 +00002606 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002607
Chris Lattner4b009652007-07-25 00:24:17 +00002608 // handle the common case first (both operands are arithmetic).
2609 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002610 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002611
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002612 // Put any potential pointer into PExp
2613 Expr* PExp = lex, *IExp = rex;
2614 if (IExp->getType()->isPointerType())
2615 std::swap(PExp, IExp);
2616
2617 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2618 if (IExp->getType()->isIntegerType()) {
2619 // Check for arithmetic on pointers to incomplete types
2620 if (!PTy->getPointeeType()->isObjectType()) {
2621 if (PTy->getPointeeType()->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002622 Diag(Loc, diag::ext_gnu_void_ptr)
2623 << lex->getSourceRange() << rex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002624 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002625 Diag(Loc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002626 << lex->getType() << lex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002627 return QualType();
2628 }
2629 }
2630 return PExp->getType();
2631 }
2632 }
2633
Chris Lattner1eafdea2008-11-18 01:30:42 +00002634 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002635}
2636
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002637// C99 6.5.6
2638QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002639 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002640 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002641 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002642
Steve Naroff8f708362007-08-24 19:07:16 +00002643 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002644
Chris Lattnerf6da2912007-12-09 21:53:25 +00002645 // Enforce type constraints: C99 6.5.6p3.
2646
2647 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002648 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002649 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002650
2651 // Either ptr - int or ptr - ptr.
2652 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002653 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002654
Chris Lattnerf6da2912007-12-09 21:53:25 +00002655 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002656 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002657 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002658 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002659 Diag(Loc, diag::ext_gnu_void_ptr)
2660 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002661 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002662 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002663 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002664 return QualType();
2665 }
2666 }
2667
2668 // The result type of a pointer-int computation is the pointer type.
2669 if (rex->getType()->isIntegerType())
2670 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002671
Chris Lattnerf6da2912007-12-09 21:53:25 +00002672 // Handle pointer-pointer subtractions.
2673 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002674 QualType rpointee = RHSPTy->getPointeeType();
2675
Chris Lattnerf6da2912007-12-09 21:53:25 +00002676 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002677 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002678 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002679 if (rpointee->isVoidType()) {
2680 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002681 Diag(Loc, diag::ext_gnu_void_ptr)
2682 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002683 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002684 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002685 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002686 return QualType();
2687 }
2688 }
2689
2690 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002691 if (!Context.typesAreCompatible(
2692 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2693 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002694 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002695 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002696 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002697 return QualType();
2698 }
2699
2700 return Context.getPointerDiffType();
2701 }
2702 }
2703
Chris Lattner1eafdea2008-11-18 01:30:42 +00002704 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002705}
2706
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002707// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002708QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002709 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002710 // C99 6.5.7p2: Each of the operands shall have integer type.
2711 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002712 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002713
Chris Lattner2c8bff72007-12-12 05:47:28 +00002714 // Shifts don't perform usual arithmetic conversions, they just do integer
2715 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002716 if (!isCompAssign)
2717 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002718 UsualUnaryConversions(rex);
2719
2720 // "The type of the result is that of the promoted left operand."
2721 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002722}
2723
Eli Friedman0d9549b2008-08-22 00:56:42 +00002724static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2725 ASTContext& Context) {
2726 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2727 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2728 // ID acts sort of like void* for ObjC interfaces
2729 if (LHSIface && Context.isObjCIdType(RHS))
2730 return true;
2731 if (RHSIface && Context.isObjCIdType(LHS))
2732 return true;
2733 if (!LHSIface || !RHSIface)
2734 return false;
2735 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2736 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2737}
2738
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002739// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002740QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002741 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002742 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002743 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002744
Chris Lattner254f3bc2007-08-26 01:18:55 +00002745 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002746 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2747 UsualArithmeticConversions(lex, rex);
2748 else {
2749 UsualUnaryConversions(lex);
2750 UsualUnaryConversions(rex);
2751 }
Chris Lattner4b009652007-07-25 00:24:17 +00002752 QualType lType = lex->getType();
2753 QualType rType = rex->getType();
2754
Ted Kremenek486509e2007-10-29 17:13:39 +00002755 // For non-floating point types, check for self-comparisons of the form
2756 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2757 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002758 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002759 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2760 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002761 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002762 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002763 }
2764
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002765 // The result of comparisons is 'bool' in C++, 'int' in C.
2766 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2767
Chris Lattner254f3bc2007-08-26 01:18:55 +00002768 if (isRelational) {
2769 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002770 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002771 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002772 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002773 if (lType->isFloatingType()) {
2774 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002775 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002776 }
2777
Chris Lattner254f3bc2007-08-26 01:18:55 +00002778 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002779 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002780 }
Chris Lattner4b009652007-07-25 00:24:17 +00002781
Chris Lattner22be8422007-08-26 01:10:14 +00002782 bool LHSIsNull = lex->isNullPointerConstant(Context);
2783 bool RHSIsNull = rex->isNullPointerConstant(Context);
2784
Chris Lattner254f3bc2007-08-26 01:18:55 +00002785 // All of the following pointer related warnings are GCC extensions, except
2786 // when handling null pointer constants. One day, we can consider making them
2787 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002788 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002789 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002790 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002791 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002792 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002793
Steve Naroff3b435622007-11-13 14:57:38 +00002794 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002795 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2796 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002797 RCanPointeeTy.getUnqualifiedType()) &&
2798 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002799 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002800 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002801 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002802 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002803 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002804 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002805 // Handle block pointer types.
2806 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2807 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2808 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2809
2810 if (!LHSIsNull && !RHSIsNull &&
2811 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002812 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002813 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00002814 }
2815 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002816 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002817 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002818 // Allow block pointers to be compared with null pointer constants.
2819 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2820 (lType->isPointerType() && rType->isBlockPointerType())) {
2821 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002822 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002823 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00002824 }
2825 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002826 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00002827 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002828
Steve Naroff936c4362008-06-03 14:04:54 +00002829 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002830 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00002831 const PointerType *LPT = lType->getAsPointerType();
2832 const PointerType *RPT = rType->getAsPointerType();
2833 bool LPtrToVoid = LPT ?
2834 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2835 bool RPtrToVoid = RPT ?
2836 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2837
2838 if (!LPtrToVoid && !RPtrToVoid &&
2839 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002840 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002841 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00002842 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002843 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00002844 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002845 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002846 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002847 }
Steve Naroff936c4362008-06-03 14:04:54 +00002848 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2849 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002850 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002851 } else {
2852 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002853 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00002854 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002855 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002856 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002857 }
Steve Naroff936c4362008-06-03 14:04:54 +00002858 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002859 }
Steve Naroff936c4362008-06-03 14:04:54 +00002860 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2861 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002862 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002863 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002864 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002865 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002866 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002867 }
Steve Naroff936c4362008-06-03 14:04:54 +00002868 if (lType->isIntegerType() &&
2869 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002870 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002871 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002872 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002873 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002874 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002875 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002876 // Handle block pointers.
2877 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2878 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002879 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002880 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002881 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002882 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002883 }
2884 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2885 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002886 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002887 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002888 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002889 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002890 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00002891 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002892}
2893
Nate Begemanc5f0f652008-07-14 18:02:46 +00002894/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2895/// operates on extended vector types. Instead of producing an IntTy result,
2896/// like a scalar comparison, a vector comparison produces a vector of integer
2897/// types.
2898QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002899 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00002900 bool isRelational) {
2901 // Check to make sure we're operating on vectors of the same type and width,
2902 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002903 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002904 if (vType.isNull())
2905 return vType;
2906
2907 QualType lType = lex->getType();
2908 QualType rType = rex->getType();
2909
2910 // For non-floating point types, check for self-comparisons of the form
2911 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2912 // often indicate logic errors in the program.
2913 if (!lType->isFloatingType()) {
2914 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2915 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2916 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002917 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002918 }
2919
2920 // Check for comparisons of floating point operands using != and ==.
2921 if (!isRelational && lType->isFloatingType()) {
2922 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002923 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002924 }
2925
2926 // Return the type for the comparison, which is the same as vector type for
2927 // integer vectors, or an integer type of identical size and number of
2928 // elements for floating point vectors.
2929 if (lType->isIntegerType())
2930 return lType;
2931
2932 const VectorType *VTy = lType->getAsVectorType();
2933
2934 // FIXME: need to deal with non-32b int / non-64b long long
2935 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2936 if (TypeSize == 32) {
2937 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2938 }
2939 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2940 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2941}
2942
Chris Lattner4b009652007-07-25 00:24:17 +00002943inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002944 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002945{
2946 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002947 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002948
Steve Naroff8f708362007-08-24 19:07:16 +00002949 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002950
2951 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002952 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002953 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002954}
2955
2956inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00002957 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00002958{
2959 UsualUnaryConversions(lex);
2960 UsualUnaryConversions(rex);
2961
Eli Friedmanbea3f842008-05-13 20:16:47 +00002962 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002963 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002964 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002965}
2966
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00002967/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
2968/// is a read-only property; return true if so. A readonly property expression
2969/// depends on various declarations and thus must be treated specially.
2970///
2971static bool IsReadonlyProperty(Expr *E, Sema &S)
2972{
2973 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
2974 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
2975 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
2976 QualType BaseType = PropExpr->getBase()->getType();
2977 if (const PointerType *PTy = BaseType->getAsPointerType())
2978 if (const ObjCInterfaceType *IFTy =
2979 PTy->getPointeeType()->getAsObjCInterfaceType())
2980 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
2981 if (S.isPropertyReadonly(PDecl, IFace))
2982 return true;
2983 }
2984 }
2985 return false;
2986}
2987
Chris Lattner4c2642c2008-11-18 01:22:49 +00002988/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
2989/// emit an error and return true. If so, return false.
2990static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00002991 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
2992 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
2993 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00002994 if (IsLV == Expr::MLV_Valid)
2995 return false;
2996
2997 unsigned Diag = 0;
2998 bool NeedType = false;
2999 switch (IsLV) { // C99 6.5.16p2
3000 default: assert(0 && "Unknown result from isModifiableLvalue!");
3001 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00003002 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003003 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3004 NeedType = true;
3005 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003006 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003007 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3008 NeedType = true;
3009 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003010 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003011 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3012 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003013 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003014 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3015 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003016 case Expr::MLV_IncompleteType:
3017 case Expr::MLV_IncompleteVoidType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003018 Diag = diag::err_typecheck_incomplete_type_not_modifiable_lvalue;
3019 NeedType = true;
3020 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003021 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003022 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3023 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003024 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003025 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3026 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003027 case Expr::MLV_ReadonlyProperty:
3028 Diag = diag::error_readonly_property_assignment;
3029 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003030 case Expr::MLV_NoSetterProperty:
3031 Diag = diag::error_nosetter_property_assignment;
3032 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003033 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003034
Chris Lattner4c2642c2008-11-18 01:22:49 +00003035 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003036 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003037 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003038 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003039 return true;
3040}
3041
3042
3043
3044// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003045QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3046 SourceLocation Loc,
3047 QualType CompoundType) {
3048 // Verify that LHS is a modifiable lvalue, and emit error if not.
3049 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003050 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003051
3052 QualType LHSType = LHS->getType();
3053 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003054
Chris Lattner005ed752008-01-04 18:04:52 +00003055 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003056 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003057 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003058 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003059 // Special case of NSObject attributes on c-style pointer types.
3060 if (ConvTy == IncompatiblePointer &&
3061 ((Context.isObjCNSObjectType(LHSType) &&
3062 Context.isObjCObjectPointerType(RHSType)) ||
3063 (Context.isObjCNSObjectType(RHSType) &&
3064 Context.isObjCObjectPointerType(LHSType))))
3065 ConvTy = Compatible;
3066
Chris Lattner34c85082008-08-21 18:04:13 +00003067 // If the RHS is a unary plus or minus, check to see if they = and + are
3068 // right next to each other. If so, the user may have typo'd "x =+ 4"
3069 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003070 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003071 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3072 RHSCheck = ICE->getSubExpr();
3073 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3074 if ((UO->getOpcode() == UnaryOperator::Plus ||
3075 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003076 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003077 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003078 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003079 Diag(Loc, diag::warn_not_compound_assign)
3080 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3081 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003082 }
3083 } else {
3084 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003085 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003086 }
Chris Lattner005ed752008-01-04 18:04:52 +00003087
Chris Lattner1eafdea2008-11-18 01:30:42 +00003088 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3089 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003090 return QualType();
3091
Chris Lattner4b009652007-07-25 00:24:17 +00003092 // C99 6.5.16p3: The type of an assignment expression is the type of the
3093 // left operand unless the left operand has qualified type, in which case
3094 // it is the unqualified version of the type of the left operand.
3095 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3096 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003097 // C++ 5.17p1: the type of the assignment expression is that of its left
3098 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003099 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003100}
3101
Chris Lattner1eafdea2008-11-18 01:30:42 +00003102// C99 6.5.17
3103QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3104 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00003105
3106 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003107 DefaultFunctionArrayConversion(RHS);
3108 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003109}
3110
3111/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3112/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003113QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3114 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003115 QualType ResType = Op->getType();
3116 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003117
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003118 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3119 // Decrement of bool is not allowed.
3120 if (!isInc) {
3121 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3122 return QualType();
3123 }
3124 // Increment of bool sets it to true, but is deprecated.
3125 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3126 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003127 // OK!
3128 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3129 // C99 6.5.2.4p2, 6.5.6p2
3130 if (PT->getPointeeType()->isObjectType()) {
3131 // Pointer to object is ok!
3132 } else if (PT->getPointeeType()->isVoidType()) {
3133 // Pointer to void is extension.
3134 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
3135 } else {
Chris Lattner9d2cf082008-11-19 05:27:50 +00003136 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003137 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003138 return QualType();
3139 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003140 } else if (ResType->isComplexType()) {
3141 // C99 does not support ++/-- on complex types, we allow as an extension.
3142 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003143 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003144 } else {
3145 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003146 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003147 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003148 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00003149 // At this point, we know we have a real, complex or pointer type.
3150 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003151 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003152 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003153 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003154}
3155
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003156/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003157/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003158/// where the declaration is needed for type checking. We only need to
3159/// handle cases when the expression references a function designator
3160/// or is an lvalue. Here are some examples:
3161/// - &(x) => x
3162/// - &*****f => f for f a function designator.
3163/// - &s.xx => s
3164/// - &s.zz[1].yy -> s, if zz is an array
3165/// - *(x + 1) -> x, if x is an array
3166/// - &"123"[2] -> 0
3167/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003168static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003169 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003170 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003171 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003172 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003173 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003174 // Fields cannot be declared with a 'register' storage class.
3175 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003176 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003177 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003178 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003179 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003180 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003181
Douglas Gregord2baafd2008-10-21 16:13:35 +00003182 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003183 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003184 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003185 return 0;
3186 else
3187 return VD;
3188 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003189 case Stmt::UnaryOperatorClass: {
3190 UnaryOperator *UO = cast<UnaryOperator>(E);
3191
3192 switch(UO->getOpcode()) {
3193 case UnaryOperator::Deref: {
3194 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003195 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3196 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3197 if (!VD || VD->getType()->isPointerType())
3198 return 0;
3199 return VD;
3200 }
3201 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003202 }
3203 case UnaryOperator::Real:
3204 case UnaryOperator::Imag:
3205 case UnaryOperator::Extension:
3206 return getPrimaryDecl(UO->getSubExpr());
3207 default:
3208 return 0;
3209 }
3210 }
3211 case Stmt::BinaryOperatorClass: {
3212 BinaryOperator *BO = cast<BinaryOperator>(E);
3213
3214 // Handle cases involving pointer arithmetic. The result of an
3215 // Assign or AddAssign is not an lvalue so they can be ignored.
3216
3217 // (x + n) or (n + x) => x
3218 if (BO->getOpcode() == BinaryOperator::Add) {
3219 if (BO->getLHS()->getType()->isPointerType()) {
3220 return getPrimaryDecl(BO->getLHS());
3221 } else if (BO->getRHS()->getType()->isPointerType()) {
3222 return getPrimaryDecl(BO->getRHS());
3223 }
3224 }
3225
3226 return 0;
3227 }
Chris Lattner4b009652007-07-25 00:24:17 +00003228 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003229 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003230 case Stmt::ImplicitCastExprClass:
3231 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003232 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003233 default:
3234 return 0;
3235 }
3236}
3237
3238/// CheckAddressOfOperand - The operand of & must be either a function
3239/// designator or an lvalue designating an object. If it is an lvalue, the
3240/// object cannot be declared with storage class register or be a bit field.
3241/// Note: The usual conversions are *not* applied to the operand of the &
3242/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00003243/// In C++, the operand might be an overloaded function name, in which case
3244/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003245QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003246 if (op->isTypeDependent())
3247 return Context.DependentTy;
3248
Steve Naroff9c6c3592008-01-13 17:10:08 +00003249 if (getLangOptions().C99) {
3250 // Implement C99-only parts of addressof rules.
3251 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3252 if (uOp->getOpcode() == UnaryOperator::Deref)
3253 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3254 // (assuming the deref expression is valid).
3255 return uOp->getSubExpr()->getType();
3256 }
3257 // Technically, there should be a check for array subscript
3258 // expressions here, but the result of one is always an lvalue anyway.
3259 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003260 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003261 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003262
Chris Lattner4b009652007-07-25 00:24:17 +00003263 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003264 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3265 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003266 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3267 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003268 return QualType();
3269 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003270 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003271 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3272 if (Field->isBitField()) {
3273 Diag(OpLoc, diag::err_typecheck_address_of)
3274 << "bit-field" << op->getSourceRange();
3275 return QualType();
3276 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003277 }
3278 // Check for Apple extension for accessing vector components.
3279 } else if (isa<ArraySubscriptExpr>(op) &&
3280 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003281 Diag(OpLoc, diag::err_typecheck_address_of)
3282 << "vector" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003283 return QualType();
3284 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00003285 // We have an lvalue with a decl. Make sure the decl is not declared
3286 // with the register storage-class specifier.
3287 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3288 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003289 Diag(OpLoc, diag::err_typecheck_address_of)
3290 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003291 return QualType();
3292 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003293 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003294 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003295 } else if (isa<FieldDecl>(dcl)) {
3296 // Okay: we can take the address of a field.
Nuno Lopesdf239522008-12-16 22:58:26 +00003297 } else if (isa<FunctionDecl>(dcl)) {
3298 // Okay: we can take the address of a function.
Douglas Gregor5b82d612008-12-10 21:26:49 +00003299 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003300 else
Chris Lattner4b009652007-07-25 00:24:17 +00003301 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003302 }
Chris Lattnera55e3212008-07-27 00:48:22 +00003303
Chris Lattner4b009652007-07-25 00:24:17 +00003304 // If the operand has type "type", the result has type "pointer to type".
3305 return Context.getPointerType(op->getType());
3306}
3307
Chris Lattnerda5c0872008-11-23 09:13:29 +00003308QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3309 UsualUnaryConversions(Op);
3310 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003311
Chris Lattnerda5c0872008-11-23 09:13:29 +00003312 // Note that per both C89 and C99, this is always legal, even if ptype is an
3313 // incomplete type or void. It would be possible to warn about dereferencing
3314 // a void pointer, but it's completely well-defined, and such a warning is
3315 // unlikely to catch any mistakes.
3316 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003317 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00003318
Chris Lattner77d52da2008-11-20 06:06:08 +00003319 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003320 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003321 return QualType();
3322}
3323
3324static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3325 tok::TokenKind Kind) {
3326 BinaryOperator::Opcode Opc;
3327 switch (Kind) {
3328 default: assert(0 && "Unknown binop!");
3329 case tok::star: Opc = BinaryOperator::Mul; break;
3330 case tok::slash: Opc = BinaryOperator::Div; break;
3331 case tok::percent: Opc = BinaryOperator::Rem; break;
3332 case tok::plus: Opc = BinaryOperator::Add; break;
3333 case tok::minus: Opc = BinaryOperator::Sub; break;
3334 case tok::lessless: Opc = BinaryOperator::Shl; break;
3335 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3336 case tok::lessequal: Opc = BinaryOperator::LE; break;
3337 case tok::less: Opc = BinaryOperator::LT; break;
3338 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3339 case tok::greater: Opc = BinaryOperator::GT; break;
3340 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3341 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3342 case tok::amp: Opc = BinaryOperator::And; break;
3343 case tok::caret: Opc = BinaryOperator::Xor; break;
3344 case tok::pipe: Opc = BinaryOperator::Or; break;
3345 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3346 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3347 case tok::equal: Opc = BinaryOperator::Assign; break;
3348 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3349 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3350 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3351 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3352 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3353 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3354 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3355 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3356 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3357 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3358 case tok::comma: Opc = BinaryOperator::Comma; break;
3359 }
3360 return Opc;
3361}
3362
3363static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3364 tok::TokenKind Kind) {
3365 UnaryOperator::Opcode Opc;
3366 switch (Kind) {
3367 default: assert(0 && "Unknown unary op!");
3368 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3369 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3370 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3371 case tok::star: Opc = UnaryOperator::Deref; break;
3372 case tok::plus: Opc = UnaryOperator::Plus; break;
3373 case tok::minus: Opc = UnaryOperator::Minus; break;
3374 case tok::tilde: Opc = UnaryOperator::Not; break;
3375 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003376 case tok::kw___real: Opc = UnaryOperator::Real; break;
3377 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3378 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3379 }
3380 return Opc;
3381}
3382
Douglas Gregord7f915e2008-11-06 23:29:22 +00003383/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3384/// operator @p Opc at location @c TokLoc. This routine only supports
3385/// built-in operations; ActOnBinOp handles overloaded operators.
3386Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3387 unsigned Op,
3388 Expr *lhs, Expr *rhs) {
3389 QualType ResultTy; // Result type of the binary operator.
3390 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3391 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3392
3393 switch (Opc) {
3394 default:
3395 assert(0 && "Unknown binary expr!");
3396 case BinaryOperator::Assign:
3397 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3398 break;
3399 case BinaryOperator::Mul:
3400 case BinaryOperator::Div:
3401 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3402 break;
3403 case BinaryOperator::Rem:
3404 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3405 break;
3406 case BinaryOperator::Add:
3407 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3408 break;
3409 case BinaryOperator::Sub:
3410 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3411 break;
3412 case BinaryOperator::Shl:
3413 case BinaryOperator::Shr:
3414 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3415 break;
3416 case BinaryOperator::LE:
3417 case BinaryOperator::LT:
3418 case BinaryOperator::GE:
3419 case BinaryOperator::GT:
3420 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3421 break;
3422 case BinaryOperator::EQ:
3423 case BinaryOperator::NE:
3424 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3425 break;
3426 case BinaryOperator::And:
3427 case BinaryOperator::Xor:
3428 case BinaryOperator::Or:
3429 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3430 break;
3431 case BinaryOperator::LAnd:
3432 case BinaryOperator::LOr:
3433 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3434 break;
3435 case BinaryOperator::MulAssign:
3436 case BinaryOperator::DivAssign:
3437 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3438 if (!CompTy.isNull())
3439 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3440 break;
3441 case BinaryOperator::RemAssign:
3442 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3443 if (!CompTy.isNull())
3444 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3445 break;
3446 case BinaryOperator::AddAssign:
3447 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3448 if (!CompTy.isNull())
3449 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3450 break;
3451 case BinaryOperator::SubAssign:
3452 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3453 if (!CompTy.isNull())
3454 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3455 break;
3456 case BinaryOperator::ShlAssign:
3457 case BinaryOperator::ShrAssign:
3458 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3459 if (!CompTy.isNull())
3460 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3461 break;
3462 case BinaryOperator::AndAssign:
3463 case BinaryOperator::XorAssign:
3464 case BinaryOperator::OrAssign:
3465 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3466 if (!CompTy.isNull())
3467 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3468 break;
3469 case BinaryOperator::Comma:
3470 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3471 break;
3472 }
3473 if (ResultTy.isNull())
3474 return true;
3475 if (CompTy.isNull())
3476 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
3477 else
3478 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
3479}
3480
Chris Lattner4b009652007-07-25 00:24:17 +00003481// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003482Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3483 tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00003484 ExprTy *LHS, ExprTy *RHS) {
3485 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
3486 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
3487
Steve Naroff87d58b42007-09-16 03:34:24 +00003488 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3489 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003490
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003491 // If either expression is type-dependent, just build the AST.
3492 // FIXME: We'll need to perform some caching of the result of name
3493 // lookup for operator+.
3494 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
3495 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3496 return new CompoundAssignOperator(lhs, rhs, Opc, Context.DependentTy,
3497 Context.DependentTy, TokLoc);
3498 else
3499 return new BinaryOperator(lhs, rhs, Opc, Context.DependentTy, TokLoc);
3500 }
3501
Douglas Gregord7f915e2008-11-06 23:29:22 +00003502 if (getLangOptions().CPlusPlus &&
3503 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3504 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003505 // If this is one of the assignment operators, we only perform
3506 // overload resolution if the left-hand side is a class or
3507 // enumeration type (C++ [expr.ass]p3).
3508 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3509 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3510 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3511 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003512
3513 // Determine which overloaded operator we're dealing with.
3514 static const OverloadedOperatorKind OverOps[] = {
3515 OO_Star, OO_Slash, OO_Percent,
3516 OO_Plus, OO_Minus,
3517 OO_LessLess, OO_GreaterGreater,
3518 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3519 OO_EqualEqual, OO_ExclaimEqual,
3520 OO_Amp,
3521 OO_Caret,
3522 OO_Pipe,
3523 OO_AmpAmp,
3524 OO_PipePipe,
3525 OO_Equal, OO_StarEqual,
3526 OO_SlashEqual, OO_PercentEqual,
3527 OO_PlusEqual, OO_MinusEqual,
3528 OO_LessLessEqual, OO_GreaterGreaterEqual,
3529 OO_AmpEqual, OO_CaretEqual,
3530 OO_PipeEqual,
3531 OO_Comma
3532 };
3533 OverloadedOperatorKind OverOp = OverOps[Opc];
3534
Douglas Gregor5ed15042008-11-18 23:14:02 +00003535 // Add the appropriate overloaded operators (C++ [over.match.oper])
3536 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003537 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003538 Expr *Args[2] = { lhs, rhs };
Douglas Gregor5ed15042008-11-18 23:14:02 +00003539 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregord7f915e2008-11-06 23:29:22 +00003540
3541 // Perform overload resolution.
3542 OverloadCandidateSet::iterator Best;
3543 switch (BestViableFunction(CandidateSet, Best)) {
3544 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003545 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003546 FunctionDecl *FnDecl = Best->Function;
3547
Douglas Gregor70d26122008-11-12 17:17:38 +00003548 if (FnDecl) {
3549 // We matched an overloaded operator. Build a call to that
3550 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003551
Douglas Gregor70d26122008-11-12 17:17:38 +00003552 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003553 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3554 if (PerformObjectArgumentInitialization(lhs, Method) ||
3555 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3556 "passing"))
3557 return true;
3558 } else {
3559 // Convert the arguments.
3560 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3561 "passing") ||
3562 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3563 "passing"))
3564 return true;
3565 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003566
Douglas Gregor70d26122008-11-12 17:17:38 +00003567 // Determine the result type
3568 QualType ResultTy
3569 = FnDecl->getType()->getAsFunctionType()->getResultType();
3570 ResultTy = ResultTy.getNonReferenceType();
3571
3572 // Build the actual expression node.
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003573 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3574 SourceLocation());
3575 UsualUnaryConversions(FnExpr);
3576
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003577 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, TokLoc);
Douglas Gregor70d26122008-11-12 17:17:38 +00003578 } else {
3579 // We matched a built-in operator. Convert the arguments, then
3580 // break out so that we will build the appropriate built-in
3581 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003582 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3583 Best->Conversions[0], "passing") ||
3584 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3585 Best->Conversions[1], "passing"))
Douglas Gregor70d26122008-11-12 17:17:38 +00003586 return true;
3587
3588 break;
3589 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003590 }
3591
3592 case OR_No_Viable_Function:
3593 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003594 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003595 break;
3596
3597 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003598 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3599 << BinaryOperator::getOpcodeStr(Opc)
3600 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003601 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3602 return true;
3603 }
3604
Douglas Gregor70d26122008-11-12 17:17:38 +00003605 // Either we found no viable overloaded operator or we matched a
3606 // built-in operator. In either case, fall through to trying to
3607 // build a built-in operation.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003608 }
Chris Lattner4b009652007-07-25 00:24:17 +00003609
Douglas Gregord7f915e2008-11-06 23:29:22 +00003610 // Build a built-in binary operation.
3611 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003612}
3613
3614// Unary Operators. 'Tok' is the token for the operator.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003615Action::ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3616 tok::TokenKind Op, ExprTy *input) {
Chris Lattner4b009652007-07-25 00:24:17 +00003617 Expr *Input = (Expr*)input;
3618 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003619
3620 if (getLangOptions().CPlusPlus &&
3621 (Input->getType()->isRecordType()
3622 || Input->getType()->isEnumeralType())) {
3623 // Determine which overloaded operator we're dealing with.
3624 static const OverloadedOperatorKind OverOps[] = {
3625 OO_None, OO_None,
3626 OO_PlusPlus, OO_MinusMinus,
3627 OO_Amp, OO_Star,
3628 OO_Plus, OO_Minus,
3629 OO_Tilde, OO_Exclaim,
3630 OO_None, OO_None,
3631 OO_None,
3632 OO_None
3633 };
3634 OverloadedOperatorKind OverOp = OverOps[Opc];
3635
3636 // Add the appropriate overloaded operators (C++ [over.match.oper])
3637 // to the candidate set.
3638 OverloadCandidateSet CandidateSet;
3639 if (OverOp != OO_None)
3640 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3641
3642 // Perform overload resolution.
3643 OverloadCandidateSet::iterator Best;
3644 switch (BestViableFunction(CandidateSet, Best)) {
3645 case OR_Success: {
3646 // We found a built-in operator or an overloaded operator.
3647 FunctionDecl *FnDecl = Best->Function;
3648
3649 if (FnDecl) {
3650 // We matched an overloaded operator. Build a call to that
3651 // operator.
3652
3653 // Convert the arguments.
3654 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3655 if (PerformObjectArgumentInitialization(Input, Method))
3656 return true;
3657 } else {
3658 // Convert the arguments.
3659 if (PerformCopyInitialization(Input,
3660 FnDecl->getParamDecl(0)->getType(),
3661 "passing"))
3662 return true;
3663 }
3664
3665 // Determine the result type
3666 QualType ResultTy
3667 = FnDecl->getType()->getAsFunctionType()->getResultType();
3668 ResultTy = ResultTy.getNonReferenceType();
3669
3670 // Build the actual expression node.
3671 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3672 SourceLocation());
3673 UsualUnaryConversions(FnExpr);
3674
3675 return new CXXOperatorCallExpr(FnExpr, &Input, 1, ResultTy, OpLoc);
3676 } else {
3677 // We matched a built-in operator. Convert the arguments, then
3678 // break out so that we will build the appropriate built-in
3679 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003680 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3681 Best->Conversions[0], "passing"))
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003682 return true;
3683
3684 break;
3685 }
3686 }
3687
3688 case OR_No_Viable_Function:
3689 // No viable function; fall through to handling this as a
3690 // built-in operator, which will produce an error message for us.
3691 break;
3692
3693 case OR_Ambiguous:
3694 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3695 << UnaryOperator::getOpcodeStr(Opc)
3696 << Input->getSourceRange();
3697 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3698 return true;
3699 }
3700
3701 // Either we found no viable overloaded operator or we matched a
3702 // built-in operator. In either case, fall through to trying to
3703 // build a built-in operation.
3704 }
3705
Chris Lattner4b009652007-07-25 00:24:17 +00003706 QualType resultType;
3707 switch (Opc) {
3708 default:
3709 assert(0 && "Unimplemented unary expr!");
3710 case UnaryOperator::PreInc:
3711 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003712 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3713 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00003714 break;
3715 case UnaryOperator::AddrOf:
3716 resultType = CheckAddressOfOperand(Input, OpLoc);
3717 break;
3718 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00003719 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00003720 resultType = CheckIndirectionOperand(Input, OpLoc);
3721 break;
3722 case UnaryOperator::Plus:
3723 case UnaryOperator::Minus:
3724 UsualUnaryConversions(Input);
3725 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003726 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3727 break;
3728 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3729 resultType->isEnumeralType())
3730 break;
3731 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3732 Opc == UnaryOperator::Plus &&
3733 resultType->isPointerType())
3734 break;
3735
Chris Lattner77d52da2008-11-20 06:06:08 +00003736 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003737 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003738 case UnaryOperator::Not: // bitwise complement
3739 UsualUnaryConversions(Input);
3740 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00003741 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3742 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3743 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00003744 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003745 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00003746 else if (!resultType->isIntegerType())
Chris Lattner77d52da2008-11-20 06:06:08 +00003747 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003748 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003749 break;
3750 case UnaryOperator::LNot: // logical negation
3751 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
3752 DefaultFunctionArrayConversion(Input);
3753 resultType = Input->getType();
3754 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Chris Lattner77d52da2008-11-20 06:06:08 +00003755 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003756 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003757 // LNot always has type int. C99 6.5.3.3p5.
3758 resultType = Context.IntTy;
3759 break;
Chris Lattner03931a72007-08-24 21:16:53 +00003760 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00003761 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00003762 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00003763 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003764 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00003765 resultType = Input->getType();
3766 break;
3767 }
3768 if (resultType.isNull())
3769 return true;
3770 return new UnaryOperator(Input, Opc, resultType, OpLoc);
3771}
3772
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003773/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3774Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00003775 SourceLocation LabLoc,
3776 IdentifierInfo *LabelII) {
3777 // Look up the record for this label identifier.
3778 LabelStmt *&LabelDecl = LabelMap[LabelII];
3779
Daniel Dunbar879788d2008-08-04 16:51:22 +00003780 // If we haven't seen this label yet, create a forward reference. It
3781 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00003782 if (LabelDecl == 0)
3783 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
3784
3785 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00003786 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3787 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00003788}
3789
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003790Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00003791 SourceLocation RPLoc) { // "({..})"
3792 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3793 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3794 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3795
3796 // FIXME: there are a variety of strange constraints to enforce here, for
3797 // example, it is not possible to goto into a stmt expression apparently.
3798 // More semantic analysis is needed.
3799
3800 // FIXME: the last statement in the compount stmt has its value used. We
3801 // should not warn about it being unused.
3802
3803 // If there are sub stmts in the compound stmt, take the type of the last one
3804 // as the type of the stmtexpr.
3805 QualType Ty = Context.VoidTy;
3806
Chris Lattner200964f2008-07-26 19:51:01 +00003807 if (!Compound->body_empty()) {
3808 Stmt *LastStmt = Compound->body_back();
3809 // If LastStmt is a label, skip down through into the body.
3810 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3811 LastStmt = Label->getSubStmt();
3812
3813 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00003814 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00003815 }
Chris Lattner4b009652007-07-25 00:24:17 +00003816
3817 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
3818}
Steve Naroff63bad2d2007-08-01 22:05:33 +00003819
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003820Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
3821 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003822 SourceLocation TypeLoc,
3823 TypeTy *argty,
3824 OffsetOfComponent *CompPtr,
3825 unsigned NumComponents,
3826 SourceLocation RPLoc) {
3827 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3828 assert(!ArgTy.isNull() && "Missing type argument!");
3829
3830 // We must have at least one component that refers to the type, and the first
3831 // one is known to be a field designator. Verify that the ArgTy represents
3832 // a struct/union/class.
3833 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00003834 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003835
3836 // Otherwise, create a compound literal expression as the base, and
3837 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00003838 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003839
Chris Lattnerb37522e2007-08-31 21:49:13 +00003840 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3841 // GCC extension, diagnose them.
3842 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003843 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3844 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00003845
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003846 for (unsigned i = 0; i != NumComponents; ++i) {
3847 const OffsetOfComponent &OC = CompPtr[i];
3848 if (OC.isBrackets) {
3849 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00003850 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003851 if (!AT) {
3852 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003853 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003854 }
3855
Chris Lattner2af6a802007-08-30 17:59:59 +00003856 // FIXME: C++: Verify that operator[] isn't overloaded.
3857
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003858 // C99 6.5.2.1p1
3859 Expr *Idx = static_cast<Expr*>(OC.U.E);
3860 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00003861 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
3862 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003863
3864 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3865 continue;
3866 }
3867
3868 const RecordType *RC = Res->getType()->getAsRecordType();
3869 if (!RC) {
3870 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003871 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003872 }
3873
3874 // Get the decl corresponding to this.
3875 RecordDecl *RD = RC->getDecl();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003876 FieldDecl *MemberDecl
3877 = dyn_cast_or_null<FieldDecl>(LookupDecl(OC.U.IdentInfo,
3878 Decl::IDNS_Ordinary,
Douglas Gregor78d70132009-01-14 22:20:51 +00003879 S, RD, false, false).getAsDecl());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003880 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00003881 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
3882 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00003883
3884 // FIXME: C++: Verify that MemberDecl isn't a static field.
3885 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00003886 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3887 // matter here.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003888 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3889 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003890 }
3891
3892 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3893 BuiltinLoc);
3894}
3895
3896
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003897Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00003898 TypeTy *arg1, TypeTy *arg2,
3899 SourceLocation RPLoc) {
3900 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3901 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3902
3903 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3904
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003905 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00003906}
3907
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003908Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00003909 ExprTy *expr1, ExprTy *expr2,
3910 SourceLocation RPLoc) {
3911 Expr *CondExpr = static_cast<Expr*>(cond);
3912 Expr *LHSExpr = static_cast<Expr*>(expr1);
3913 Expr *RHSExpr = static_cast<Expr*>(expr2);
3914
3915 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3916
3917 // The conditional expression is required to be a constant expression.
3918 llvm::APSInt condEval(32);
3919 SourceLocation ExpLoc;
3920 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003921 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
3922 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00003923
3924 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3925 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3926 RHSExpr->getType();
3927 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3928}
3929
Steve Naroff52a81c02008-09-03 18:15:37 +00003930//===----------------------------------------------------------------------===//
3931// Clang Extensions.
3932//===----------------------------------------------------------------------===//
3933
3934/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00003935void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003936 // Analyze block parameters.
3937 BlockSemaInfo *BSI = new BlockSemaInfo();
3938
3939 // Add BSI to CurBlock.
3940 BSI->PrevBlockInfo = CurBlock;
3941 CurBlock = BSI;
3942
3943 BSI->ReturnType = 0;
3944 BSI->TheScope = BlockScope;
3945
Steve Naroff52059382008-10-10 01:28:17 +00003946 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00003947 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00003948}
3949
3950void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003951 // Analyze arguments to block.
3952 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3953 "Not a function declarator!");
3954 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3955
Steve Naroff52059382008-10-10 01:28:17 +00003956 CurBlock->hasPrototype = FTI.hasPrototype;
3957 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00003958
3959 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3960 // no arguments, not a function that takes a single void argument.
3961 if (FTI.hasPrototype &&
3962 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3963 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3964 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3965 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00003966 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00003967 } else if (FTI.hasPrototype) {
3968 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00003969 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3970 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00003971 }
Steve Naroff52059382008-10-10 01:28:17 +00003972 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3973
3974 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3975 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3976 // If this has an identifier, add it to the scope stack.
3977 if ((*AI)->getIdentifier())
3978 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00003979}
3980
3981/// ActOnBlockError - If there is an error parsing a block, this callback
3982/// is invoked to pop the information about the block from the action impl.
3983void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3984 // Ensure that CurBlock is deleted.
3985 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3986
3987 // Pop off CurBlock, handle nested blocks.
3988 CurBlock = CurBlock->PrevBlockInfo;
3989
3990 // FIXME: Delete the ParmVarDecl objects as well???
3991
3992}
3993
3994/// ActOnBlockStmtExpr - This is called when the body of a block statement
3995/// literal was successfully completed. ^(int x){...}
3996Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3997 Scope *CurScope) {
3998 // Ensure that CurBlock is deleted.
3999 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
4000 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
4001
Steve Naroff52059382008-10-10 01:28:17 +00004002 PopDeclContext();
4003
Steve Naroff52a81c02008-09-03 18:15:37 +00004004 // Pop off CurBlock, handle nested blocks.
4005 CurBlock = CurBlock->PrevBlockInfo;
4006
4007 QualType RetTy = Context.VoidTy;
4008 if (BSI->ReturnType)
4009 RetTy = QualType(BSI->ReturnType, 0);
4010
4011 llvm::SmallVector<QualType, 8> ArgTypes;
4012 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4013 ArgTypes.push_back(BSI->Params[i]->getType());
4014
4015 QualType BlockTy;
4016 if (!BSI->hasPrototype)
4017 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4018 else
4019 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004020 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00004021
4022 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00004023
Steve Naroff95029d92008-10-08 18:44:00 +00004024 BSI->TheDecl->setBody(Body.take());
4025 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004026}
4027
Nate Begemanbd881ef2008-01-30 20:50:20 +00004028/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004029/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00004030/// The number of arguments has already been validated to match the number of
4031/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004032static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4033 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004034 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00004035 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004036 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4037 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00004038
4039 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004040 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00004041 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004042 return true;
4043}
4044
4045Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4046 SourceLocation *CommaLocs,
4047 SourceLocation BuiltinLoc,
4048 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004049 // __builtin_overload requires at least 2 arguments
4050 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004051 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4052 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004053
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004054 // The first argument is required to be a constant expression. It tells us
4055 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00004056 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004057 Expr *NParamsExpr = Args[0];
4058 llvm::APSInt constEval(32);
4059 SourceLocation ExpLoc;
4060 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004061 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4062 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004063
4064 // Verify that the number of parameters is > 0
4065 unsigned NumParams = constEval.getZExtValue();
4066 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004067 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4068 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004069 // Verify that we have at least 1 + NumParams arguments to the builtin.
4070 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004071 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4072 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004073
4074 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00004075 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00004076 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004077 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4078 // UsualUnaryConversions will convert the function DeclRefExpr into a
4079 // pointer to function.
4080 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004081 const FunctionTypeProto *FnType = 0;
4082 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4083 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004084
4085 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4086 // parameters, and the number of parameters must match the value passed to
4087 // the builtin.
4088 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004089 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4090 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004091
4092 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00004093 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004094 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004095 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004096 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004097 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4098 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00004099 // Remember our match, and continue processing the remaining arguments
4100 // to catch any errors.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004101 OE = new OverloadExpr(Args, NumArgs, i,
4102 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00004103 BuiltinLoc, RParenLoc);
4104 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004105 }
Nate Begemanc6078c92008-01-31 05:38:29 +00004106 // Return the newly created OverloadExpr node, if we succeded in matching
4107 // exactly one of the candidate functions.
4108 if (OE)
4109 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004110
4111 // If we didn't find a matching function Expr in the __builtin_overload list
4112 // the return an error.
4113 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00004114 for (unsigned i = 0; i != NumParams; ++i) {
4115 if (i != 0) typeNames += ", ";
4116 typeNames += Args[i+1]->getType().getAsString();
4117 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004118
Chris Lattner77d52da2008-11-20 06:06:08 +00004119 return Diag(BuiltinLoc, diag::err_overload_no_match)
4120 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004121}
4122
Anders Carlsson36760332007-10-15 20:28:48 +00004123Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4124 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004125 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004126 Expr *E = static_cast<Expr*>(expr);
4127 QualType T = QualType::getFromOpaquePtr(type);
4128
4129 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004130
4131 // Get the va_list type
4132 QualType VaListType = Context.getBuiltinVaListType();
4133 // Deal with implicit array decay; for example, on x86-64,
4134 // va_list is an array, but it's supposed to decay to
4135 // a pointer for va_arg.
4136 if (VaListType->isArrayType())
4137 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004138 // Make sure the input expression also decays appropriately.
4139 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004140
4141 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004142 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004143 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004144 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00004145
4146 // FIXME: Warn if a non-POD type is passed in.
4147
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004148 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004149}
4150
Douglas Gregorad4b3792008-11-29 04:51:27 +00004151Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4152 // The type of __null will be int or long, depending on the size of
4153 // pointers on the target.
4154 QualType Ty;
4155 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4156 Ty = Context.IntTy;
4157 else
4158 Ty = Context.LongTy;
4159
4160 return new GNUNullExpr(Ty, TokenLoc);
4161}
4162
Chris Lattner005ed752008-01-04 18:04:52 +00004163bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4164 SourceLocation Loc,
4165 QualType DstType, QualType SrcType,
4166 Expr *SrcExpr, const char *Flavor) {
4167 // Decode the result (notice that AST's are still created for extensions).
4168 bool isInvalid = false;
4169 unsigned DiagKind;
4170 switch (ConvTy) {
4171 default: assert(0 && "Unknown conversion type");
4172 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004173 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004174 DiagKind = diag::ext_typecheck_convert_pointer_int;
4175 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004176 case IntToPointer:
4177 DiagKind = diag::ext_typecheck_convert_int_pointer;
4178 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004179 case IncompatiblePointer:
4180 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4181 break;
4182 case FunctionVoidPointer:
4183 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4184 break;
4185 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004186 // If the qualifiers lost were because we were applying the
4187 // (deprecated) C++ conversion from a string literal to a char*
4188 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4189 // Ideally, this check would be performed in
4190 // CheckPointerTypesForAssignment. However, that would require a
4191 // bit of refactoring (so that the second argument is an
4192 // expression, rather than a type), which should be done as part
4193 // of a larger effort to fix CheckPointerTypesForAssignment for
4194 // C++ semantics.
4195 if (getLangOptions().CPlusPlus &&
4196 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4197 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004198 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4199 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004200 case IntToBlockPointer:
4201 DiagKind = diag::err_int_to_block_pointer;
4202 break;
4203 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004204 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004205 break;
Steve Naroff19608432008-10-14 22:18:38 +00004206 case IncompatibleObjCQualifiedId:
4207 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4208 // it can give a more specific diagnostic.
4209 DiagKind = diag::warn_incompatible_qualified_id;
4210 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004211 case Incompatible:
4212 DiagKind = diag::err_typecheck_convert_incompatible;
4213 isInvalid = true;
4214 break;
4215 }
4216
Chris Lattner271d4c22008-11-24 05:29:24 +00004217 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4218 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004219 return isInvalid;
4220}
Anders Carlssond5201b92008-11-30 19:50:32 +00004221
4222bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4223{
4224 Expr::EvalResult EvalResult;
4225
4226 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4227 EvalResult.HasSideEffects) {
4228 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4229
4230 if (EvalResult.Diag) {
4231 // We only show the note if it's not the usual "invalid subexpression"
4232 // or if it's actually in a subexpression.
4233 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4234 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4235 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4236 }
4237
4238 return true;
4239 }
4240
4241 if (EvalResult.Diag) {
4242 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4243 E->getSourceRange();
4244
4245 // Print the reason it's not a constant.
4246 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4247 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4248 }
4249
4250 if (Result)
4251 *Result = EvalResult.Val.getInt();
4252 return false;
4253}