blob: 820326f77a6e9c7c2f8af2fd1627c6c2c9843a42 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
Chris Lattner299b8842008-07-25 21:10:04 +000029//===----------------------------------------------------------------------===//
30// Standard Promotions and Conversions
31//===----------------------------------------------------------------------===//
32
Chris Lattner299b8842008-07-25 21:10:04 +000033/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
34void Sema::DefaultFunctionArrayConversion(Expr *&E) {
35 QualType Ty = E->getType();
36 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
37
Chris Lattner299b8842008-07-25 21:10:04 +000038 if (Ty->isFunctionType())
39 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +000040 else if (Ty->isArrayType()) {
41 // In C90 mode, arrays only promote to pointers if the array expression is
42 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
43 // type 'array of type' is converted to an expression that has type 'pointer
44 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
45 // that has type 'array of type' ...". The relevant change is "an lvalue"
46 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +000047 //
48 // C++ 4.2p1:
49 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
50 // T" can be converted to an rvalue of type "pointer to T".
51 //
52 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
53 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +000054 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
55 }
Chris Lattner299b8842008-07-25 21:10:04 +000056}
57
58/// UsualUnaryConversions - Performs various conversions that are common to most
59/// operators (C99 6.3). The conversions of array and function types are
60/// sometimes surpressed. For example, the array->pointer conversion doesn't
61/// apply if the array is an argument to the sizeof or address (&) operators.
62/// In these instances, this routine should *not* be called.
63Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
64 QualType Ty = Expr->getType();
65 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
66
Chris Lattner299b8842008-07-25 21:10:04 +000067 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
68 ImpCastExprToType(Expr, Context.IntTy);
69 else
70 DefaultFunctionArrayConversion(Expr);
71
72 return Expr;
73}
74
Chris Lattner9305c3d2008-07-25 22:25:12 +000075/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
76/// do not have a prototype. Arguments that have type float are promoted to
77/// double. All other argument types are converted by UsualUnaryConversions().
78void Sema::DefaultArgumentPromotion(Expr *&Expr) {
79 QualType Ty = Expr->getType();
80 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
81
82 // If this is a 'float' (CVR qualified or typedef) promote to double.
83 if (const BuiltinType *BT = Ty->getAsBuiltinType())
84 if (BT->getKind() == BuiltinType::Float)
85 return ImpCastExprToType(Expr, Context.DoubleTy);
86
87 UsualUnaryConversions(Expr);
88}
89
Anders Carlsson4b8e38c2009-01-16 16:48:51 +000090// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
91// will warn if the resulting type is not a POD type.
92void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT)
93
94{
95 DefaultArgumentPromotion(Expr);
96
97 if (!Expr->getType()->isPODType()) {
98 Diag(Expr->getLocStart(),
99 diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
100 Expr->getType() << CT;
101 }
102}
103
104
Chris Lattner299b8842008-07-25 21:10:04 +0000105/// UsualArithmeticConversions - Performs various conversions that are common to
106/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
107/// routine returns the first non-arithmetic type found. The client is
108/// responsible for emitting appropriate error diagnostics.
109/// FIXME: verify the conversion rules for "complex int" are consistent with
110/// GCC.
111QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
112 bool isCompAssign) {
113 if (!isCompAssign) {
114 UsualUnaryConversions(lhsExpr);
115 UsualUnaryConversions(rhsExpr);
116 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000117
Chris Lattner299b8842008-07-25 21:10:04 +0000118 // For conversion purposes, we ignore any qualifiers.
119 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000120 QualType lhs =
121 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
122 QualType rhs =
123 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000124
125 // If both types are identical, no conversion is needed.
126 if (lhs == rhs)
127 return lhs;
128
129 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
130 // The caller can deal with this (e.g. pointer + int).
131 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
132 return lhs;
133
134 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
135 if (!isCompAssign) {
136 ImpCastExprToType(lhsExpr, destType);
137 ImpCastExprToType(rhsExpr, destType);
138 }
139 return destType;
140}
141
142QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
143 // Perform the usual unary conversions. We do this early so that
144 // integral promotions to "int" can allow us to exit early, in the
145 // lhs == rhs check. Also, for conversion purposes, we ignore any
146 // qualifiers. For example, "const float" and "float" are
147 // equivalent.
Douglas Gregor3d4492e2008-11-13 20:12:29 +0000148 if (lhs->isPromotableIntegerType()) lhs = Context.IntTy;
149 else lhs = lhs.getUnqualifiedType();
150 if (rhs->isPromotableIntegerType()) rhs = Context.IntTy;
151 else rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000152
Chris Lattner299b8842008-07-25 21:10:04 +0000153 // If both types are identical, no conversion is needed.
154 if (lhs == rhs)
155 return lhs;
156
157 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
158 // The caller can deal with this (e.g. pointer + int).
159 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
160 return lhs;
161
162 // At this point, we have two different arithmetic types.
163
164 // Handle complex types first (C99 6.3.1.8p1).
165 if (lhs->isComplexType() || rhs->isComplexType()) {
166 // if we have an integer operand, the result is the complex type.
167 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
168 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000169 return lhs;
170 }
171 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
172 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000173 return rhs;
174 }
175 // This handles complex/complex, complex/float, or float/complex.
176 // When both operands are complex, the shorter operand is converted to the
177 // type of the longer, and that is the type of the result. This corresponds
178 // to what is done when combining two real floating-point operands.
179 // The fun begins when size promotion occur across type domains.
180 // From H&S 6.3.4: When one operand is complex and the other is a real
181 // floating-point type, the less precise type is converted, within it's
182 // real or complex domain, to the precision of the other type. For example,
183 // when combining a "long double" with a "double _Complex", the
184 // "double _Complex" is promoted to "long double _Complex".
185 int result = Context.getFloatingTypeOrder(lhs, rhs);
186
187 if (result > 0) { // The left side is bigger, convert rhs.
188 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000189 } else if (result < 0) { // The right side is bigger, convert lhs.
190 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000191 }
192 // At this point, lhs and rhs have the same rank/size. Now, make sure the
193 // domains match. This is a requirement for our implementation, C99
194 // does not require this promotion.
195 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
196 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000197 return rhs;
198 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000199 return lhs;
200 }
201 }
202 return lhs; // The domain/size match exactly.
203 }
204 // Now handle "real" floating types (i.e. float, double, long double).
205 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
206 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000207 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000208 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000209 return lhs;
210 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000211 if (rhs->isComplexIntegerType()) {
212 // convert rhs to the complex floating point type.
213 return Context.getComplexType(lhs);
214 }
215 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000216 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000217 return rhs;
218 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000219 if (lhs->isComplexIntegerType()) {
220 // convert lhs to the complex floating point type.
221 return Context.getComplexType(rhs);
222 }
Chris Lattner299b8842008-07-25 21:10:04 +0000223 // We have two real floating types, float/complex combos were handled above.
224 // Convert the smaller operand to the bigger result.
225 int result = Context.getFloatingTypeOrder(lhs, rhs);
226
227 if (result > 0) { // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000228 return lhs;
229 }
230 if (result < 0) { // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000231 return rhs;
232 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000233 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
Chris Lattner299b8842008-07-25 21:10:04 +0000234 }
235 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
236 // Handle GCC complex int extension.
237 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
238 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
239
240 if (lhsComplexInt && rhsComplexInt) {
241 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
242 rhsComplexInt->getElementType()) >= 0) {
243 // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000244 return lhs;
245 }
Chris Lattner299b8842008-07-25 21:10:04 +0000246 return rhs;
247 } else if (lhsComplexInt && rhs->isIntegerType()) {
248 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000249 return lhs;
250 } else if (rhsComplexInt && lhs->isIntegerType()) {
251 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000252 return rhs;
253 }
254 }
255 // Finally, we have two differing integer types.
256 // The rules for this case are in C99 6.3.1.8
257 int compare = Context.getIntegerTypeOrder(lhs, rhs);
258 bool lhsSigned = lhs->isSignedIntegerType(),
259 rhsSigned = rhs->isSignedIntegerType();
260 QualType destType;
261 if (lhsSigned == rhsSigned) {
262 // Same signedness; use the higher-ranked type
263 destType = compare >= 0 ? lhs : rhs;
264 } else if (compare != (lhsSigned ? 1 : -1)) {
265 // The unsigned type has greater than or equal rank to the
266 // signed type, so use the unsigned type
267 destType = lhsSigned ? rhs : lhs;
268 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
269 // The two types are different widths; if we are here, that
270 // means the signed type is larger than the unsigned type, so
271 // use the signed type.
272 destType = lhsSigned ? lhs : rhs;
273 } else {
274 // The signed type is higher-ranked than the unsigned type,
275 // but isn't actually any bigger (like unsigned int and long
276 // on most 32-bit systems). Use the unsigned type corresponding
277 // to the signed type.
278 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
279 }
Chris Lattner299b8842008-07-25 21:10:04 +0000280 return destType;
281}
282
283//===----------------------------------------------------------------------===//
284// Semantic Analysis for various Expression Types
285//===----------------------------------------------------------------------===//
286
287
Steve Naroff87d58b42007-09-16 03:34:24 +0000288/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000289/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
290/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
291/// multiple tokens. However, the common case is that StringToks points to one
292/// string.
293///
294Action::ExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000295Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000296 assert(NumStringToks && "Must have at least one string!");
297
298 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
299 if (Literal.hadError)
300 return ExprResult(true);
301
302 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
303 for (unsigned i = 0; i != NumStringToks; ++i)
304 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000305
306 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000307 if (Literal.Pascal && Literal.GetStringLength() > 256)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000308 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long)
309 << SourceRange(StringToks[0].getLocation(),
310 StringToks[NumStringToks-1].getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000311
Chris Lattnera6dcce32008-02-11 00:02:17 +0000312 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000313 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000314 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000315
316 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
317 if (getLangOptions().CPlusPlus)
318 StrTy.addConst();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000319
320 // Get an array type for the string, according to C99 6.4.5. This includes
321 // the nul terminator character as well as the string length for pascal
322 // strings.
323 StrTy = Context.getConstantArrayType(StrTy,
324 llvm::APInt(32, Literal.GetStringLength()+1),
325 ArrayType::Normal, 0);
326
Chris Lattner4b009652007-07-25 00:24:17 +0000327 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
328 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000329 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000330 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000331 StringToks[NumStringToks-1].getLocation());
332}
333
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000334/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
335/// CurBlock to VD should cause it to be snapshotted (as we do for auto
336/// variables defined outside the block) or false if this is not needed (e.g.
337/// for values inside the block or for globals).
338///
339/// FIXME: This will create BlockDeclRefExprs for global variables,
340/// function references, etc which is suboptimal :) and breaks
341/// things like "integer constant expression" tests.
342static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
343 ValueDecl *VD) {
344 // If the value is defined inside the block, we couldn't snapshot it even if
345 // we wanted to.
346 if (CurBlock->TheDecl == VD->getDeclContext())
347 return false;
348
349 // If this is an enum constant or function, it is constant, don't snapshot.
350 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
351 return false;
352
353 // If this is a reference to an extern, static, or global variable, no need to
354 // snapshot it.
355 // FIXME: What about 'const' variables in C++?
356 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
357 return Var->hasLocalStorage();
358
359 return true;
360}
361
362
363
Steve Naroff0acc9c92007-09-15 18:49:24 +0000364/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000365/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000366/// identifier is used in a function call context.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000367/// LookupCtx is only used for a C++ qualified-id (foo::bar) to indicate the
368/// class or namespace that the identifier must be a member of.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000369Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000370 IdentifierInfo &II,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000371 bool HasTrailingLParen,
372 const CXXScopeSpec *SS) {
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000373 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS);
374}
375
Douglas Gregor566782a2009-01-06 05:10:23 +0000376/// BuildDeclRefExpr - Build either a DeclRefExpr or a
377/// QualifiedDeclRefExpr based on whether or not SS is a
378/// nested-name-specifier.
379DeclRefExpr *Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
380 bool TypeDependent, bool ValueDependent,
381 const CXXScopeSpec *SS) {
382 if (SS && !SS->isEmpty())
383 return new QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent,
384 SS->getRange().getBegin());
385 else
386 return new DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
387}
388
Douglas Gregor723d3332009-01-07 00:43:41 +0000389/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
390/// variable corresponding to the anonymous union or struct whose type
391/// is Record.
392static ScopedDecl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
393 assert(Record->isAnonymousStructOrUnion() &&
394 "Record must be an anonymous struct or union!");
395
396 // FIXME: Once ScopedDecls are directly linked together, this will
397 // be an O(1) operation rather than a slow walk through DeclContext's
398 // vector (which itself will be eliminated). DeclGroups might make
399 // this even better.
400 DeclContext *Ctx = Record->getDeclContext();
401 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
402 DEnd = Ctx->decls_end();
403 D != DEnd; ++D) {
404 if (*D == Record) {
405 // The object for the anonymous struct/union directly
406 // follows its type in the list of declarations.
407 ++D;
408 assert(D != DEnd && "Missing object for anonymous record");
409 assert(!cast<ScopedDecl>(*D)->getDeclName() && "Decl should be unnamed");
410 return *D;
411 }
412 }
413
414 assert(false && "Missing object for anonymous record");
415 return 0;
416}
417
418Sema::ExprResult
419Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
420 FieldDecl *Field,
421 Expr *BaseObjectExpr,
422 SourceLocation OpLoc) {
423 assert(Field->getDeclContext()->isRecord() &&
424 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
425 && "Field must be stored inside an anonymous struct or union");
426
427 // Construct the sequence of field member references
428 // we'll have to perform to get to the field in the anonymous
429 // union/struct. The list of members is built from the field
430 // outward, so traverse it backwards to go from an object in
431 // the current context to the field we found.
432 llvm::SmallVector<FieldDecl *, 4> AnonFields;
433 AnonFields.push_back(Field);
434 VarDecl *BaseObject = 0;
435 DeclContext *Ctx = Field->getDeclContext();
436 do {
437 RecordDecl *Record = cast<RecordDecl>(Ctx);
438 ScopedDecl *AnonObject = getObjectForAnonymousRecordDecl(Record);
439 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
440 AnonFields.push_back(AnonField);
441 else {
442 BaseObject = cast<VarDecl>(AnonObject);
443 break;
444 }
445 Ctx = Ctx->getParent();
446 } while (Ctx->isRecord() &&
447 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
448
449 // Build the expression that refers to the base object, from
450 // which we will build a sequence of member references to each
451 // of the anonymous union objects and, eventually, the field we
452 // found via name lookup.
453 bool BaseObjectIsPointer = false;
454 unsigned ExtraQuals = 0;
455 if (BaseObject) {
456 // BaseObject is an anonymous struct/union variable (and is,
457 // therefore, not part of another non-anonymous record).
458 delete BaseObjectExpr;
459
460 BaseObjectExpr = new DeclRefExpr(BaseObject, BaseObject->getType(),
461 SourceLocation());
462 ExtraQuals
463 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
464 } else if (BaseObjectExpr) {
465 // The caller provided the base object expression. Determine
466 // whether its a pointer and whether it adds any qualifiers to the
467 // anonymous struct/union fields we're looking into.
468 QualType ObjectType = BaseObjectExpr->getType();
469 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
470 BaseObjectIsPointer = true;
471 ObjectType = ObjectPtr->getPointeeType();
472 }
473 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
474 } else {
475 // We've found a member of an anonymous struct/union that is
476 // inside a non-anonymous struct/union, so in a well-formed
477 // program our base object expression is "this".
478 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
479 if (!MD->isStatic()) {
480 QualType AnonFieldType
481 = Context.getTagDeclType(
482 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
483 QualType ThisType = Context.getTagDeclType(MD->getParent());
484 if ((Context.getCanonicalType(AnonFieldType)
485 == Context.getCanonicalType(ThisType)) ||
486 IsDerivedFrom(ThisType, AnonFieldType)) {
487 // Our base object expression is "this".
488 BaseObjectExpr = new CXXThisExpr(SourceLocation(),
489 MD->getThisType(Context));
490 BaseObjectIsPointer = true;
491 }
492 } else {
493 return Diag(Loc, diag::err_invalid_member_use_in_static_method)
494 << Field->getDeclName();
495 }
496 ExtraQuals = MD->getTypeQualifiers();
497 }
498
499 if (!BaseObjectExpr)
500 return Diag(Loc, diag::err_invalid_non_static_member_use)
501 << Field->getDeclName();
502 }
503
504 // Build the implicit member references to the field of the
505 // anonymous struct/union.
506 Expr *Result = BaseObjectExpr;
507 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
508 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
509 FI != FIEnd; ++FI) {
510 QualType MemberType = (*FI)->getType();
511 if (!(*FI)->isMutable()) {
512 unsigned combinedQualifiers
513 = MemberType.getCVRQualifiers() | ExtraQuals;
514 MemberType = MemberType.getQualifiedType(combinedQualifiers);
515 }
516 Result = new MemberExpr(Result, BaseObjectIsPointer, *FI,
517 OpLoc, MemberType);
518 BaseObjectIsPointer = false;
519 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
520 OpLoc = SourceLocation();
521 }
522
523 return Result;
524}
525
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000526/// ActOnDeclarationNameExpr - The parser has read some kind of name
527/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
528/// performs lookup on that name and returns an expression that refers
529/// to that name. This routine isn't directly called from the parser,
530/// because the parser doesn't know about DeclarationName. Rather,
531/// this routine is called by ActOnIdentifierExpr,
532/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
533/// which form the DeclarationName from the corresponding syntactic
534/// forms.
535///
536/// HasTrailingLParen indicates whether this identifier is used in a
537/// function call context. LookupCtx is only used for a C++
538/// qualified-id (foo::bar) to indicate the class or namespace that
539/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000540///
541/// If ForceResolution is true, then we will attempt to resolve the
542/// name even if it looks like a dependent name. This option is off by
543/// default.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000544Sema::ExprResult Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
545 DeclarationName Name,
546 bool HasTrailingLParen,
Douglas Gregora133e262008-12-06 00:22:45 +0000547 const CXXScopeSpec *SS,
548 bool ForceResolution) {
549 if (S->getTemplateParamParent() && Name.getAsIdentifierInfo() &&
550 HasTrailingLParen && !SS && !ForceResolution) {
551 // We've seen something of the form
552 // identifier(
553 // and we are in a template, so it is likely that 's' is a
554 // dependent name. However, we won't know until we've parsed all
555 // of the call arguments. So, build a CXXDependentNameExpr node
556 // to represent this name. Then, if it turns out that none of the
557 // arguments are type-dependent, we'll force the resolution of the
558 // dependent name at that point.
559 return new CXXDependentNameExpr(Name.getAsIdentifierInfo(),
560 Context.DependentTy, Loc);
561 }
562
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000563 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000564 Decl *D = 0;
565 LookupResult Lookup;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000566 if (SS && !SS->isEmpty()) {
567 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
568 if (DC == 0)
569 return true;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000570 Lookup = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000571 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000572 Lookup = LookupDecl(Name, Decl::IDNS_Ordinary, S);
573
574 if (Lookup.isAmbiguous())
575 return DiagnoseAmbiguousLookup(Lookup, Name, Loc,
576 SS && SS->isSet()? SS->getRange()
577 : SourceRange());
578 else
579 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000580
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000581 // If this reference is in an Objective-C method, then ivar lookup happens as
582 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000583 IdentifierInfo *II = Name.getAsIdentifierInfo();
584 if (II && getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000585 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000586 // There are two cases to handle here. 1) scoped lookup could have failed,
587 // in which case we should look for an ivar. 2) scoped lookup could have
588 // found a decl, but that decl is outside the current method (i.e. a global
589 // variable). In these two cases, we do a lookup for an ivar with this
590 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000591 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000592 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000593 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000594 // FIXME: This should use a new expr for a direct reference, don't turn
595 // this into Self->ivar, just return a BareIVarExpr or something.
596 IdentifierInfo &II = Context.Idents.get("self");
597 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000598 ObjCIvarRefExpr *MRef= new ObjCIvarRefExpr(IV, IV->getType(), Loc,
599 static_cast<Expr*>(SelfExpr.Val), true, true);
600 Context.setFieldDecl(IFace, IV, MRef);
601 return MRef;
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000602 }
603 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000604 // Needed to implement property "super.method" notation.
Chris Lattner87fada82008-11-20 05:35:30 +0000605 if (SD == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000606 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000607 getCurMethodDecl()->getClassInterface()));
Douglas Gregord8606632008-11-04 14:56:14 +0000608 return new ObjCSuperExpr(Loc, T);
Steve Naroff6f786252008-06-02 23:03:37 +0000609 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000610 }
Chris Lattner4b009652007-07-25 00:24:17 +0000611 if (D == 0) {
612 // Otherwise, this could be an implicitly declared function reference (legal
613 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000614 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000615 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000616 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000617 else {
618 // If this name wasn't predeclared and if this is not a function call,
619 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000620 if (SS && !SS->isEmpty())
Chris Lattner77d52da2008-11-20 06:06:08 +0000621 return Diag(Loc, diag::err_typecheck_no_member)
Chris Lattnerb1753422008-11-23 21:45:46 +0000622 << Name << SS->getRange();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000623 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
624 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000625 return Diag(Loc, diag::err_undeclared_use) << Name.getAsString();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000626 else
Chris Lattnerb1753422008-11-23 21:45:46 +0000627 return Diag(Loc, diag::err_undeclared_var_use) << Name;
Chris Lattner4b009652007-07-25 00:24:17 +0000628 }
629 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000630
631 // We may have found a field within an anonymous union or struct
632 // (C++ [class.union]).
633 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
634 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
635 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000636
Douglas Gregor3257fb52008-12-22 05:46:06 +0000637 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
638 if (!MD->isStatic()) {
639 // C++ [class.mfct.nonstatic]p2:
640 // [...] if name lookup (3.4.1) resolves the name in the
641 // id-expression to a nonstatic nontype member of class X or of
642 // a base class of X, the id-expression is transformed into a
643 // class member access expression (5.2.5) using (*this) (9.3.2)
644 // as the postfix-expression to the left of the '.' operator.
645 DeclContext *Ctx = 0;
646 QualType MemberType;
647 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
648 Ctx = FD->getDeclContext();
649 MemberType = FD->getType();
650
651 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
652 MemberType = RefType->getPointeeType();
653 else if (!FD->isMutable()) {
654 unsigned combinedQualifiers
655 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
656 MemberType = MemberType.getQualifiedType(combinedQualifiers);
657 }
658 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
659 if (!Method->isStatic()) {
660 Ctx = Method->getParent();
661 MemberType = Method->getType();
662 }
663 } else if (OverloadedFunctionDecl *Ovl
664 = dyn_cast<OverloadedFunctionDecl>(D)) {
665 for (OverloadedFunctionDecl::function_iterator
666 Func = Ovl->function_begin(),
667 FuncEnd = Ovl->function_end();
668 Func != FuncEnd; ++Func) {
669 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
670 if (!DMethod->isStatic()) {
671 Ctx = Ovl->getDeclContext();
672 MemberType = Context.OverloadTy;
673 break;
674 }
675 }
676 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000677
678 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000679 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
680 QualType ThisType = Context.getTagDeclType(MD->getParent());
681 if ((Context.getCanonicalType(CtxType)
682 == Context.getCanonicalType(ThisType)) ||
683 IsDerivedFrom(ThisType, CtxType)) {
684 // Build the implicit member access expression.
685 Expr *This = new CXXThisExpr(SourceLocation(),
686 MD->getThisType(Context));
687 return new MemberExpr(This, true, cast<NamedDecl>(D),
688 SourceLocation(), MemberType);
689 }
690 }
691 }
692 }
693
Douglas Gregor8acb7272008-12-11 16:49:14 +0000694 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000695 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
696 if (MD->isStatic())
697 // "invalid use of member 'x' in static member function"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000698 return Diag(Loc, diag::err_invalid_member_use_in_static_method)
Chris Lattner271d4c22008-11-24 05:29:24 +0000699 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000700 }
701
Douglas Gregor3257fb52008-12-22 05:46:06 +0000702 // Any other ways we could have found the field in a well-formed
703 // program would have been turned into implicit member expressions
704 // above.
Chris Lattner271d4c22008-11-24 05:29:24 +0000705 return Diag(Loc, diag::err_invalid_non_static_member_use)
706 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000707 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000708
Chris Lattner4b009652007-07-25 00:24:17 +0000709 if (isa<TypedefDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000710 return Diag(Loc, diag::err_unexpected_typedef) << Name;
Ted Kremenek42730c52008-01-07 19:49:32 +0000711 if (isa<ObjCInterfaceDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000712 return Diag(Loc, diag::err_unexpected_interface) << Name;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000713 if (isa<NamespaceDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000714 return Diag(Loc, diag::err_unexpected_namespace) << Name;
Chris Lattner4b009652007-07-25 00:24:17 +0000715
Steve Naroffd6163f32008-09-05 22:11:13 +0000716 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000717 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Douglas Gregor566782a2009-01-06 05:10:23 +0000718 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc, false, false, SS);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000719
Steve Naroffd6163f32008-09-05 22:11:13 +0000720 ValueDecl *VD = cast<ValueDecl>(D);
721
722 // check if referencing an identifier with __attribute__((deprecated)).
723 if (VD->getAttr<DeprecatedAttr>())
Chris Lattner271d4c22008-11-24 05:29:24 +0000724 Diag(Loc, diag::warn_deprecated) << VD->getDeclName();
Douglas Gregor48840c72008-12-10 23:01:14 +0000725
726 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
727 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
728 Scope *CheckS = S;
729 while (CheckS) {
730 if (CheckS->isWithinElse() &&
731 CheckS->getControlParent()->isDeclScope(Var)) {
732 if (Var->getType()->isBooleanType())
733 Diag(Loc, diag::warn_value_always_false) << Var->getDeclName();
734 else
735 Diag(Loc, diag::warn_value_always_zero) << Var->getDeclName();
736 break;
737 }
738
739 // Move up one more control parent to check again.
740 CheckS = CheckS->getControlParent();
741 if (CheckS)
742 CheckS = CheckS->getParent();
743 }
744 }
745 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000746
747 // Only create DeclRefExpr's for valid Decl's.
748 if (VD->isInvalidDecl())
749 return true;
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000750
751 // If the identifier reference is inside a block, and it refers to a value
752 // that is outside the block, create a BlockDeclRefExpr instead of a
753 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
754 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000755 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000756 // We do not do this for things like enum constants, global variables, etc,
757 // as they do not get snapshotted.
758 //
759 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000760 // The BlocksAttr indicates the variable is bound by-reference.
761 if (VD->getAttr<BlocksAttr>())
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000762 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
763 Loc, true);
Steve Naroff52059382008-10-10 01:28:17 +0000764
765 // Variable will be bound by-copy, make it const within the closure.
766 VD->getType().addConst();
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000767 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
768 Loc, false);
Steve Naroff52059382008-10-10 01:28:17 +0000769 }
770 // If this reference is not in a block or if the referenced variable is
771 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000772
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000773 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000774 bool ValueDependent = false;
775 if (getLangOptions().CPlusPlus) {
776 // C++ [temp.dep.expr]p3:
777 // An id-expression is type-dependent if it contains:
778 // - an identifier that was declared with a dependent type,
779 if (VD->getType()->isDependentType())
780 TypeDependent = true;
781 // - FIXME: a template-id that is dependent,
782 // - a conversion-function-id that specifies a dependent type,
783 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
784 Name.getCXXNameType()->isDependentType())
785 TypeDependent = true;
786 // - a nested-name-specifier that contains a class-name that
787 // names a dependent type.
788 else if (SS && !SS->isEmpty()) {
789 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
790 DC; DC = DC->getParent()) {
791 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000792 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000793 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
794 if (Context.getTypeDeclType(Record)->isDependentType()) {
795 TypeDependent = true;
796 break;
797 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000798 }
799 }
800 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000801
Douglas Gregora5d84612008-12-10 20:57:37 +0000802 // C++ [temp.dep.constexpr]p2:
803 //
804 // An identifier is value-dependent if it is:
805 // - a name declared with a dependent type,
806 if (TypeDependent)
807 ValueDependent = true;
808 // - the name of a non-type template parameter,
809 else if (isa<NonTypeTemplateParmDecl>(VD))
810 ValueDependent = true;
811 // - a constant with integral or enumeration type and is
812 // initialized with an expression that is value-dependent
813 // (FIXME!).
814 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000815
Douglas Gregor566782a2009-01-06 05:10:23 +0000816 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
817 TypeDependent, ValueDependent, SS);
Chris Lattner4b009652007-07-25 00:24:17 +0000818}
819
Chris Lattner69909292008-08-10 01:53:14 +0000820Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000821 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000822 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000823
824 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000825 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000826 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
827 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
828 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000829 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000830
Chris Lattner7e637512008-01-12 08:14:25 +0000831 // Pre-defined identifiers are of type char[x], where x is the length of the
832 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000833 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000834 if (FunctionDecl *FD = getCurFunctionDecl())
835 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000836 else if (ObjCMethodDecl *MD = getCurMethodDecl())
837 Length = MD->getSynthesizedMethodSize();
838 else {
839 Diag(Loc, diag::ext_predef_outside_function);
840 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
841 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
842 }
843
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000844
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000845 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000846 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000847 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000848 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000849}
850
Steve Naroff87d58b42007-09-16 03:34:24 +0000851Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000852 llvm::SmallString<16> CharBuffer;
853 CharBuffer.resize(Tok.getLength());
854 const char *ThisTokBegin = &CharBuffer[0];
855 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
856
857 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
858 Tok.getLocation(), PP);
859 if (Literal.hadError())
860 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000861
862 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
863
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000864 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
865 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000866}
867
Steve Naroff87d58b42007-09-16 03:34:24 +0000868Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattnerfd5f1432009-01-16 07:10:29 +0000869 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +0000870 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
871 if (Tok.getLength() == 1) {
Chris Lattnerfd5f1432009-01-16 07:10:29 +0000872 const char Val = PP.getSpelledCharacterAt(Tok.getLocation());
873 unsigned IntSize = Context.Target.getIntWidth();
874 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000875 Context.IntTy,
876 Tok.getLocation()));
877 }
Ted Kremenekdbde2282009-01-13 23:19:12 +0000878
Chris Lattner4b009652007-07-25 00:24:17 +0000879 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000880 // Add padding so that NumericLiteralParser can overread by one character.
881 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000882 const char *ThisTokBegin = &IntegerBuffer[0];
883
884 // Get the spelling of the token, which eliminates trigraphs, etc.
885 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner2e6b4bf2008-09-30 20:51:14 +0000886
Chris Lattner4b009652007-07-25 00:24:17 +0000887 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
888 Tok.getLocation(), PP);
889 if (Literal.hadError)
890 return ExprResult(true);
891
Chris Lattner1de66eb2007-08-26 03:42:43 +0000892 Expr *Res;
893
894 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000895 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000896 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000897 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000898 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000899 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000900 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000901 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000902
903 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
904
Ted Kremenekddedbe22007-11-29 00:56:49 +0000905 // isExact will be set by GetFloatValue().
906 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000907 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000908 Ty, Tok.getLocation());
909
Chris Lattner1de66eb2007-08-26 03:42:43 +0000910 } else if (!Literal.isIntegerLiteral()) {
911 return ExprResult(true);
912 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000913 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000914
Neil Booth7421e9c2007-08-29 22:00:19 +0000915 // long long is a C99 feature.
916 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000917 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000918 Diag(Tok.getLocation(), diag::ext_longlong);
919
Chris Lattner4b009652007-07-25 00:24:17 +0000920 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000921 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000922
923 if (Literal.GetIntegerValue(ResultVal)) {
924 // If this value didn't fit into uintmax_t, warn and force to ull.
925 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000926 Ty = Context.UnsignedLongLongTy;
927 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000928 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000929 } else {
930 // If this value fits into a ULL, try to figure out what else it fits into
931 // according to the rules of C99 6.4.4.1p5.
932
933 // Octal, Hexadecimal, and integers with a U suffix are allowed to
934 // be an unsigned int.
935 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
936
937 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000938 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000939 if (!Literal.isLong && !Literal.isLongLong) {
940 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000941 unsigned IntSize = Context.Target.getIntWidth();
942
Chris Lattner4b009652007-07-25 00:24:17 +0000943 // Does it fit in a unsigned int?
944 if (ResultVal.isIntN(IntSize)) {
945 // Does it fit in a signed int?
946 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000947 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000948 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000949 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000950 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000951 }
Chris Lattner4b009652007-07-25 00:24:17 +0000952 }
953
954 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000955 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000956 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000957
958 // Does it fit in a unsigned long?
959 if (ResultVal.isIntN(LongSize)) {
960 // Does it fit in a signed long?
961 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000962 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000963 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000964 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000965 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000966 }
Chris Lattner4b009652007-07-25 00:24:17 +0000967 }
968
969 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000970 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000971 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000972
973 // Does it fit in a unsigned long long?
974 if (ResultVal.isIntN(LongLongSize)) {
975 // Does it fit in a signed long long?
976 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000977 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000978 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000979 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000980 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000981 }
982 }
983
984 // If we still couldn't decide a type, we probably have something that
985 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000986 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000987 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000988 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000989 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000990 }
Chris Lattnere4068872008-05-09 05:59:00 +0000991
992 if (ResultVal.getBitWidth() != Width)
993 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000994 }
995
Chris Lattner48d7f382008-04-02 04:24:33 +0000996 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000997 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000998
999 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1000 if (Literal.isImaginary)
1001 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
1002
1003 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +00001004}
1005
Steve Naroff87d58b42007-09-16 03:34:24 +00001006Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +00001007 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +00001008 Expr *E = (Expr *)Val;
1009 assert((E != 0) && "ActOnParenExpr() missing expr");
1010 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +00001011}
1012
1013/// The UsualUnaryConversions() function is *not* called by this routine.
1014/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001015bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1016 SourceLocation OpLoc,
1017 const SourceRange &ExprRange,
1018 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +00001019 // C99 6.5.3.4p1:
1020 if (isa<FunctionType>(exprType) && isSizeof)
1021 // alignof(function) is allowed.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001022 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
Chris Lattner4b009652007-07-25 00:24:17 +00001023 else if (exprType->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001024 Diag(OpLoc, diag::ext_sizeof_void_type)
1025 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
1026 else if (exprType->isIncompleteType())
1027 return Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
1028 diag::err_alignof_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001029 << exprType << ExprRange;
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001030
1031 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001032}
1033
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001034/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1035/// the same for @c alignof and @c __alignof
1036/// Note that the ArgRange is invalid if isType is false.
1037Action::ExprResult
1038Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1039 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001040 // If error parsing type, ignore.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001041 if (TyOrEx == 0) return true;
Chris Lattner4b009652007-07-25 00:24:17 +00001042
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001043 QualType ArgTy;
1044 SourceRange Range;
1045 if (isType) {
1046 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1047 Range = ArgRange;
1048 } else {
1049 // Get the end location.
1050 Expr *ArgEx = (Expr *)TyOrEx;
1051 Range = ArgEx->getSourceRange();
1052 ArgTy = ArgEx->getType();
1053 }
1054
1055 // Verify that the operand is valid.
1056 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Chris Lattner4b009652007-07-25 00:24:17 +00001057 return true;
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001058
1059 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1060 return new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, Context.getSizeType(),
1061 OpLoc, Range.getEnd());
Chris Lattner4b009652007-07-25 00:24:17 +00001062}
1063
Chris Lattner5110ad52007-08-24 21:41:10 +00001064QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +00001065 DefaultFunctionArrayConversion(V);
1066
Chris Lattnera16e42d2007-08-26 05:39:26 +00001067 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001068 if (const ComplexType *CT = V->getType()->getAsComplexType())
1069 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001070
1071 // Otherwise they pass through real integer and floating point types here.
1072 if (V->getType()->isArithmeticType())
1073 return V->getType();
1074
1075 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +00001076 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001077 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001078}
1079
1080
Chris Lattner4b009652007-07-25 00:24:17 +00001081
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001082Action::ExprResult Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001083 tok::TokenKind Kind,
1084 ExprTy *Input) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001085 Expr *Arg = (Expr *)Input;
1086
Chris Lattner4b009652007-07-25 00:24:17 +00001087 UnaryOperator::Opcode Opc;
1088 switch (Kind) {
1089 default: assert(0 && "Unknown unary op!");
1090 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1091 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1092 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001093
1094 if (getLangOptions().CPlusPlus &&
1095 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1096 // Which overloaded operator?
1097 OverloadedOperatorKind OverOp =
1098 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1099
1100 // C++ [over.inc]p1:
1101 //
1102 // [...] If the function is a member function with one
1103 // parameter (which shall be of type int) or a non-member
1104 // function with two parameters (the second of which shall be
1105 // of type int), it defines the postfix increment operator ++
1106 // for objects of that type. When the postfix increment is
1107 // called as a result of using the ++ operator, the int
1108 // argument will have value zero.
1109 Expr *Args[2] = {
1110 Arg,
1111 new IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1112 /*isSigned=*/true),
1113 Context.IntTy, SourceLocation())
1114 };
1115
1116 // Build the candidate set for overloading
1117 OverloadCandidateSet CandidateSet;
1118 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
1119
1120 // Perform overload resolution.
1121 OverloadCandidateSet::iterator Best;
1122 switch (BestViableFunction(CandidateSet, Best)) {
1123 case OR_Success: {
1124 // We found a built-in operator or an overloaded operator.
1125 FunctionDecl *FnDecl = Best->Function;
1126
1127 if (FnDecl) {
1128 // We matched an overloaded operator. Build a call to that
1129 // operator.
1130
1131 // Convert the arguments.
1132 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1133 if (PerformObjectArgumentInitialization(Arg, Method))
1134 return true;
1135 } else {
1136 // Convert the arguments.
1137 if (PerformCopyInitialization(Arg,
1138 FnDecl->getParamDecl(0)->getType(),
1139 "passing"))
1140 return true;
1141 }
1142
1143 // Determine the result type
1144 QualType ResultTy
1145 = FnDecl->getType()->getAsFunctionType()->getResultType();
1146 ResultTy = ResultTy.getNonReferenceType();
1147
1148 // Build the actual expression node.
1149 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
1150 SourceLocation());
1151 UsualUnaryConversions(FnExpr);
1152
1153 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, OpLoc);
1154 } else {
1155 // We matched a built-in operator. Convert the arguments, then
1156 // break out so that we will build the appropriate built-in
1157 // operator node.
1158 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1159 "passing"))
1160 return true;
1161
1162 break;
1163 }
1164 }
1165
1166 case OR_No_Viable_Function:
1167 // No viable function; fall through to handling this as a
1168 // built-in operator, which will produce an error message for us.
1169 break;
1170
1171 case OR_Ambiguous:
1172 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1173 << UnaryOperator::getOpcodeStr(Opc)
1174 << Arg->getSourceRange();
1175 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1176 return true;
1177 }
1178
1179 // Either we found no viable overloaded operator or we matched a
1180 // built-in operator. In either case, fall through to trying to
1181 // build a built-in operation.
1182 }
1183
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001184 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1185 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001186 if (result.isNull())
1187 return true;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001188 return new UnaryOperator(Arg, Opc, result, OpLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001189}
1190
1191Action::ExprResult Sema::
Douglas Gregor80723c52008-11-19 17:17:41 +00001192ActOnArraySubscriptExpr(Scope *S, ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001193 ExprTy *Idx, SourceLocation RLoc) {
1194 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
1195
Douglas Gregor80723c52008-11-19 17:17:41 +00001196 if (getLangOptions().CPlusPlus &&
Eli Friedmane658bf52008-12-15 22:34:21 +00001197 (LHSExp->getType()->isRecordType() ||
1198 LHSExp->getType()->isEnumeralType() ||
1199 RHSExp->getType()->isRecordType() ||
1200 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001201 // Add the appropriate overloaded operators (C++ [over.match.oper])
1202 // to the candidate set.
1203 OverloadCandidateSet CandidateSet;
1204 Expr *Args[2] = { LHSExp, RHSExp };
1205 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
1206
1207 // Perform overload resolution.
1208 OverloadCandidateSet::iterator Best;
1209 switch (BestViableFunction(CandidateSet, Best)) {
1210 case OR_Success: {
1211 // We found a built-in operator or an overloaded operator.
1212 FunctionDecl *FnDecl = Best->Function;
1213
1214 if (FnDecl) {
1215 // We matched an overloaded operator. Build a call to that
1216 // operator.
1217
1218 // Convert the arguments.
1219 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1220 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1221 PerformCopyInitialization(RHSExp,
1222 FnDecl->getParamDecl(0)->getType(),
1223 "passing"))
1224 return true;
1225 } else {
1226 // Convert the arguments.
1227 if (PerformCopyInitialization(LHSExp,
1228 FnDecl->getParamDecl(0)->getType(),
1229 "passing") ||
1230 PerformCopyInitialization(RHSExp,
1231 FnDecl->getParamDecl(1)->getType(),
1232 "passing"))
1233 return true;
1234 }
1235
1236 // Determine the result type
1237 QualType ResultTy
1238 = FnDecl->getType()->getAsFunctionType()->getResultType();
1239 ResultTy = ResultTy.getNonReferenceType();
1240
1241 // Build the actual expression node.
1242 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
1243 SourceLocation());
1244 UsualUnaryConversions(FnExpr);
1245
1246 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, LLoc);
1247 } else {
1248 // We matched a built-in operator. Convert the arguments, then
1249 // break out so that we will build the appropriate built-in
1250 // operator node.
1251 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1252 "passing") ||
1253 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1254 "passing"))
1255 return true;
1256
1257 break;
1258 }
1259 }
1260
1261 case OR_No_Viable_Function:
1262 // No viable function; fall through to handling this as a
1263 // built-in operator, which will produce an error message for us.
1264 break;
1265
1266 case OR_Ambiguous:
1267 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1268 << "[]"
1269 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1270 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1271 return true;
1272 }
1273
1274 // Either we found no viable overloaded operator or we matched a
1275 // built-in operator. In either case, fall through to trying to
1276 // build a built-in operation.
1277 }
1278
Chris Lattner4b009652007-07-25 00:24:17 +00001279 // Perform default conversions.
1280 DefaultFunctionArrayConversion(LHSExp);
1281 DefaultFunctionArrayConversion(RHSExp);
1282
1283 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1284
1285 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001286 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001287 // in the subscript position. As a result, we need to derive the array base
1288 // and index from the expression types.
1289 Expr *BaseExpr, *IndexExpr;
1290 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001291 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001292 BaseExpr = LHSExp;
1293 IndexExpr = RHSExp;
1294 // FIXME: need to deal with const...
1295 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001296 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001297 // Handle the uncommon case of "123[Ptr]".
1298 BaseExpr = RHSExp;
1299 IndexExpr = LHSExp;
1300 // FIXME: need to deal with const...
1301 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001302 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1303 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001304 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +00001305
1306 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +00001307 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1308 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner8ba580c2008-11-19 05:08:23 +00001309 return Diag(LLoc, diag::err_ext_vector_component_access)
1310 << SourceRange(LLoc, RLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001311 // FIXME: need to deal with const...
1312 ResultType = VTy->getElementType();
1313 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001314 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value)
1315 << RHSExp->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001316 }
1317 // C99 6.5.2.1p1
1318 if (!IndexExpr->getType()->isIntegerType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001319 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript)
1320 << IndexExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001321
1322 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1323 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001324 // void (*)(int)) and pointers to incomplete types. Functions are not
1325 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001326 if (!ResultType->isObjectType())
1327 return Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001328 diag::err_typecheck_subscript_not_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001329 << BaseExpr->getType() << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001330
1331 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
1332}
1333
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001334QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001335CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001336 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001337 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001338
1339 // This flag determines whether or not the component is to be treated as a
1340 // special name, or a regular GLSL-style component access.
1341 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001342
1343 // The vector accessor can't exceed the number of elements.
1344 const char *compStr = CompName.getName();
1345 if (strlen(compStr) > vecType->getNumElements()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001346 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001347 << baseType << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001348 return QualType();
1349 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001350
1351 // Check that we've found one of the special components, or that the component
1352 // names must come from the same set.
1353 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1354 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
1355 SpecialComponent = true;
1356 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001357 do
1358 compStr++;
1359 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1360 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
1361 do
1362 compStr++;
1363 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
1364 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
1365 do
1366 compStr++;
1367 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
1368 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001369
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 the component names
1372 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001373 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1374 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001375 return QualType();
1376 }
1377 // Each component accessor can't exceed the vector type.
1378 compStr = CompName.getName();
1379 while (*compStr) {
1380 if (vecType->isAccessorWithinNumElements(*compStr))
1381 compStr++;
1382 else
1383 break;
1384 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001385 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001386 // We didn't get to the end of the string. This means a component accessor
1387 // exceeds the number of elements in the vector.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001388 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001389 << baseType << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001390 return QualType();
1391 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001392
1393 // If we have a special component name, verify that the current vector length
1394 // is an even number, since all special component names return exactly half
1395 // the elements.
1396 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001397 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001398 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001399 return QualType();
1400 }
1401
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001402 // The component accessor looks fine - now we need to compute the actual type.
1403 // The vector type is implied by the component accessor. For example,
1404 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001405 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1406 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
Chris Lattner65cae292008-11-19 08:23:25 +00001407 : CompName.getLength();
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001408 if (CompSize == 1)
1409 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001410
Nate Begemanaf6ed502008-04-18 23:10:10 +00001411 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001412 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001413 // diagostics look bad. We want extended vector types to appear built-in.
1414 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1415 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1416 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001417 }
1418 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001419}
1420
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001421/// constructSetterName - Return the setter name for the given
1422/// identifier, i.e. "set" + Name where the initial character of Name
1423/// has been capitalized.
1424// FIXME: Merge with same routine in Parser. But where should this
1425// live?
1426static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1427 const IdentifierInfo *Name) {
1428 llvm::SmallString<100> SelectorName;
1429 SelectorName = "set";
1430 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1431 SelectorName[3] = toupper(SelectorName[3]);
1432 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1433}
1434
Chris Lattner4b009652007-07-25 00:24:17 +00001435Action::ExprResult Sema::
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001436ActOnMemberReferenceExpr(Scope *S, ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001437 tok::TokenKind OpKind, SourceLocation MemberLoc,
1438 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001439 Expr *BaseExpr = static_cast<Expr *>(Base);
1440 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001441
1442 // Perform default conversions.
1443 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +00001444
Steve Naroff2cb66382007-07-26 03:11:44 +00001445 QualType BaseType = BaseExpr->getType();
1446 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001447
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001448 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1449 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001450 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001451 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001452 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001453 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001454 return BuildOverloadedArrowExpr(S, BaseExpr, OpLoc, MemberLoc, Member);
Steve Naroff2cb66382007-07-26 03:11:44 +00001455 else
Chris Lattner8ba580c2008-11-19 05:08:23 +00001456 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001457 << BaseType << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001458 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001459
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001460 // Handle field access to simple records. This also handles access to fields
1461 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001462 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001463 RecordDecl *RDecl = RTy->getDecl();
1464 if (RTy->isIncompleteType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001465 return Diag(OpLoc, diag::err_typecheck_incomplete_tag)
Chris Lattner271d4c22008-11-24 05:29:24 +00001466 << RDecl->getDeclName() << BaseExpr->getSourceRange();
Steve Naroff2cb66382007-07-26 03:11:44 +00001467 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001468 // FIXME: Qualified name lookup for C++ is a bit more complicated
1469 // than this.
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001470 LookupResult Result
1471 = LookupQualifiedName(RDecl, DeclarationName(&Member),
1472 LookupCriteria(LookupCriteria::Member,
1473 /*RedeclarationOnly=*/false,
1474 getLangOptions().CPlusPlus));
1475
1476 Decl *MemberDecl = 0;
1477 if (!Result)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001478 return Diag(MemberLoc, diag::err_typecheck_no_member)
Chris Lattner65cae292008-11-19 08:23:25 +00001479 << &Member << BaseExpr->getSourceRange();
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001480 else if (Result.isAmbiguous())
1481 return DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1482 MemberLoc, BaseExpr->getSourceRange());
1483 else
1484 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001485
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001486 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001487 // We may have found a field within an anonymous union or struct
1488 // (C++ [class.union]).
1489 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
1490 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
1491 BaseExpr, OpLoc);
1492
Douglas Gregor82d44772008-12-20 23:49:58 +00001493 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1494 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001495 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001496 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1497 MemberType = Ref->getPointeeType();
1498 else {
1499 unsigned combinedQualifiers =
1500 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001501 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001502 combinedQualifiers &= ~QualType::Const;
1503 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1504 }
Eli Friedman76b49832008-02-06 22:48:16 +00001505
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001506 return new MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
Douglas Gregor82d44772008-12-20 23:49:58 +00001507 MemberLoc, MemberType);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001508 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001509 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Var, MemberLoc,
1510 Var->getType().getNonReferenceType());
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001511 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001512 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberFn, MemberLoc,
1513 MemberFn->getType());
1514 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001515 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001516 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl, MemberLoc,
1517 Context.OverloadTy);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001518 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001519 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Enum, MemberLoc,
1520 Enum->getType());
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001521 else if (isa<TypeDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001522 return Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1523 << DeclarationName(&Member) << int(OpKind == tok::arrow);
Eli Friedman76b49832008-02-06 22:48:16 +00001524
Douglas Gregor82d44772008-12-20 23:49:58 +00001525 // We found a declaration kind that we didn't expect. This is a
1526 // generic error message that tells the user that she can't refer
1527 // to this member with '.' or '->'.
1528 return Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1529 << DeclarationName(&Member) << int(OpKind == tok::arrow);
Chris Lattnera57cf472008-07-21 04:28:12 +00001530 }
1531
Chris Lattnere9d71612008-07-21 04:59:05 +00001532 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1533 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001534 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001535 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Fariborz Jahanianea944842008-12-18 17:29:46 +00001536 ObjCIvarRefExpr *MRef= new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc,
1537 BaseExpr,
1538 OpKind == tok::arrow);
1539 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
1540 return MRef;
Fariborz Jahanian09772392008-12-13 22:20:28 +00001541 }
Chris Lattner8ba580c2008-11-19 05:08:23 +00001542 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Chris Lattner271d4c22008-11-24 05:29:24 +00001543 << IFTy->getDecl()->getDeclName() << &Member
Chris Lattner8ba580c2008-11-19 05:08:23 +00001544 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001545 }
1546
Chris Lattnere9d71612008-07-21 04:59:05 +00001547 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1548 // pointer to a (potentially qualified) interface type.
1549 const PointerType *PTy;
1550 const ObjCInterfaceType *IFTy;
1551 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1552 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1553 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001554
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001555 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001556 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
1557 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1558
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001559 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001560 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1561 E = IFTy->qual_end(); I != E; ++I)
1562 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1563 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001564
1565 // If that failed, look for an "implicit" property by seeing if the nullary
1566 // selector is implemented.
1567
1568 // FIXME: The logic for looking up nullary and unary selectors should be
1569 // shared with the code in ActOnInstanceMessage.
1570
1571 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1572 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1573
1574 // If this reference is in an @implementation, check for 'private' methods.
1575 if (!Getter)
1576 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1577 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1578 if (ObjCImplementationDecl *ImpDecl =
1579 ObjCImplementations[ClassDecl->getIdentifier()])
1580 Getter = ImpDecl->getInstanceMethod(Sel);
1581
Steve Naroff04151f32008-10-22 19:16:27 +00001582 // Look through local category implementations associated with the class.
1583 if (!Getter) {
1584 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1585 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1586 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1587 }
1588 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001589 if (Getter) {
1590 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001591 // will look for the matching setter, in case it is needed.
1592 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1593 &Member);
1594 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1595 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1596 if (!Setter) {
1597 // If this reference is in an @implementation, also check for 'private'
1598 // methods.
1599 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1600 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1601 if (ObjCImplementationDecl *ImpDecl =
1602 ObjCImplementations[ClassDecl->getIdentifier()])
1603 Setter = ImpDecl->getInstanceMethod(SetterSel);
1604 }
1605 // Look through local category implementations associated with the class.
1606 if (!Setter) {
1607 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1608 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1609 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1610 }
1611 }
1612
1613 // FIXME: we must check that the setter has property type.
1614 return new ObjCKVCRefExpr(Getter, Getter->getResultType(), Setter,
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00001615 MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001616 }
Anders Carlsson96095fc2008-12-19 17:27:57 +00001617
1618 return Diag(MemberLoc, diag::err_property_not_found) <<
1619 &Member << BaseType;
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001620 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001621 // Handle properties on qualified "id" protocols.
1622 const ObjCQualifiedIdType *QIdTy;
1623 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1624 // Check protocols on qualified interfaces.
1625 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001626 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroffd1d44402008-10-20 22:53:06 +00001627 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1628 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001629 // Also must look for a getter name which uses property syntax.
1630 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1631 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1632 return new ObjCMessageExpr(BaseExpr, Sel, OMD->getResultType(), OMD,
1633 OpLoc, MemberLoc, NULL, 0);
1634 }
1635 }
Anders Carlsson96095fc2008-12-19 17:27:57 +00001636
1637 return Diag(MemberLoc, diag::err_property_not_found) <<
1638 &Member << BaseType;
Steve Naroffd1d44402008-10-20 22:53:06 +00001639 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001640 // Handle 'field access' to vectors, such as 'V.xx'.
1641 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1642 // Component access limited to variables (reject vec4.rg.g).
1643 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1644 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner8ba580c2008-11-19 05:08:23 +00001645 return Diag(MemberLoc, diag::err_ext_vector_component_access)
1646 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001647 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1648 if (ret.isNull())
1649 return true;
1650 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1651 }
1652
Chris Lattner8ba580c2008-11-19 05:08:23 +00001653 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001654 << BaseType << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001655}
1656
Douglas Gregor3257fb52008-12-22 05:46:06 +00001657/// ConvertArgumentsForCall - Converts the arguments specified in
1658/// Args/NumArgs to the parameter types of the function FDecl with
1659/// function prototype Proto. Call is the call expression itself, and
1660/// Fn is the function expression. For a C++ member function, this
1661/// routine does not attempt to convert the object argument. Returns
1662/// true if the call is ill-formed.
1663bool
1664Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1665 FunctionDecl *FDecl,
1666 const FunctionTypeProto *Proto,
1667 Expr **Args, unsigned NumArgs,
1668 SourceLocation RParenLoc) {
1669 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1670 // assignment, to the types of the corresponding parameter, ...
1671 unsigned NumArgsInProto = Proto->getNumArgs();
1672 unsigned NumArgsToCheck = NumArgs;
1673
1674 // If too few arguments are available (and we don't have default
1675 // arguments for the remaining parameters), don't make the call.
1676 if (NumArgs < NumArgsInProto) {
1677 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1678 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1679 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1680 // Use default arguments for missing arguments
1681 NumArgsToCheck = NumArgsInProto;
1682 Call->setNumArgs(NumArgsInProto);
1683 }
1684
1685 // If too many are passed and not variadic, error on the extras and drop
1686 // them.
1687 if (NumArgs > NumArgsInProto) {
1688 if (!Proto->isVariadic()) {
1689 Diag(Args[NumArgsInProto]->getLocStart(),
1690 diag::err_typecheck_call_too_many_args)
1691 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1692 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1693 Args[NumArgs-1]->getLocEnd());
1694 // This deletes the extra arguments.
1695 Call->setNumArgs(NumArgsInProto);
1696 }
1697 NumArgsToCheck = NumArgsInProto;
1698 }
1699
1700 // Continue to check argument types (even if we have too few/many args).
1701 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1702 QualType ProtoArgType = Proto->getArgType(i);
1703
1704 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001705 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001706 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001707
1708 // Pass the argument.
1709 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1710 return true;
1711 } else
1712 // We already type-checked the argument, so we know it works.
Douglas Gregor3257fb52008-12-22 05:46:06 +00001713 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
1714 QualType ArgType = Arg->getType();
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001715
Douglas Gregor3257fb52008-12-22 05:46:06 +00001716 Call->setArg(i, Arg);
1717 }
1718
1719 // If this is a variadic call, handle args passed through "...".
1720 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001721 VariadicCallType CallType = VariadicFunction;
1722 if (Fn->getType()->isBlockPointerType())
1723 CallType = VariadicBlock; // Block
1724 else if (isa<MemberExpr>(Fn))
1725 CallType = VariadicMethod;
1726
Douglas Gregor3257fb52008-12-22 05:46:06 +00001727 // Promote the arguments (C99 6.5.2.2p7).
1728 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1729 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001730 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001731 Call->setArg(i, Arg);
1732 }
1733 }
1734
1735 return false;
1736}
1737
Steve Naroff87d58b42007-09-16 03:34:24 +00001738/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001739/// This provides the location of the left/right parens and a list of comma
1740/// locations.
Douglas Gregor3257fb52008-12-22 05:46:06 +00001741Action::ExprResult
1742Sema::ActOnCallExpr(Scope *S, ExprTy *fn, SourceLocation LParenLoc,
1743 ExprTy **args, unsigned NumArgs,
1744 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner4b009652007-07-25 00:24:17 +00001745 Expr *Fn = static_cast<Expr *>(fn);
1746 Expr **Args = reinterpret_cast<Expr**>(args);
1747 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001748 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001749 OverloadedFunctionDecl *Ovl = NULL;
1750
Douglas Gregora133e262008-12-06 00:22:45 +00001751 // Determine whether this is a dependent call inside a C++ template,
1752 // in which case we won't do any semantic analysis now.
1753 bool Dependent = false;
1754 if (Fn->isTypeDependent()) {
1755 if (CXXDependentNameExpr *FnName = dyn_cast<CXXDependentNameExpr>(Fn)) {
1756 if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1757 Dependent = true;
1758 else {
1759 // Resolve the CXXDependentNameExpr to an actual identifier;
1760 // it wasn't really a dependent name after all.
1761 ExprResult Resolved
1762 = ActOnDeclarationNameExpr(S, FnName->getLocation(), FnName->getName(),
1763 /*HasTrailingLParen=*/true,
1764 /*SS=*/0,
1765 /*ForceResolution=*/true);
1766 if (Resolved.isInvalid)
1767 return true;
1768 else {
1769 delete Fn;
1770 Fn = (Expr *)Resolved.Val;
1771 }
1772 }
1773 } else
1774 Dependent = true;
1775 } else
1776 Dependent = Expr::hasAnyTypeDependentArguments(Args, NumArgs);
1777
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001778 // FIXME: Will need to cache the results of name lookup (including
1779 // ADL) in Fn.
Douglas Gregora133e262008-12-06 00:22:45 +00001780 if (Dependent)
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001781 return new CallExpr(Fn, Args, NumArgs, Context.DependentTy, RParenLoc);
1782
Douglas Gregor3257fb52008-12-22 05:46:06 +00001783 // Determine whether this is a call to an object (C++ [over.call.object]).
1784 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
1785 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1786 CommaLocs, RParenLoc);
1787
1788 // Determine whether this is a call to a member function.
1789 if (getLangOptions().CPlusPlus) {
1790 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1791 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1792 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
1793 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1794 CommaLocs, RParenLoc);
1795 }
1796
Douglas Gregord2baafd2008-10-21 16:13:35 +00001797 // If we're directly calling a function or a set of overloaded
1798 // functions, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00001799 DeclRefExpr *DRExpr = NULL;
1800 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1801 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1802 else
1803 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1804
1805 if (DRExpr) {
1806 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1807 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
Douglas Gregord2baafd2008-10-21 16:13:35 +00001808 }
1809
Douglas Gregord2baafd2008-10-21 16:13:35 +00001810 if (Ovl) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001811 FDecl = ResolveOverloadedCallFn(Fn, Ovl, LParenLoc, Args, NumArgs, CommaLocs,
1812 RParenLoc);
1813 if (!FDecl)
Douglas Gregord2baafd2008-10-21 16:13:35 +00001814 return true;
1815
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001816 // Update Fn to refer to the actual function selected.
Douglas Gregor566782a2009-01-06 05:10:23 +00001817 Expr *NewFn = 0;
1818 if (QualifiedDeclRefExpr *QDRExpr = dyn_cast<QualifiedDeclRefExpr>(DRExpr))
1819 NewFn = new QualifiedDeclRefExpr(FDecl, FDecl->getType(),
1820 QDRExpr->getLocation(), false, false,
1821 QDRExpr->getSourceRange().getBegin());
1822 else
1823 NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1824 Fn->getSourceRange().getBegin());
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001825 Fn->Destroy(Context);
1826 Fn = NewFn;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001827 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001828
1829 // Promote the function operand.
1830 UsualUnaryConversions(Fn);
1831
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001832 // Make the call expr early, before semantic checks. This guarantees cleanup
1833 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +00001834 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001835 Context.BoolTy, RParenLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001836
Steve Naroffd6163f32008-09-05 22:11:13 +00001837 const FunctionType *FuncT;
1838 if (!Fn->getType()->isBlockPointerType()) {
1839 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1840 // have type pointer to function".
1841 const PointerType *PT = Fn->getType()->getAsPointerType();
1842 if (PT == 0)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001843 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001844 << Fn->getType() << Fn->getSourceRange();
Steve Naroffd6163f32008-09-05 22:11:13 +00001845 FuncT = PT->getPointeeType()->getAsFunctionType();
1846 } else { // This is a block call.
1847 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1848 getAsFunctionType();
1849 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001850 if (FuncT == 0)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001851 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001852 << Fn->getType() << Fn->getSourceRange();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001853
1854 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001855 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Chris Lattner4b009652007-07-25 00:24:17 +00001856
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001857 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001858 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
1859 RParenLoc))
1860 return true;
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001861 } else {
1862 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1863
Steve Naroffdb65e052007-08-28 23:30:39 +00001864 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001865 for (unsigned i = 0; i != NumArgs; i++) {
1866 Expr *Arg = Args[i];
1867 DefaultArgumentPromotion(Arg);
1868 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001869 }
Chris Lattner4b009652007-07-25 00:24:17 +00001870 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001871
Douglas Gregor3257fb52008-12-22 05:46:06 +00001872 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
1873 if (!Method->isStatic())
1874 return Diag(LParenLoc, diag::err_member_call_without_object)
1875 << Fn->getSourceRange();
1876
Chris Lattner2e64c072007-08-10 20:18:51 +00001877 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001878 if (FDecl)
1879 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001880
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001881 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001882}
1883
1884Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001885ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001886 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001887 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001888 QualType literalType = QualType::getFromOpaquePtr(Ty);
1889 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001890 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001891 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001892
Eli Friedman8c2173d2008-05-20 05:22:08 +00001893 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001894 if (literalType->isVariableArrayType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001895 return Diag(LParenLoc, diag::err_variable_object_no_init)
1896 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001897 } else if (literalType->isIncompleteType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001898 return Diag(LParenLoc, diag::err_typecheck_decl_incomplete_type)
Chris Lattner271d4c22008-11-24 05:29:24 +00001899 << literalType
Chris Lattner8ba580c2008-11-19 05:08:23 +00001900 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001901 }
1902
Douglas Gregor6428e762008-11-05 15:29:30 +00001903 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001904 DeclarationName(), /*FIXME:DirectInit=*/false))
Steve Naroff92590f92008-01-09 20:58:06 +00001905 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001906
Chris Lattnere5cb5862008-12-04 23:50:19 +00001907 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001908 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001909 if (CheckForConstantInitializer(literalExpr, literalType))
1910 return true;
1911 }
Chris Lattnerce236e72008-10-26 23:35:51 +00001912 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1913 isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001914}
1915
1916Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001917ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattnerce236e72008-10-26 23:35:51 +00001918 InitListDesignations &Designators,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001919 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001920 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001921
Steve Naroff0acc9c92007-09-15 18:49:24 +00001922 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001923 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001924
Chris Lattner71ca8c82008-10-26 23:43:26 +00001925 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1926 Designators.hasAnyDesignators());
Chris Lattner48d7f382008-04-02 04:24:33 +00001927 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1928 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001929}
1930
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001931/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001932bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001933 UsualUnaryConversions(castExpr);
1934
1935 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1936 // type needs to be scalar.
1937 if (castType->isVoidType()) {
1938 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001939 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
1940 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001941 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00001942 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
1943 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
1944 (castType->isStructureType() || castType->isUnionType())) {
1945 // GCC struct/union extension: allow cast to self.
1946 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
1947 << castType << castExpr->getSourceRange();
1948 } else if (castType->isUnionType()) {
1949 // GCC cast to union extension
1950 RecordDecl *RD = castType->getAsRecordType()->getDecl();
1951 RecordDecl::field_iterator Field, FieldEnd;
1952 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1953 Field != FieldEnd; ++Field) {
1954 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
1955 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
1956 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
1957 << castExpr->getSourceRange();
1958 break;
1959 }
1960 }
1961 if (Field == FieldEnd)
1962 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
1963 << castExpr->getType() << castExpr->getSourceRange();
1964 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001965 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001966 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001967 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001968 }
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001969 } else if (!castExpr->getType()->isScalarType() &&
1970 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001971 return Diag(castExpr->getLocStart(),
1972 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001973 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001974 } else if (castExpr->getType()->isVectorType()) {
1975 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1976 return true;
1977 } else if (castType->isVectorType()) {
1978 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1979 return true;
1980 }
1981 return false;
1982}
1983
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001984bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001985 assert(VectorTy->isVectorType() && "Not a vector type!");
1986
1987 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001988 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001989 return Diag(R.getBegin(),
1990 Ty->isVectorType() ?
1991 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00001992 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001993 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001994 } else
1995 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001996 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001997 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001998
1999 return false;
2000}
2001
Chris Lattner4b009652007-07-25 00:24:17 +00002002Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00002003ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00002004 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002005 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002006
2007 Expr *castExpr = static_cast<Expr*>(Op);
2008 QualType castType = QualType::getFromOpaquePtr(Ty);
2009
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002010 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
2011 return true;
Steve Naroff7f1412d2008-11-03 23:29:32 +00002012 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00002013}
2014
Chris Lattner98a425c2007-11-26 01:40:58 +00002015/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2016/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00002017inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
2018 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
2019 UsualUnaryConversions(cond);
2020 UsualUnaryConversions(lex);
2021 UsualUnaryConversions(rex);
2022 QualType condT = cond->getType();
2023 QualType lexT = lex->getType();
2024 QualType rexT = rex->getType();
2025
2026 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002027 if (!cond->isTypeDependent()) {
2028 if (!condT->isScalarType()) { // C99 6.5.15p2
2029 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
2030 return QualType();
2031 }
Chris Lattner4b009652007-07-25 00:24:17 +00002032 }
Chris Lattner992ae932008-01-06 22:42:25 +00002033
2034 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002035 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
2036 return Context.DependentTy;
2037
Chris Lattner992ae932008-01-06 22:42:25 +00002038 // If both operands have arithmetic type, do the usual arithmetic conversions
2039 // to find a common type: C99 6.5.15p3,5.
2040 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002041 UsualArithmeticConversions(lex, rex);
2042 return lex->getType();
2043 }
Chris Lattner992ae932008-01-06 22:42:25 +00002044
2045 // If both operands are the same structure or union type, the result is that
2046 // type.
Chris Lattner71225142007-07-31 21:27:01 +00002047 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00002048 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002049 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00002050 // "If both the operands have structure or union type, the result has
2051 // that type." This implies that CV qualifiers are dropped.
2052 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002053 }
Chris Lattner992ae932008-01-06 22:42:25 +00002054
2055 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002056 // The following || allows only one side to be void (a GCC-ism).
2057 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00002058 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002059 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2060 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00002061 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002062 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2063 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00002064 ImpCastExprToType(lex, Context.VoidTy);
2065 ImpCastExprToType(rex, Context.VoidTy);
2066 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002067 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002068 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2069 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002070 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2071 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002072 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002073 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002074 return lexT;
2075 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002076 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2077 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002078 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002079 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002080 return rexT;
2081 }
Chris Lattner0ac51632008-01-06 22:50:31 +00002082 // Handle the case where both operands are pointers before we handle null
2083 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00002084 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2085 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2086 // get the "pointed to" types
2087 QualType lhptee = LHSPT->getPointeeType();
2088 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002089
Chris Lattner71225142007-07-31 21:27:01 +00002090 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2091 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002092 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002093 // Figure out necessary qualifiers (C99 6.5.15p6)
2094 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002095 QualType destType = Context.getPointerType(destPointee);
2096 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2097 ImpCastExprToType(rex, destType); // promote to void*
2098 return destType;
2099 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002100 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002101 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002102 QualType destType = Context.getPointerType(destPointee);
2103 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2104 ImpCastExprToType(rex, destType); // promote to void*
2105 return destType;
2106 }
Chris Lattner4b009652007-07-25 00:24:17 +00002107
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002108 QualType compositeType = lexT;
2109
2110 // If either type is an Objective-C object type then check
2111 // compatibility according to Objective-C.
2112 if (Context.isObjCObjectPointerType(lexT) ||
2113 Context.isObjCObjectPointerType(rexT)) {
2114 // If both operands are interfaces and either operand can be
2115 // assigned to the other, use that type as the composite
2116 // type. This allows
2117 // xxx ? (A*) a : (B*) b
2118 // where B is a subclass of A.
2119 //
2120 // Additionally, as for assignment, if either type is 'id'
2121 // allow silent coercion. Finally, if the types are
2122 // incompatible then make sure to use 'id' as the composite
2123 // type so the result is acceptable for sending messages to.
2124
2125 // FIXME: This code should not be localized to here. Also this
2126 // should use a compatible check instead of abusing the
2127 // canAssignObjCInterfaces code.
2128 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2129 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2130 if (LHSIface && RHSIface &&
2131 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2132 compositeType = lexT;
2133 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002134 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002135 compositeType = rexT;
2136 } else if (Context.isObjCIdType(lhptee) ||
2137 Context.isObjCIdType(rhptee)) {
2138 // FIXME: This code looks wrong, because isObjCIdType checks
2139 // the struct but getObjCIdType returns the pointer to
2140 // struct. This is horrible and should be fixed.
2141 compositeType = Context.getObjCIdType();
2142 } else {
2143 QualType incompatTy = Context.getObjCIdType();
2144 ImpCastExprToType(lex, incompatTy);
2145 ImpCastExprToType(rex, incompatTy);
2146 return incompatTy;
2147 }
2148 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2149 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002150 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002151 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002152 // In this situation, we assume void* type. No especially good
2153 // reason, but this is what gcc does, and we do have to pick
2154 // to get a consistent AST.
2155 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002156 ImpCastExprToType(lex, incompatTy);
2157 ImpCastExprToType(rex, incompatTy);
2158 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002159 }
2160 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002161 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2162 // differently qualified versions of compatible types, the result type is
2163 // a pointer to an appropriately qualified version of the *composite*
2164 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002165 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002166 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00002167 ImpCastExprToType(lex, compositeType);
2168 ImpCastExprToType(rex, compositeType);
2169 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002170 }
Chris Lattner4b009652007-07-25 00:24:17 +00002171 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002172 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2173 // evaluates to "struct objc_object *" (and is handled above when comparing
2174 // id with statically typed objects).
2175 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2176 // GCC allows qualified id and any Objective-C type to devolve to
2177 // id. Currently localizing to here until clear this should be
2178 // part of ObjCQualifiedIdTypesAreCompatible.
2179 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2180 (lexT->isObjCQualifiedIdType() &&
2181 Context.isObjCObjectPointerType(rexT)) ||
2182 (rexT->isObjCQualifiedIdType() &&
2183 Context.isObjCObjectPointerType(lexT))) {
2184 // FIXME: This is not the correct composite type. This only
2185 // happens to work because id can more or less be used anywhere,
2186 // however this may change the type of method sends.
2187 // FIXME: gcc adds some type-checking of the arguments and emits
2188 // (confusing) incompatible comparison warnings in some
2189 // cases. Investigate.
2190 QualType compositeType = Context.getObjCIdType();
2191 ImpCastExprToType(lex, compositeType);
2192 ImpCastExprToType(rex, compositeType);
2193 return compositeType;
2194 }
2195 }
2196
Steve Naroff3eac7692008-09-10 19:17:48 +00002197 // Selection between block pointer types is ok as long as they are the same.
2198 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2199 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2200 return lexT;
2201
Chris Lattner992ae932008-01-06 22:42:25 +00002202 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00002203 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002204 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002205 return QualType();
2206}
2207
Steve Naroff87d58b42007-09-16 03:34:24 +00002208/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002209/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00002210Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00002211 SourceLocation ColonLoc,
2212 ExprTy *Cond, ExprTy *LHS,
2213 ExprTy *RHS) {
2214 Expr *CondExpr = (Expr *) Cond;
2215 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00002216
2217 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2218 // was the condition.
2219 bool isLHSNull = LHSExpr == 0;
2220 if (isLHSNull)
2221 LHSExpr = CondExpr;
2222
Chris Lattner4b009652007-07-25 00:24:17 +00002223 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
2224 RHSExpr, QuestionLoc);
2225 if (result.isNull())
2226 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00002227 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
2228 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00002229}
2230
Chris Lattner4b009652007-07-25 00:24:17 +00002231
2232// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2233// being closely modeled after the C99 spec:-). The odd characteristic of this
2234// routine is it effectively iqnores the qualifiers on the top level pointee.
2235// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2236// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00002237Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002238Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2239 QualType lhptee, rhptee;
2240
2241 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002242 lhptee = lhsType->getAsPointerType()->getPointeeType();
2243 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002244
2245 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002246 lhptee = Context.getCanonicalType(lhptee);
2247 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002248
Chris Lattner005ed752008-01-04 18:04:52 +00002249 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002250
2251 // C99 6.5.16.1p1: This following citation is common to constraints
2252 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2253 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00002254 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002255 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002256 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002257
2258 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2259 // incomplete type and the other is a pointer to a qualified or unqualified
2260 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002261 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002262 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002263 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002264
2265 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002266 assert(rhptee->isFunctionType());
2267 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002268 }
2269
2270 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002271 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002272 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002273
2274 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002275 assert(lhptee->isFunctionType());
2276 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002277 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002278
2279 // Check for ObjC interfaces
2280 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2281 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2282 if (LHSIface && RHSIface &&
2283 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2284 return ConvTy;
2285
2286 // ID acts sort of like void* for ObjC interfaces
2287 if (LHSIface && Context.isObjCIdType(rhptee))
2288 return ConvTy;
2289 if (RHSIface && Context.isObjCIdType(lhptee))
2290 return ConvTy;
2291
Chris Lattner4b009652007-07-25 00:24:17 +00002292 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2293 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002294 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2295 rhptee.getUnqualifiedType()))
2296 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002297 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002298}
2299
Steve Naroff3454b6c2008-09-04 15:10:53 +00002300/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2301/// block pointer types are compatible or whether a block and normal pointer
2302/// are compatible. It is more restrict than comparing two function pointer
2303// types.
2304Sema::AssignConvertType
2305Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2306 QualType rhsType) {
2307 QualType lhptee, rhptee;
2308
2309 // get the "pointed to" type (ignoring qualifiers at the top level)
2310 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2311 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2312
2313 // make sure we operate on the canonical type
2314 lhptee = Context.getCanonicalType(lhptee);
2315 rhptee = Context.getCanonicalType(rhptee);
2316
2317 AssignConvertType ConvTy = Compatible;
2318
2319 // For blocks we enforce that qualifiers are identical.
2320 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2321 ConvTy = CompatiblePointerDiscardsQualifiers;
2322
2323 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2324 return IncompatibleBlockPointer;
2325 return ConvTy;
2326}
2327
Chris Lattner4b009652007-07-25 00:24:17 +00002328/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2329/// has code to accommodate several GCC extensions when type checking
2330/// pointers. Here are some objectionable examples that GCC considers warnings:
2331///
2332/// int a, *pint;
2333/// short *pshort;
2334/// struct foo *pfoo;
2335///
2336/// pint = pshort; // warning: assignment from incompatible pointer type
2337/// a = pint; // warning: assignment makes integer from pointer without a cast
2338/// pint = a; // warning: assignment makes pointer from integer without a cast
2339/// pint = pfoo; // warning: assignment from incompatible pointer type
2340///
2341/// As a result, the code for dealing with pointers is more complex than the
2342/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002343///
Chris Lattner005ed752008-01-04 18:04:52 +00002344Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002345Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002346 // Get canonical types. We're not formatting these types, just comparing
2347 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002348 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2349 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002350
2351 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002352 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002353
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002354 // If the left-hand side is a reference type, then we are in a
2355 // (rare!) case where we've allowed the use of references in C,
2356 // e.g., as a parameter type in a built-in function. In this case,
2357 // just make sure that the type referenced is compatible with the
2358 // right-hand side type. The caller is responsible for adjusting
2359 // lhsType so that the resulting expression does not have reference
2360 // type.
2361 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2362 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002363 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002364 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002365 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002366
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002367 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2368 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002369 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002370 // Relax integer conversions like we do for pointers below.
2371 if (rhsType->isIntegerType())
2372 return IntToPointer;
2373 if (lhsType->isIntegerType())
2374 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002375 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002376 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002377
Nate Begemanc5f0f652008-07-14 18:02:46 +00002378 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002379 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002380 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2381 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002382 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002383
Nate Begemanc5f0f652008-07-14 18:02:46 +00002384 // If we are allowing lax vector conversions, and LHS and RHS are both
2385 // vectors, the total size only needs to be the same. This is a bitcast;
2386 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002387 if (getLangOptions().LaxVectorConversions &&
2388 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002389 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2390 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002391 }
2392 return Incompatible;
2393 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002394
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002395 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002396 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002397
Chris Lattner390564e2008-04-07 06:49:41 +00002398 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002399 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002400 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002401
Chris Lattner390564e2008-04-07 06:49:41 +00002402 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002403 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002404
Steve Naroffa982c712008-09-29 18:10:17 +00002405 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002406 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002407 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002408
2409 // Treat block pointers as objects.
2410 if (getLangOptions().ObjC1 &&
2411 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2412 return Compatible;
2413 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002414 return Incompatible;
2415 }
2416
2417 if (isa<BlockPointerType>(lhsType)) {
2418 if (rhsType->isIntegerType())
2419 return IntToPointer;
2420
Steve Naroffa982c712008-09-29 18:10:17 +00002421 // Treat block pointers as objects.
2422 if (getLangOptions().ObjC1 &&
2423 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2424 return Compatible;
2425
Steve Naroff3454b6c2008-09-04 15:10:53 +00002426 if (rhsType->isBlockPointerType())
2427 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2428
2429 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2430 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002431 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002432 }
Chris Lattner1853da22008-01-04 23:18:45 +00002433 return Incompatible;
2434 }
2435
Chris Lattner390564e2008-04-07 06:49:41 +00002436 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002437 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002438 if (lhsType == Context.BoolTy)
2439 return Compatible;
2440
2441 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002442 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002443
Chris Lattner390564e2008-04-07 06:49:41 +00002444 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002445 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002446
2447 if (isa<BlockPointerType>(lhsType) &&
2448 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002449 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002450 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002451 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002452
Chris Lattner1853da22008-01-04 23:18:45 +00002453 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002454 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002455 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002456 }
2457 return Incompatible;
2458}
2459
Chris Lattner005ed752008-01-04 18:04:52 +00002460Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002461Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002462 if (getLangOptions().CPlusPlus) {
2463 if (!lhsType->isRecordType()) {
2464 // C++ 5.17p3: If the left operand is not of class type, the
2465 // expression is implicitly converted (C++ 4) to the
2466 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002467 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2468 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002469 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002470 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002471 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002472 }
2473
2474 // FIXME: Currently, we fall through and treat C++ classes like C
2475 // structures.
2476 }
2477
Steve Naroffcdee22d2007-11-27 17:58:44 +00002478 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2479 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002480 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2481 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002482 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002483 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002484 return Compatible;
2485 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002486
2487 // We don't allow conversion of non-null-pointer constants to integers.
2488 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2489 return IntToBlockPointer;
2490
Chris Lattner5f505bf2007-10-16 02:55:40 +00002491 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002492 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002493 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002494 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002495 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002496 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002497 if (!lhsType->isReferenceType())
2498 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002499
Chris Lattner005ed752008-01-04 18:04:52 +00002500 Sema::AssignConvertType result =
2501 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002502
2503 // C99 6.5.16.1p2: The value of the right operand is converted to the
2504 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002505 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2506 // so that we can use references in built-in functions even in C.
2507 // The getNonReferenceType() call makes sure that the resulting expression
2508 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002509 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002510 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002511 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002512}
2513
Chris Lattner005ed752008-01-04 18:04:52 +00002514Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002515Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2516 return CheckAssignmentConstraints(lhsType, rhsType);
2517}
2518
Chris Lattner1eafdea2008-11-18 01:30:42 +00002519QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002520 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002521 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002522 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002523 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002524}
2525
Chris Lattner1eafdea2008-11-18 01:30:42 +00002526inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002527 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002528 // For conversion purposes, we ignore any qualifiers.
2529 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002530 QualType lhsType =
2531 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2532 QualType rhsType =
2533 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002534
Nate Begemanc5f0f652008-07-14 18:02:46 +00002535 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002536 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002537 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002538
Nate Begemanc5f0f652008-07-14 18:02:46 +00002539 // Handle the case of a vector & extvector type of the same size and element
2540 // type. It would be nice if we only had one vector type someday.
2541 if (getLangOptions().LaxVectorConversions)
2542 if (const VectorType *LV = lhsType->getAsVectorType())
2543 if (const VectorType *RV = rhsType->getAsVectorType())
2544 if (LV->getElementType() == RV->getElementType() &&
2545 LV->getNumElements() == RV->getNumElements())
2546 return lhsType->isExtVectorType() ? lhsType : rhsType;
2547
2548 // If the lhs is an extended vector and the rhs is a scalar of the same type
2549 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002550 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002551 QualType eltType = V->getElementType();
2552
2553 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2554 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2555 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002556 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002557 return lhsType;
2558 }
2559 }
2560
Nate Begemanc5f0f652008-07-14 18:02:46 +00002561 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002562 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002563 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002564 QualType eltType = V->getElementType();
2565
2566 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2567 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2568 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002569 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002570 return rhsType;
2571 }
2572 }
2573
Chris Lattner4b009652007-07-25 00:24:17 +00002574 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002575 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002576 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002577 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002578 return QualType();
2579}
2580
2581inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002582 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002583{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002584 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002585 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002586
Steve Naroff8f708362007-08-24 19:07:16 +00002587 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002588
Chris Lattner4b009652007-07-25 00:24:17 +00002589 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002590 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002591 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002592}
2593
2594inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002595 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002596{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002597 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2598 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2599 return CheckVectorOperands(Loc, lex, rex);
2600 return InvalidOperands(Loc, lex, rex);
2601 }
Chris Lattner4b009652007-07-25 00:24:17 +00002602
Steve Naroff8f708362007-08-24 19:07:16 +00002603 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002604
Chris Lattner4b009652007-07-25 00:24:17 +00002605 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002606 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002607 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002608}
2609
2610inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002611 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002612{
2613 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002614 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002615
Steve Naroff8f708362007-08-24 19:07:16 +00002616 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002617
Chris Lattner4b009652007-07-25 00:24:17 +00002618 // handle the common case first (both operands are arithmetic).
2619 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002620 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002621
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002622 // Put any potential pointer into PExp
2623 Expr* PExp = lex, *IExp = rex;
2624 if (IExp->getType()->isPointerType())
2625 std::swap(PExp, IExp);
2626
2627 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2628 if (IExp->getType()->isIntegerType()) {
2629 // Check for arithmetic on pointers to incomplete types
2630 if (!PTy->getPointeeType()->isObjectType()) {
2631 if (PTy->getPointeeType()->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002632 Diag(Loc, diag::ext_gnu_void_ptr)
2633 << lex->getSourceRange() << rex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002634 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002635 Diag(Loc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002636 << lex->getType() << lex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002637 return QualType();
2638 }
2639 }
2640 return PExp->getType();
2641 }
2642 }
2643
Chris Lattner1eafdea2008-11-18 01:30:42 +00002644 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002645}
2646
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002647// C99 6.5.6
2648QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002649 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002650 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002651 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002652
Steve Naroff8f708362007-08-24 19:07:16 +00002653 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002654
Chris Lattnerf6da2912007-12-09 21:53:25 +00002655 // Enforce type constraints: C99 6.5.6p3.
2656
2657 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002658 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002659 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002660
2661 // Either ptr - int or ptr - ptr.
2662 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002663 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002664
Chris Lattnerf6da2912007-12-09 21:53:25 +00002665 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002666 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002667 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002668 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002669 Diag(Loc, diag::ext_gnu_void_ptr)
2670 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002671 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002672 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002673 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002674 return QualType();
2675 }
2676 }
2677
2678 // The result type of a pointer-int computation is the pointer type.
2679 if (rex->getType()->isIntegerType())
2680 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002681
Chris Lattnerf6da2912007-12-09 21:53:25 +00002682 // Handle pointer-pointer subtractions.
2683 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002684 QualType rpointee = RHSPTy->getPointeeType();
2685
Chris Lattnerf6da2912007-12-09 21:53:25 +00002686 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002687 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002688 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002689 if (rpointee->isVoidType()) {
2690 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002691 Diag(Loc, diag::ext_gnu_void_ptr)
2692 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002693 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002694 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002695 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002696 return QualType();
2697 }
2698 }
2699
2700 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002701 if (!Context.typesAreCompatible(
2702 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2703 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002704 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002705 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002706 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002707 return QualType();
2708 }
2709
2710 return Context.getPointerDiffType();
2711 }
2712 }
2713
Chris Lattner1eafdea2008-11-18 01:30:42 +00002714 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002715}
2716
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002717// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002718QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002719 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002720 // C99 6.5.7p2: Each of the operands shall have integer type.
2721 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002722 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002723
Chris Lattner2c8bff72007-12-12 05:47:28 +00002724 // Shifts don't perform usual arithmetic conversions, they just do integer
2725 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002726 if (!isCompAssign)
2727 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002728 UsualUnaryConversions(rex);
2729
2730 // "The type of the result is that of the promoted left operand."
2731 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002732}
2733
Eli Friedman0d9549b2008-08-22 00:56:42 +00002734static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2735 ASTContext& Context) {
2736 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2737 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2738 // ID acts sort of like void* for ObjC interfaces
2739 if (LHSIface && Context.isObjCIdType(RHS))
2740 return true;
2741 if (RHSIface && Context.isObjCIdType(LHS))
2742 return true;
2743 if (!LHSIface || !RHSIface)
2744 return false;
2745 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2746 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2747}
2748
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002749// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002750QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002751 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002752 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002753 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002754
Chris Lattner254f3bc2007-08-26 01:18:55 +00002755 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002756 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2757 UsualArithmeticConversions(lex, rex);
2758 else {
2759 UsualUnaryConversions(lex);
2760 UsualUnaryConversions(rex);
2761 }
Chris Lattner4b009652007-07-25 00:24:17 +00002762 QualType lType = lex->getType();
2763 QualType rType = rex->getType();
2764
Ted Kremenek486509e2007-10-29 17:13:39 +00002765 // For non-floating point types, check for self-comparisons of the form
2766 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2767 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002768 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002769 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2770 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002771 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002772 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002773 }
2774
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002775 // The result of comparisons is 'bool' in C++, 'int' in C.
2776 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2777
Chris Lattner254f3bc2007-08-26 01:18:55 +00002778 if (isRelational) {
2779 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002780 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002781 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002782 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002783 if (lType->isFloatingType()) {
2784 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002785 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002786 }
2787
Chris Lattner254f3bc2007-08-26 01:18:55 +00002788 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002789 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002790 }
Chris Lattner4b009652007-07-25 00:24:17 +00002791
Chris Lattner22be8422007-08-26 01:10:14 +00002792 bool LHSIsNull = lex->isNullPointerConstant(Context);
2793 bool RHSIsNull = rex->isNullPointerConstant(Context);
2794
Chris Lattner254f3bc2007-08-26 01:18:55 +00002795 // All of the following pointer related warnings are GCC extensions, except
2796 // when handling null pointer constants. One day, we can consider making them
2797 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002798 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002799 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002800 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002801 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002802 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002803
Steve Naroff3b435622007-11-13 14:57:38 +00002804 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002805 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2806 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002807 RCanPointeeTy.getUnqualifiedType()) &&
2808 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002809 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002810 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002811 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002812 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002813 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002814 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002815 // Handle block pointer types.
2816 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2817 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2818 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2819
2820 if (!LHSIsNull && !RHSIsNull &&
2821 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
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 Naroff3454b6c2008-09-04 15:10:53 +00002824 }
2825 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002826 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002827 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002828 // Allow block pointers to be compared with null pointer constants.
2829 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2830 (lType->isPointerType() && rType->isBlockPointerType())) {
2831 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002832 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002833 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00002834 }
2835 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002836 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00002837 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002838
Steve Naroff936c4362008-06-03 14:04:54 +00002839 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002840 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00002841 const PointerType *LPT = lType->getAsPointerType();
2842 const PointerType *RPT = rType->getAsPointerType();
2843 bool LPtrToVoid = LPT ?
2844 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2845 bool RPtrToVoid = RPT ?
2846 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2847
2848 if (!LPtrToVoid && !RPtrToVoid &&
2849 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002850 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002851 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00002852 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002853 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00002854 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002855 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002856 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002857 }
Steve Naroff936c4362008-06-03 14:04:54 +00002858 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2859 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002860 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002861 } else {
2862 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002863 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00002864 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002865 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002866 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002867 }
Steve Naroff936c4362008-06-03 14:04:54 +00002868 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002869 }
Steve Naroff936c4362008-06-03 14:04:54 +00002870 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2871 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002872 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002873 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002874 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002875 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002876 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002877 }
Steve Naroff936c4362008-06-03 14:04:54 +00002878 if (lType->isIntegerType() &&
2879 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002880 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002881 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002882 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002883 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002884 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002885 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002886 // Handle block pointers.
2887 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2888 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002889 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002890 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002891 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002892 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002893 }
2894 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2895 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002896 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002897 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002898 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002899 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002900 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00002901 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002902}
2903
Nate Begemanc5f0f652008-07-14 18:02:46 +00002904/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2905/// operates on extended vector types. Instead of producing an IntTy result,
2906/// like a scalar comparison, a vector comparison produces a vector of integer
2907/// types.
2908QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002909 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00002910 bool isRelational) {
2911 // Check to make sure we're operating on vectors of the same type and width,
2912 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002913 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002914 if (vType.isNull())
2915 return vType;
2916
2917 QualType lType = lex->getType();
2918 QualType rType = rex->getType();
2919
2920 // For non-floating point types, check for self-comparisons of the form
2921 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2922 // often indicate logic errors in the program.
2923 if (!lType->isFloatingType()) {
2924 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2925 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2926 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002927 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002928 }
2929
2930 // Check for comparisons of floating point operands using != and ==.
2931 if (!isRelational && lType->isFloatingType()) {
2932 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002933 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002934 }
2935
2936 // Return the type for the comparison, which is the same as vector type for
2937 // integer vectors, or an integer type of identical size and number of
2938 // elements for floating point vectors.
2939 if (lType->isIntegerType())
2940 return lType;
2941
2942 const VectorType *VTy = lType->getAsVectorType();
2943
2944 // FIXME: need to deal with non-32b int / non-64b long long
2945 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2946 if (TypeSize == 32) {
2947 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2948 }
2949 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2950 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2951}
2952
Chris Lattner4b009652007-07-25 00:24:17 +00002953inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002954 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002955{
2956 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002957 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002958
Steve Naroff8f708362007-08-24 19:07:16 +00002959 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002960
2961 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002962 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002963 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002964}
2965
2966inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00002967 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00002968{
2969 UsualUnaryConversions(lex);
2970 UsualUnaryConversions(rex);
2971
Eli Friedmanbea3f842008-05-13 20:16:47 +00002972 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002973 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002974 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002975}
2976
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00002977/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
2978/// is a read-only property; return true if so. A readonly property expression
2979/// depends on various declarations and thus must be treated specially.
2980///
2981static bool IsReadonlyProperty(Expr *E, Sema &S)
2982{
2983 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
2984 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
2985 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
2986 QualType BaseType = PropExpr->getBase()->getType();
2987 if (const PointerType *PTy = BaseType->getAsPointerType())
2988 if (const ObjCInterfaceType *IFTy =
2989 PTy->getPointeeType()->getAsObjCInterfaceType())
2990 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
2991 if (S.isPropertyReadonly(PDecl, IFace))
2992 return true;
2993 }
2994 }
2995 return false;
2996}
2997
Chris Lattner4c2642c2008-11-18 01:22:49 +00002998/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
2999/// emit an error and return true. If so, return false.
3000static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003001 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3002 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3003 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003004 if (IsLV == Expr::MLV_Valid)
3005 return false;
3006
3007 unsigned Diag = 0;
3008 bool NeedType = false;
3009 switch (IsLV) { // C99 6.5.16p2
3010 default: assert(0 && "Unknown result from isModifiableLvalue!");
3011 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00003012 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003013 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3014 NeedType = true;
3015 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003016 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003017 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3018 NeedType = true;
3019 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003020 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003021 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3022 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003023 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003024 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3025 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003026 case Expr::MLV_IncompleteType:
3027 case Expr::MLV_IncompleteVoidType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003028 Diag = diag::err_typecheck_incomplete_type_not_modifiable_lvalue;
3029 NeedType = true;
3030 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003031 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003032 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3033 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003034 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003035 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3036 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003037 case Expr::MLV_ReadonlyProperty:
3038 Diag = diag::error_readonly_property_assignment;
3039 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003040 case Expr::MLV_NoSetterProperty:
3041 Diag = diag::error_nosetter_property_assignment;
3042 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003043 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003044
Chris Lattner4c2642c2008-11-18 01:22:49 +00003045 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003046 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003047 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003048 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003049 return true;
3050}
3051
3052
3053
3054// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003055QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3056 SourceLocation Loc,
3057 QualType CompoundType) {
3058 // Verify that LHS is a modifiable lvalue, and emit error if not.
3059 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003060 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003061
3062 QualType LHSType = LHS->getType();
3063 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003064
Chris Lattner005ed752008-01-04 18:04:52 +00003065 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003066 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003067 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003068 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003069 // Special case of NSObject attributes on c-style pointer types.
3070 if (ConvTy == IncompatiblePointer &&
3071 ((Context.isObjCNSObjectType(LHSType) &&
3072 Context.isObjCObjectPointerType(RHSType)) ||
3073 (Context.isObjCNSObjectType(RHSType) &&
3074 Context.isObjCObjectPointerType(LHSType))))
3075 ConvTy = Compatible;
3076
Chris Lattner34c85082008-08-21 18:04:13 +00003077 // If the RHS is a unary plus or minus, check to see if they = and + are
3078 // right next to each other. If so, the user may have typo'd "x =+ 4"
3079 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003080 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003081 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3082 RHSCheck = ICE->getSubExpr();
3083 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3084 if ((UO->getOpcode() == UnaryOperator::Plus ||
3085 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003086 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003087 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003088 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003089 Diag(Loc, diag::warn_not_compound_assign)
3090 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3091 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003092 }
3093 } else {
3094 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003095 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003096 }
Chris Lattner005ed752008-01-04 18:04:52 +00003097
Chris Lattner1eafdea2008-11-18 01:30:42 +00003098 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3099 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003100 return QualType();
3101
Chris Lattner4b009652007-07-25 00:24:17 +00003102 // C99 6.5.16p3: The type of an assignment expression is the type of the
3103 // left operand unless the left operand has qualified type, in which case
3104 // it is the unqualified version of the type of the left operand.
3105 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3106 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003107 // C++ 5.17p1: the type of the assignment expression is that of its left
3108 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003109 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003110}
3111
Chris Lattner1eafdea2008-11-18 01:30:42 +00003112// C99 6.5.17
3113QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3114 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00003115
3116 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003117 DefaultFunctionArrayConversion(RHS);
3118 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003119}
3120
3121/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3122/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003123QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3124 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003125 QualType ResType = Op->getType();
3126 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003127
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003128 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3129 // Decrement of bool is not allowed.
3130 if (!isInc) {
3131 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3132 return QualType();
3133 }
3134 // Increment of bool sets it to true, but is deprecated.
3135 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3136 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003137 // OK!
3138 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3139 // C99 6.5.2.4p2, 6.5.6p2
3140 if (PT->getPointeeType()->isObjectType()) {
3141 // Pointer to object is ok!
3142 } else if (PT->getPointeeType()->isVoidType()) {
3143 // Pointer to void is extension.
3144 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
3145 } else {
Chris Lattner9d2cf082008-11-19 05:27:50 +00003146 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003147 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003148 return QualType();
3149 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003150 } else if (ResType->isComplexType()) {
3151 // C99 does not support ++/-- on complex types, we allow as an extension.
3152 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003153 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003154 } else {
3155 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003156 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003157 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003158 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00003159 // At this point, we know we have a real, complex or pointer type.
3160 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003161 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003162 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003163 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003164}
3165
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003166/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003167/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003168/// where the declaration is needed for type checking. We only need to
3169/// handle cases when the expression references a function designator
3170/// or is an lvalue. Here are some examples:
3171/// - &(x) => x
3172/// - &*****f => f for f a function designator.
3173/// - &s.xx => s
3174/// - &s.zz[1].yy -> s, if zz is an array
3175/// - *(x + 1) -> x, if x is an array
3176/// - &"123"[2] -> 0
3177/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003178static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003179 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003180 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003181 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003182 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003183 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003184 // Fields cannot be declared with a 'register' storage class.
3185 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003186 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003187 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003188 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003189 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003190 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003191
Douglas Gregord2baafd2008-10-21 16:13:35 +00003192 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003193 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003194 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003195 return 0;
3196 else
3197 return VD;
3198 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003199 case Stmt::UnaryOperatorClass: {
3200 UnaryOperator *UO = cast<UnaryOperator>(E);
3201
3202 switch(UO->getOpcode()) {
3203 case UnaryOperator::Deref: {
3204 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003205 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3206 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3207 if (!VD || VD->getType()->isPointerType())
3208 return 0;
3209 return VD;
3210 }
3211 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003212 }
3213 case UnaryOperator::Real:
3214 case UnaryOperator::Imag:
3215 case UnaryOperator::Extension:
3216 return getPrimaryDecl(UO->getSubExpr());
3217 default:
3218 return 0;
3219 }
3220 }
3221 case Stmt::BinaryOperatorClass: {
3222 BinaryOperator *BO = cast<BinaryOperator>(E);
3223
3224 // Handle cases involving pointer arithmetic. The result of an
3225 // Assign or AddAssign is not an lvalue so they can be ignored.
3226
3227 // (x + n) or (n + x) => x
3228 if (BO->getOpcode() == BinaryOperator::Add) {
3229 if (BO->getLHS()->getType()->isPointerType()) {
3230 return getPrimaryDecl(BO->getLHS());
3231 } else if (BO->getRHS()->getType()->isPointerType()) {
3232 return getPrimaryDecl(BO->getRHS());
3233 }
3234 }
3235
3236 return 0;
3237 }
Chris Lattner4b009652007-07-25 00:24:17 +00003238 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003239 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003240 case Stmt::ImplicitCastExprClass:
3241 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003242 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003243 default:
3244 return 0;
3245 }
3246}
3247
3248/// CheckAddressOfOperand - The operand of & must be either a function
3249/// designator or an lvalue designating an object. If it is an lvalue, the
3250/// object cannot be declared with storage class register or be a bit field.
3251/// Note: The usual conversions are *not* applied to the operand of the &
3252/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00003253/// In C++, the operand might be an overloaded function name, in which case
3254/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003255QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003256 if (op->isTypeDependent())
3257 return Context.DependentTy;
3258
Steve Naroff9c6c3592008-01-13 17:10:08 +00003259 if (getLangOptions().C99) {
3260 // Implement C99-only parts of addressof rules.
3261 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3262 if (uOp->getOpcode() == UnaryOperator::Deref)
3263 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3264 // (assuming the deref expression is valid).
3265 return uOp->getSubExpr()->getType();
3266 }
3267 // Technically, there should be a check for array subscript
3268 // expressions here, but the result of one is always an lvalue anyway.
3269 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003270 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003271 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003272
Chris Lattner4b009652007-07-25 00:24:17 +00003273 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003274 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3275 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003276 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3277 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003278 return QualType();
3279 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003280 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003281 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3282 if (Field->isBitField()) {
3283 Diag(OpLoc, diag::err_typecheck_address_of)
3284 << "bit-field" << op->getSourceRange();
3285 return QualType();
3286 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003287 }
3288 // Check for Apple extension for accessing vector components.
3289 } else if (isa<ArraySubscriptExpr>(op) &&
3290 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003291 Diag(OpLoc, diag::err_typecheck_address_of)
3292 << "vector" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003293 return QualType();
3294 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00003295 // We have an lvalue with a decl. Make sure the decl is not declared
3296 // with the register storage-class specifier.
3297 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3298 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003299 Diag(OpLoc, diag::err_typecheck_address_of)
3300 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003301 return QualType();
3302 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003303 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003304 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003305 } else if (isa<FieldDecl>(dcl)) {
3306 // Okay: we can take the address of a field.
Nuno Lopesdf239522008-12-16 22:58:26 +00003307 } else if (isa<FunctionDecl>(dcl)) {
3308 // Okay: we can take the address of a function.
Douglas Gregor5b82d612008-12-10 21:26:49 +00003309 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003310 else
Chris Lattner4b009652007-07-25 00:24:17 +00003311 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003312 }
Chris Lattnera55e3212008-07-27 00:48:22 +00003313
Chris Lattner4b009652007-07-25 00:24:17 +00003314 // If the operand has type "type", the result has type "pointer to type".
3315 return Context.getPointerType(op->getType());
3316}
3317
Chris Lattnerda5c0872008-11-23 09:13:29 +00003318QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3319 UsualUnaryConversions(Op);
3320 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003321
Chris Lattnerda5c0872008-11-23 09:13:29 +00003322 // Note that per both C89 and C99, this is always legal, even if ptype is an
3323 // incomplete type or void. It would be possible to warn about dereferencing
3324 // a void pointer, but it's completely well-defined, and such a warning is
3325 // unlikely to catch any mistakes.
3326 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003327 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00003328
Chris Lattner77d52da2008-11-20 06:06:08 +00003329 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003330 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003331 return QualType();
3332}
3333
3334static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3335 tok::TokenKind Kind) {
3336 BinaryOperator::Opcode Opc;
3337 switch (Kind) {
3338 default: assert(0 && "Unknown binop!");
3339 case tok::star: Opc = BinaryOperator::Mul; break;
3340 case tok::slash: Opc = BinaryOperator::Div; break;
3341 case tok::percent: Opc = BinaryOperator::Rem; break;
3342 case tok::plus: Opc = BinaryOperator::Add; break;
3343 case tok::minus: Opc = BinaryOperator::Sub; break;
3344 case tok::lessless: Opc = BinaryOperator::Shl; break;
3345 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3346 case tok::lessequal: Opc = BinaryOperator::LE; break;
3347 case tok::less: Opc = BinaryOperator::LT; break;
3348 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3349 case tok::greater: Opc = BinaryOperator::GT; break;
3350 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3351 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3352 case tok::amp: Opc = BinaryOperator::And; break;
3353 case tok::caret: Opc = BinaryOperator::Xor; break;
3354 case tok::pipe: Opc = BinaryOperator::Or; break;
3355 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3356 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3357 case tok::equal: Opc = BinaryOperator::Assign; break;
3358 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3359 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3360 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3361 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3362 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3363 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3364 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3365 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3366 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3367 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3368 case tok::comma: Opc = BinaryOperator::Comma; break;
3369 }
3370 return Opc;
3371}
3372
3373static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3374 tok::TokenKind Kind) {
3375 UnaryOperator::Opcode Opc;
3376 switch (Kind) {
3377 default: assert(0 && "Unknown unary op!");
3378 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3379 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3380 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3381 case tok::star: Opc = UnaryOperator::Deref; break;
3382 case tok::plus: Opc = UnaryOperator::Plus; break;
3383 case tok::minus: Opc = UnaryOperator::Minus; break;
3384 case tok::tilde: Opc = UnaryOperator::Not; break;
3385 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003386 case tok::kw___real: Opc = UnaryOperator::Real; break;
3387 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3388 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3389 }
3390 return Opc;
3391}
3392
Douglas Gregord7f915e2008-11-06 23:29:22 +00003393/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3394/// operator @p Opc at location @c TokLoc. This routine only supports
3395/// built-in operations; ActOnBinOp handles overloaded operators.
3396Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3397 unsigned Op,
3398 Expr *lhs, Expr *rhs) {
3399 QualType ResultTy; // Result type of the binary operator.
3400 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3401 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3402
3403 switch (Opc) {
3404 default:
3405 assert(0 && "Unknown binary expr!");
3406 case BinaryOperator::Assign:
3407 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3408 break;
3409 case BinaryOperator::Mul:
3410 case BinaryOperator::Div:
3411 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3412 break;
3413 case BinaryOperator::Rem:
3414 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3415 break;
3416 case BinaryOperator::Add:
3417 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3418 break;
3419 case BinaryOperator::Sub:
3420 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3421 break;
3422 case BinaryOperator::Shl:
3423 case BinaryOperator::Shr:
3424 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3425 break;
3426 case BinaryOperator::LE:
3427 case BinaryOperator::LT:
3428 case BinaryOperator::GE:
3429 case BinaryOperator::GT:
3430 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3431 break;
3432 case BinaryOperator::EQ:
3433 case BinaryOperator::NE:
3434 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3435 break;
3436 case BinaryOperator::And:
3437 case BinaryOperator::Xor:
3438 case BinaryOperator::Or:
3439 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3440 break;
3441 case BinaryOperator::LAnd:
3442 case BinaryOperator::LOr:
3443 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3444 break;
3445 case BinaryOperator::MulAssign:
3446 case BinaryOperator::DivAssign:
3447 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3448 if (!CompTy.isNull())
3449 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3450 break;
3451 case BinaryOperator::RemAssign:
3452 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3453 if (!CompTy.isNull())
3454 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3455 break;
3456 case BinaryOperator::AddAssign:
3457 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3458 if (!CompTy.isNull())
3459 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3460 break;
3461 case BinaryOperator::SubAssign:
3462 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3463 if (!CompTy.isNull())
3464 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3465 break;
3466 case BinaryOperator::ShlAssign:
3467 case BinaryOperator::ShrAssign:
3468 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3469 if (!CompTy.isNull())
3470 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3471 break;
3472 case BinaryOperator::AndAssign:
3473 case BinaryOperator::XorAssign:
3474 case BinaryOperator::OrAssign:
3475 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3476 if (!CompTy.isNull())
3477 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3478 break;
3479 case BinaryOperator::Comma:
3480 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3481 break;
3482 }
3483 if (ResultTy.isNull())
3484 return true;
3485 if (CompTy.isNull())
3486 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
3487 else
3488 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
3489}
3490
Chris Lattner4b009652007-07-25 00:24:17 +00003491// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003492Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3493 tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00003494 ExprTy *LHS, ExprTy *RHS) {
3495 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
3496 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
3497
Steve Naroff87d58b42007-09-16 03:34:24 +00003498 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3499 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003500
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003501 // If either expression is type-dependent, just build the AST.
3502 // FIXME: We'll need to perform some caching of the result of name
3503 // lookup for operator+.
3504 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
3505 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3506 return new CompoundAssignOperator(lhs, rhs, Opc, Context.DependentTy,
3507 Context.DependentTy, TokLoc);
3508 else
3509 return new BinaryOperator(lhs, rhs, Opc, Context.DependentTy, TokLoc);
3510 }
3511
Douglas Gregord7f915e2008-11-06 23:29:22 +00003512 if (getLangOptions().CPlusPlus &&
3513 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3514 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003515 // If this is one of the assignment operators, we only perform
3516 // overload resolution if the left-hand side is a class or
3517 // enumeration type (C++ [expr.ass]p3).
3518 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3519 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3520 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3521 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003522
3523 // Determine which overloaded operator we're dealing with.
3524 static const OverloadedOperatorKind OverOps[] = {
3525 OO_Star, OO_Slash, OO_Percent,
3526 OO_Plus, OO_Minus,
3527 OO_LessLess, OO_GreaterGreater,
3528 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3529 OO_EqualEqual, OO_ExclaimEqual,
3530 OO_Amp,
3531 OO_Caret,
3532 OO_Pipe,
3533 OO_AmpAmp,
3534 OO_PipePipe,
3535 OO_Equal, OO_StarEqual,
3536 OO_SlashEqual, OO_PercentEqual,
3537 OO_PlusEqual, OO_MinusEqual,
3538 OO_LessLessEqual, OO_GreaterGreaterEqual,
3539 OO_AmpEqual, OO_CaretEqual,
3540 OO_PipeEqual,
3541 OO_Comma
3542 };
3543 OverloadedOperatorKind OverOp = OverOps[Opc];
3544
Douglas Gregor5ed15042008-11-18 23:14:02 +00003545 // Add the appropriate overloaded operators (C++ [over.match.oper])
3546 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003547 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003548 Expr *Args[2] = { lhs, rhs };
Douglas Gregor5ed15042008-11-18 23:14:02 +00003549 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregord7f915e2008-11-06 23:29:22 +00003550
3551 // Perform overload resolution.
3552 OverloadCandidateSet::iterator Best;
3553 switch (BestViableFunction(CandidateSet, Best)) {
3554 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003555 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003556 FunctionDecl *FnDecl = Best->Function;
3557
Douglas Gregor70d26122008-11-12 17:17:38 +00003558 if (FnDecl) {
3559 // We matched an overloaded operator. Build a call to that
3560 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003561
Douglas Gregor70d26122008-11-12 17:17:38 +00003562 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003563 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3564 if (PerformObjectArgumentInitialization(lhs, Method) ||
3565 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3566 "passing"))
3567 return true;
3568 } else {
3569 // Convert the arguments.
3570 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3571 "passing") ||
3572 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3573 "passing"))
3574 return true;
3575 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003576
Douglas Gregor70d26122008-11-12 17:17:38 +00003577 // Determine the result type
3578 QualType ResultTy
3579 = FnDecl->getType()->getAsFunctionType()->getResultType();
3580 ResultTy = ResultTy.getNonReferenceType();
3581
3582 // Build the actual expression node.
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003583 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3584 SourceLocation());
3585 UsualUnaryConversions(FnExpr);
3586
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003587 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, TokLoc);
Douglas Gregor70d26122008-11-12 17:17:38 +00003588 } else {
3589 // We matched a built-in operator. Convert the arguments, then
3590 // break out so that we will build the appropriate built-in
3591 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003592 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3593 Best->Conversions[0], "passing") ||
3594 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3595 Best->Conversions[1], "passing"))
Douglas Gregor70d26122008-11-12 17:17:38 +00003596 return true;
3597
3598 break;
3599 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003600 }
3601
3602 case OR_No_Viable_Function:
3603 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003604 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003605 break;
3606
3607 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003608 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3609 << BinaryOperator::getOpcodeStr(Opc)
3610 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003611 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3612 return true;
3613 }
3614
Douglas Gregor70d26122008-11-12 17:17:38 +00003615 // Either we found no viable overloaded operator or we matched a
3616 // built-in operator. In either case, fall through to trying to
3617 // build a built-in operation.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003618 }
Chris Lattner4b009652007-07-25 00:24:17 +00003619
Douglas Gregord7f915e2008-11-06 23:29:22 +00003620 // Build a built-in binary operation.
3621 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003622}
3623
3624// Unary Operators. 'Tok' is the token for the operator.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003625Action::ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3626 tok::TokenKind Op, ExprTy *input) {
Chris Lattner4b009652007-07-25 00:24:17 +00003627 Expr *Input = (Expr*)input;
3628 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003629
3630 if (getLangOptions().CPlusPlus &&
3631 (Input->getType()->isRecordType()
3632 || Input->getType()->isEnumeralType())) {
3633 // Determine which overloaded operator we're dealing with.
3634 static const OverloadedOperatorKind OverOps[] = {
3635 OO_None, OO_None,
3636 OO_PlusPlus, OO_MinusMinus,
3637 OO_Amp, OO_Star,
3638 OO_Plus, OO_Minus,
3639 OO_Tilde, OO_Exclaim,
3640 OO_None, OO_None,
3641 OO_None,
3642 OO_None
3643 };
3644 OverloadedOperatorKind OverOp = OverOps[Opc];
3645
3646 // Add the appropriate overloaded operators (C++ [over.match.oper])
3647 // to the candidate set.
3648 OverloadCandidateSet CandidateSet;
3649 if (OverOp != OO_None)
3650 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3651
3652 // Perform overload resolution.
3653 OverloadCandidateSet::iterator Best;
3654 switch (BestViableFunction(CandidateSet, Best)) {
3655 case OR_Success: {
3656 // We found a built-in operator or an overloaded operator.
3657 FunctionDecl *FnDecl = Best->Function;
3658
3659 if (FnDecl) {
3660 // We matched an overloaded operator. Build a call to that
3661 // operator.
3662
3663 // Convert the arguments.
3664 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3665 if (PerformObjectArgumentInitialization(Input, Method))
3666 return true;
3667 } else {
3668 // Convert the arguments.
3669 if (PerformCopyInitialization(Input,
3670 FnDecl->getParamDecl(0)->getType(),
3671 "passing"))
3672 return true;
3673 }
3674
3675 // Determine the result type
3676 QualType ResultTy
3677 = FnDecl->getType()->getAsFunctionType()->getResultType();
3678 ResultTy = ResultTy.getNonReferenceType();
3679
3680 // Build the actual expression node.
3681 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3682 SourceLocation());
3683 UsualUnaryConversions(FnExpr);
3684
3685 return new CXXOperatorCallExpr(FnExpr, &Input, 1, ResultTy, OpLoc);
3686 } else {
3687 // We matched a built-in operator. Convert the arguments, then
3688 // break out so that we will build the appropriate built-in
3689 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003690 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3691 Best->Conversions[0], "passing"))
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003692 return true;
3693
3694 break;
3695 }
3696 }
3697
3698 case OR_No_Viable_Function:
3699 // No viable function; fall through to handling this as a
3700 // built-in operator, which will produce an error message for us.
3701 break;
3702
3703 case OR_Ambiguous:
3704 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3705 << UnaryOperator::getOpcodeStr(Opc)
3706 << Input->getSourceRange();
3707 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3708 return true;
3709 }
3710
3711 // Either we found no viable overloaded operator or we matched a
3712 // built-in operator. In either case, fall through to trying to
3713 // build a built-in operation.
3714 }
3715
Chris Lattner4b009652007-07-25 00:24:17 +00003716 QualType resultType;
3717 switch (Opc) {
3718 default:
3719 assert(0 && "Unimplemented unary expr!");
3720 case UnaryOperator::PreInc:
3721 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003722 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3723 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00003724 break;
3725 case UnaryOperator::AddrOf:
3726 resultType = CheckAddressOfOperand(Input, OpLoc);
3727 break;
3728 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00003729 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00003730 resultType = CheckIndirectionOperand(Input, OpLoc);
3731 break;
3732 case UnaryOperator::Plus:
3733 case UnaryOperator::Minus:
3734 UsualUnaryConversions(Input);
3735 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003736 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3737 break;
3738 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3739 resultType->isEnumeralType())
3740 break;
3741 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3742 Opc == UnaryOperator::Plus &&
3743 resultType->isPointerType())
3744 break;
3745
Chris Lattner77d52da2008-11-20 06:06:08 +00003746 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003747 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003748 case UnaryOperator::Not: // bitwise complement
3749 UsualUnaryConversions(Input);
3750 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00003751 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3752 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3753 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00003754 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003755 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00003756 else if (!resultType->isIntegerType())
Chris Lattner77d52da2008-11-20 06:06:08 +00003757 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003758 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003759 break;
3760 case UnaryOperator::LNot: // logical negation
3761 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
3762 DefaultFunctionArrayConversion(Input);
3763 resultType = Input->getType();
3764 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Chris Lattner77d52da2008-11-20 06:06:08 +00003765 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003766 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003767 // LNot always has type int. C99 6.5.3.3p5.
3768 resultType = Context.IntTy;
3769 break;
Chris Lattner03931a72007-08-24 21:16:53 +00003770 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00003771 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00003772 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00003773 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003774 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00003775 resultType = Input->getType();
3776 break;
3777 }
3778 if (resultType.isNull())
3779 return true;
3780 return new UnaryOperator(Input, Opc, resultType, OpLoc);
3781}
3782
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003783/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3784Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00003785 SourceLocation LabLoc,
3786 IdentifierInfo *LabelII) {
3787 // Look up the record for this label identifier.
3788 LabelStmt *&LabelDecl = LabelMap[LabelII];
3789
Daniel Dunbar879788d2008-08-04 16:51:22 +00003790 // If we haven't seen this label yet, create a forward reference. It
3791 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00003792 if (LabelDecl == 0)
3793 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
3794
3795 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00003796 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3797 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00003798}
3799
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003800Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00003801 SourceLocation RPLoc) { // "({..})"
3802 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3803 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3804 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3805
3806 // FIXME: there are a variety of strange constraints to enforce here, for
3807 // example, it is not possible to goto into a stmt expression apparently.
3808 // More semantic analysis is needed.
3809
3810 // FIXME: the last statement in the compount stmt has its value used. We
3811 // should not warn about it being unused.
3812
3813 // If there are sub stmts in the compound stmt, take the type of the last one
3814 // as the type of the stmtexpr.
3815 QualType Ty = Context.VoidTy;
3816
Chris Lattner200964f2008-07-26 19:51:01 +00003817 if (!Compound->body_empty()) {
3818 Stmt *LastStmt = Compound->body_back();
3819 // If LastStmt is a label, skip down through into the body.
3820 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3821 LastStmt = Label->getSubStmt();
3822
3823 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00003824 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00003825 }
Chris Lattner4b009652007-07-25 00:24:17 +00003826
3827 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
3828}
Steve Naroff63bad2d2007-08-01 22:05:33 +00003829
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003830Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
3831 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003832 SourceLocation TypeLoc,
3833 TypeTy *argty,
3834 OffsetOfComponent *CompPtr,
3835 unsigned NumComponents,
3836 SourceLocation RPLoc) {
3837 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3838 assert(!ArgTy.isNull() && "Missing type argument!");
3839
3840 // We must have at least one component that refers to the type, and the first
3841 // one is known to be a field designator. Verify that the ArgTy represents
3842 // a struct/union/class.
3843 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00003844 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003845
3846 // Otherwise, create a compound literal expression as the base, and
3847 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00003848 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003849
Chris Lattnerb37522e2007-08-31 21:49:13 +00003850 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3851 // GCC extension, diagnose them.
3852 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003853 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3854 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00003855
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003856 for (unsigned i = 0; i != NumComponents; ++i) {
3857 const OffsetOfComponent &OC = CompPtr[i];
3858 if (OC.isBrackets) {
3859 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00003860 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003861 if (!AT) {
3862 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003863 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003864 }
3865
Chris Lattner2af6a802007-08-30 17:59:59 +00003866 // FIXME: C++: Verify that operator[] isn't overloaded.
3867
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003868 // C99 6.5.2.1p1
3869 Expr *Idx = static_cast<Expr*>(OC.U.E);
3870 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00003871 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
3872 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003873
3874 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3875 continue;
3876 }
3877
3878 const RecordType *RC = Res->getType()->getAsRecordType();
3879 if (!RC) {
3880 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003881 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003882 }
3883
3884 // Get the decl corresponding to this.
3885 RecordDecl *RD = RC->getDecl();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003886 FieldDecl *MemberDecl
3887 = dyn_cast_or_null<FieldDecl>(LookupDecl(OC.U.IdentInfo,
3888 Decl::IDNS_Ordinary,
Douglas Gregor78d70132009-01-14 22:20:51 +00003889 S, RD, false, false).getAsDecl());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003890 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00003891 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
3892 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00003893
3894 // FIXME: C++: Verify that MemberDecl isn't a static field.
3895 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00003896 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3897 // matter here.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003898 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3899 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003900 }
3901
3902 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3903 BuiltinLoc);
3904}
3905
3906
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003907Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00003908 TypeTy *arg1, TypeTy *arg2,
3909 SourceLocation RPLoc) {
3910 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3911 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3912
3913 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3914
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003915 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00003916}
3917
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003918Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00003919 ExprTy *expr1, ExprTy *expr2,
3920 SourceLocation RPLoc) {
3921 Expr *CondExpr = static_cast<Expr*>(cond);
3922 Expr *LHSExpr = static_cast<Expr*>(expr1);
3923 Expr *RHSExpr = static_cast<Expr*>(expr2);
3924
3925 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3926
3927 // The conditional expression is required to be a constant expression.
3928 llvm::APSInt condEval(32);
3929 SourceLocation ExpLoc;
3930 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003931 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
3932 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00003933
3934 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3935 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3936 RHSExpr->getType();
3937 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3938}
3939
Steve Naroff52a81c02008-09-03 18:15:37 +00003940//===----------------------------------------------------------------------===//
3941// Clang Extensions.
3942//===----------------------------------------------------------------------===//
3943
3944/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00003945void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003946 // Analyze block parameters.
3947 BlockSemaInfo *BSI = new BlockSemaInfo();
3948
3949 // Add BSI to CurBlock.
3950 BSI->PrevBlockInfo = CurBlock;
3951 CurBlock = BSI;
3952
3953 BSI->ReturnType = 0;
3954 BSI->TheScope = BlockScope;
3955
Steve Naroff52059382008-10-10 01:28:17 +00003956 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00003957 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00003958}
3959
3960void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003961 // Analyze arguments to block.
3962 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3963 "Not a function declarator!");
3964 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3965
Steve Naroff52059382008-10-10 01:28:17 +00003966 CurBlock->hasPrototype = FTI.hasPrototype;
3967 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00003968
3969 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3970 // no arguments, not a function that takes a single void argument.
3971 if (FTI.hasPrototype &&
3972 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3973 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3974 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3975 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00003976 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00003977 } else if (FTI.hasPrototype) {
3978 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00003979 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3980 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00003981 }
Steve Naroff52059382008-10-10 01:28:17 +00003982 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3983
3984 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3985 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3986 // If this has an identifier, add it to the scope stack.
3987 if ((*AI)->getIdentifier())
3988 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00003989}
3990
3991/// ActOnBlockError - If there is an error parsing a block, this callback
3992/// is invoked to pop the information about the block from the action impl.
3993void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3994 // Ensure that CurBlock is deleted.
3995 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3996
3997 // Pop off CurBlock, handle nested blocks.
3998 CurBlock = CurBlock->PrevBlockInfo;
3999
4000 // FIXME: Delete the ParmVarDecl objects as well???
4001
4002}
4003
4004/// ActOnBlockStmtExpr - This is called when the body of a block statement
4005/// literal was successfully completed. ^(int x){...}
4006Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4007 Scope *CurScope) {
4008 // Ensure that CurBlock is deleted.
4009 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
4010 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
4011
Steve Naroff52059382008-10-10 01:28:17 +00004012 PopDeclContext();
4013
Steve Naroff52a81c02008-09-03 18:15:37 +00004014 // Pop off CurBlock, handle nested blocks.
4015 CurBlock = CurBlock->PrevBlockInfo;
4016
4017 QualType RetTy = Context.VoidTy;
4018 if (BSI->ReturnType)
4019 RetTy = QualType(BSI->ReturnType, 0);
4020
4021 llvm::SmallVector<QualType, 8> ArgTypes;
4022 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4023 ArgTypes.push_back(BSI->Params[i]->getType());
4024
4025 QualType BlockTy;
4026 if (!BSI->hasPrototype)
4027 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4028 else
4029 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004030 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00004031
4032 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00004033
Steve Naroff95029d92008-10-08 18:44:00 +00004034 BSI->TheDecl->setBody(Body.take());
4035 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004036}
4037
Nate Begemanbd881ef2008-01-30 20:50:20 +00004038/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004039/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00004040/// The number of arguments has already been validated to match the number of
4041/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004042static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4043 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004044 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00004045 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004046 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4047 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00004048
4049 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004050 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00004051 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004052 return true;
4053}
4054
4055Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4056 SourceLocation *CommaLocs,
4057 SourceLocation BuiltinLoc,
4058 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004059 // __builtin_overload requires at least 2 arguments
4060 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004061 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4062 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004063
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004064 // The first argument is required to be a constant expression. It tells us
4065 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00004066 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004067 Expr *NParamsExpr = Args[0];
4068 llvm::APSInt constEval(32);
4069 SourceLocation ExpLoc;
4070 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004071 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4072 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004073
4074 // Verify that the number of parameters is > 0
4075 unsigned NumParams = constEval.getZExtValue();
4076 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004077 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4078 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004079 // Verify that we have at least 1 + NumParams arguments to the builtin.
4080 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004081 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4082 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004083
4084 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00004085 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00004086 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004087 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4088 // UsualUnaryConversions will convert the function DeclRefExpr into a
4089 // pointer to function.
4090 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004091 const FunctionTypeProto *FnType = 0;
4092 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4093 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004094
4095 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4096 // parameters, and the number of parameters must match the value passed to
4097 // the builtin.
4098 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004099 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4100 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004101
4102 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00004103 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004104 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004105 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004106 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004107 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4108 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00004109 // Remember our match, and continue processing the remaining arguments
4110 // to catch any errors.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004111 OE = new OverloadExpr(Args, NumArgs, i,
4112 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00004113 BuiltinLoc, RParenLoc);
4114 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004115 }
Nate Begemanc6078c92008-01-31 05:38:29 +00004116 // Return the newly created OverloadExpr node, if we succeded in matching
4117 // exactly one of the candidate functions.
4118 if (OE)
4119 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004120
4121 // If we didn't find a matching function Expr in the __builtin_overload list
4122 // the return an error.
4123 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00004124 for (unsigned i = 0; i != NumParams; ++i) {
4125 if (i != 0) typeNames += ", ";
4126 typeNames += Args[i+1]->getType().getAsString();
4127 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004128
Chris Lattner77d52da2008-11-20 06:06:08 +00004129 return Diag(BuiltinLoc, diag::err_overload_no_match)
4130 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004131}
4132
Anders Carlsson36760332007-10-15 20:28:48 +00004133Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4134 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004135 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004136 Expr *E = static_cast<Expr*>(expr);
4137 QualType T = QualType::getFromOpaquePtr(type);
4138
4139 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004140
4141 // Get the va_list type
4142 QualType VaListType = Context.getBuiltinVaListType();
4143 // Deal with implicit array decay; for example, on x86-64,
4144 // va_list is an array, but it's supposed to decay to
4145 // a pointer for va_arg.
4146 if (VaListType->isArrayType())
4147 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004148 // Make sure the input expression also decays appropriately.
4149 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004150
4151 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004152 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004153 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004154 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00004155
4156 // FIXME: Warn if a non-POD type is passed in.
4157
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004158 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004159}
4160
Douglas Gregorad4b3792008-11-29 04:51:27 +00004161Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4162 // The type of __null will be int or long, depending on the size of
4163 // pointers on the target.
4164 QualType Ty;
4165 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4166 Ty = Context.IntTy;
4167 else
4168 Ty = Context.LongTy;
4169
4170 return new GNUNullExpr(Ty, TokenLoc);
4171}
4172
Chris Lattner005ed752008-01-04 18:04:52 +00004173bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4174 SourceLocation Loc,
4175 QualType DstType, QualType SrcType,
4176 Expr *SrcExpr, const char *Flavor) {
4177 // Decode the result (notice that AST's are still created for extensions).
4178 bool isInvalid = false;
4179 unsigned DiagKind;
4180 switch (ConvTy) {
4181 default: assert(0 && "Unknown conversion type");
4182 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004183 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004184 DiagKind = diag::ext_typecheck_convert_pointer_int;
4185 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004186 case IntToPointer:
4187 DiagKind = diag::ext_typecheck_convert_int_pointer;
4188 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004189 case IncompatiblePointer:
4190 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4191 break;
4192 case FunctionVoidPointer:
4193 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4194 break;
4195 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004196 // If the qualifiers lost were because we were applying the
4197 // (deprecated) C++ conversion from a string literal to a char*
4198 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4199 // Ideally, this check would be performed in
4200 // CheckPointerTypesForAssignment. However, that would require a
4201 // bit of refactoring (so that the second argument is an
4202 // expression, rather than a type), which should be done as part
4203 // of a larger effort to fix CheckPointerTypesForAssignment for
4204 // C++ semantics.
4205 if (getLangOptions().CPlusPlus &&
4206 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4207 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004208 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4209 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004210 case IntToBlockPointer:
4211 DiagKind = diag::err_int_to_block_pointer;
4212 break;
4213 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004214 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004215 break;
Steve Naroff19608432008-10-14 22:18:38 +00004216 case IncompatibleObjCQualifiedId:
4217 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4218 // it can give a more specific diagnostic.
4219 DiagKind = diag::warn_incompatible_qualified_id;
4220 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004221 case Incompatible:
4222 DiagKind = diag::err_typecheck_convert_incompatible;
4223 isInvalid = true;
4224 break;
4225 }
4226
Chris Lattner271d4c22008-11-24 05:29:24 +00004227 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4228 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004229 return isInvalid;
4230}
Anders Carlssond5201b92008-11-30 19:50:32 +00004231
4232bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4233{
4234 Expr::EvalResult EvalResult;
4235
4236 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4237 EvalResult.HasSideEffects) {
4238 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4239
4240 if (EvalResult.Diag) {
4241 // We only show the note if it's not the usual "invalid subexpression"
4242 // or if it's actually in a subexpression.
4243 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4244 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4245 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4246 }
4247
4248 return true;
4249 }
4250
4251 if (EvalResult.Diag) {
4252 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4253 E->getSourceRange();
4254
4255 // Print the reason it's not a constant.
4256 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4257 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4258 }
4259
4260 if (Result)
4261 *Result = EvalResult.Val.getInt();
4262 return false;
4263}