blob: 553c29e89720c6e7812157f3a7a4dbaea6dfa418 [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"
Douglas Gregor279272e2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#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 Lattner2cb744b2009-02-15 22:43:40 +000029
30/// DiagnoseUseOfDeprecatedDeclImpl - If the specified decl is deprecated or
31// unavailable, emit the corresponding diagnostics.
32void Sema::DiagnoseUseOfDeprecatedDeclImpl(NamedDecl *D, SourceLocation Loc) {
33 // See if the decl is deprecated.
34 if (D->getAttr<DeprecatedAttr>()) {
35 // If this reference happens *in* a deprecated function or method, don't
36 // warn. Implementing deprecated stuff requires referencing depreated
37 // stuff.
38 NamedDecl *ND = getCurFunctionOrMethodDecl();
39 if (ND == 0 || !ND->getAttr<DeprecatedAttr>())
40 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
41 }
42
43 // See if hte decl is unavailable.
44 if (D->getAttr<UnavailableAttr>())
45 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
46}
47
Chris Lattner299b8842008-07-25 21:10:04 +000048//===----------------------------------------------------------------------===//
49// Standard Promotions and Conversions
50//===----------------------------------------------------------------------===//
51
Chris Lattner299b8842008-07-25 21:10:04 +000052/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
53void Sema::DefaultFunctionArrayConversion(Expr *&E) {
54 QualType Ty = E->getType();
55 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
56
Chris Lattner299b8842008-07-25 21:10:04 +000057 if (Ty->isFunctionType())
58 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +000059 else if (Ty->isArrayType()) {
60 // In C90 mode, arrays only promote to pointers if the array expression is
61 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
62 // type 'array of type' is converted to an expression that has type 'pointer
63 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
64 // that has type 'array of type' ...". The relevant change is "an lvalue"
65 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +000066 //
67 // C++ 4.2p1:
68 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
69 // T" can be converted to an rvalue of type "pointer to T".
70 //
71 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
72 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +000073 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
74 }
Chris Lattner299b8842008-07-25 21:10:04 +000075}
76
77/// UsualUnaryConversions - Performs various conversions that are common to most
78/// operators (C99 6.3). The conversions of array and function types are
79/// sometimes surpressed. For example, the array->pointer conversion doesn't
80/// apply if the array is an argument to the sizeof or address (&) operators.
81/// In these instances, this routine should *not* be called.
82Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
83 QualType Ty = Expr->getType();
84 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
85
Chris Lattner299b8842008-07-25 21:10:04 +000086 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
87 ImpCastExprToType(Expr, Context.IntTy);
88 else
89 DefaultFunctionArrayConversion(Expr);
90
91 return Expr;
92}
93
Chris Lattner9305c3d2008-07-25 22:25:12 +000094/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
95/// do not have a prototype. Arguments that have type float are promoted to
96/// double. All other argument types are converted by UsualUnaryConversions().
97void Sema::DefaultArgumentPromotion(Expr *&Expr) {
98 QualType Ty = Expr->getType();
99 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
100
101 // If this is a 'float' (CVR qualified or typedef) promote to double.
102 if (const BuiltinType *BT = Ty->getAsBuiltinType())
103 if (BT->getKind() == BuiltinType::Float)
104 return ImpCastExprToType(Expr, Context.DoubleTy);
105
106 UsualUnaryConversions(Expr);
107}
108
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000109// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
110// will warn if the resulting type is not a POD type.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000111void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000112 DefaultArgumentPromotion(Expr);
113
114 if (!Expr->getType()->isPODType()) {
115 Diag(Expr->getLocStart(),
116 diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
117 Expr->getType() << CT;
118 }
119}
120
121
Chris Lattner299b8842008-07-25 21:10:04 +0000122/// UsualArithmeticConversions - Performs various conversions that are common to
123/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
124/// routine returns the first non-arithmetic type found. The client is
125/// responsible for emitting appropriate error diagnostics.
126/// FIXME: verify the conversion rules for "complex int" are consistent with
127/// GCC.
128QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
129 bool isCompAssign) {
130 if (!isCompAssign) {
131 UsualUnaryConversions(lhsExpr);
132 UsualUnaryConversions(rhsExpr);
133 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000134
Chris Lattner299b8842008-07-25 21:10:04 +0000135 // For conversion purposes, we ignore any qualifiers.
136 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000137 QualType lhs =
138 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
139 QualType rhs =
140 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000141
142 // If both types are identical, no conversion is needed.
143 if (lhs == rhs)
144 return lhs;
145
146 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
147 // The caller can deal with this (e.g. pointer + int).
148 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
149 return lhs;
150
151 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
152 if (!isCompAssign) {
153 ImpCastExprToType(lhsExpr, destType);
154 ImpCastExprToType(rhsExpr, destType);
155 }
156 return destType;
157}
158
159QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
160 // Perform the usual unary conversions. We do this early so that
161 // integral promotions to "int" can allow us to exit early, in the
162 // lhs == rhs check. Also, for conversion purposes, we ignore any
163 // qualifiers. For example, "const float" and "float" are
164 // equivalent.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000165 if (lhs->isPromotableIntegerType())
166 lhs = Context.IntTy;
167 else
168 lhs = lhs.getUnqualifiedType();
169 if (rhs->isPromotableIntegerType())
170 rhs = Context.IntTy;
171 else
172 rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000173
Chris Lattner299b8842008-07-25 21:10:04 +0000174 // If both types are identical, no conversion is needed.
175 if (lhs == rhs)
176 return lhs;
177
178 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
179 // The caller can deal with this (e.g. pointer + int).
180 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
181 return lhs;
182
183 // At this point, we have two different arithmetic types.
184
185 // Handle complex types first (C99 6.3.1.8p1).
186 if (lhs->isComplexType() || rhs->isComplexType()) {
187 // if we have an integer operand, the result is the complex type.
188 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
189 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000190 return lhs;
191 }
192 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
193 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000194 return rhs;
195 }
196 // This handles complex/complex, complex/float, or float/complex.
197 // When both operands are complex, the shorter operand is converted to the
198 // type of the longer, and that is the type of the result. This corresponds
199 // to what is done when combining two real floating-point operands.
200 // The fun begins when size promotion occur across type domains.
201 // From H&S 6.3.4: When one operand is complex and the other is a real
202 // floating-point type, the less precise type is converted, within it's
203 // real or complex domain, to the precision of the other type. For example,
204 // when combining a "long double" with a "double _Complex", the
205 // "double _Complex" is promoted to "long double _Complex".
206 int result = Context.getFloatingTypeOrder(lhs, rhs);
207
208 if (result > 0) { // The left side is bigger, convert rhs.
209 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000210 } else if (result < 0) { // The right side is bigger, convert lhs.
211 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000212 }
213 // At this point, lhs and rhs have the same rank/size. Now, make sure the
214 // domains match. This is a requirement for our implementation, C99
215 // does not require this promotion.
216 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
217 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000218 return rhs;
219 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000220 return lhs;
221 }
222 }
223 return lhs; // The domain/size match exactly.
224 }
225 // Now handle "real" floating types (i.e. float, double, long double).
226 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
227 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000228 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000229 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000230 return lhs;
231 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000232 if (rhs->isComplexIntegerType()) {
233 // convert rhs to the complex floating point type.
234 return Context.getComplexType(lhs);
235 }
236 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000237 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000238 return rhs;
239 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000240 if (lhs->isComplexIntegerType()) {
241 // convert lhs to the complex floating point type.
242 return Context.getComplexType(rhs);
243 }
Chris Lattner299b8842008-07-25 21:10:04 +0000244 // We have two real floating types, float/complex combos were handled above.
245 // Convert the smaller operand to the bigger result.
246 int result = Context.getFloatingTypeOrder(lhs, rhs);
Chris Lattner2cb744b2009-02-15 22:43:40 +0000247 if (result > 0) // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000248 return lhs;
Chris Lattner2cb744b2009-02-15 22:43:40 +0000249 assert(result < 0 && "illegal float comparison");
250 return rhs; // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000251 }
252 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
253 // Handle GCC complex int extension.
254 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
255 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
256
257 if (lhsComplexInt && rhsComplexInt) {
258 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
Chris Lattner2cb744b2009-02-15 22:43:40 +0000259 rhsComplexInt->getElementType()) >= 0)
260 return lhs; // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000261 return rhs;
262 } else if (lhsComplexInt && rhs->isIntegerType()) {
263 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000264 return lhs;
265 } else if (rhsComplexInt && lhs->isIntegerType()) {
266 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000267 return rhs;
268 }
269 }
270 // Finally, we have two differing integer types.
271 // The rules for this case are in C99 6.3.1.8
272 int compare = Context.getIntegerTypeOrder(lhs, rhs);
273 bool lhsSigned = lhs->isSignedIntegerType(),
274 rhsSigned = rhs->isSignedIntegerType();
275 QualType destType;
276 if (lhsSigned == rhsSigned) {
277 // Same signedness; use the higher-ranked type
278 destType = compare >= 0 ? lhs : rhs;
279 } else if (compare != (lhsSigned ? 1 : -1)) {
280 // The unsigned type has greater than or equal rank to the
281 // signed type, so use the unsigned type
282 destType = lhsSigned ? rhs : lhs;
283 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
284 // The two types are different widths; if we are here, that
285 // means the signed type is larger than the unsigned type, so
286 // use the signed type.
287 destType = lhsSigned ? lhs : rhs;
288 } else {
289 // The signed type is higher-ranked than the unsigned type,
290 // but isn't actually any bigger (like unsigned int and long
291 // on most 32-bit systems). Use the unsigned type corresponding
292 // to the signed type.
293 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
294 }
Chris Lattner299b8842008-07-25 21:10:04 +0000295 return destType;
296}
297
298//===----------------------------------------------------------------------===//
299// Semantic Analysis for various Expression Types
300//===----------------------------------------------------------------------===//
301
302
Steve Naroff87d58b42007-09-16 03:34:24 +0000303/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000304/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
305/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
306/// multiple tokens. However, the common case is that StringToks points to one
307/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000308///
309Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000310Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000311 assert(NumStringToks && "Must have at least one string!");
312
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000313 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000314 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000315 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000316
317 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
318 for (unsigned i = 0; i != NumStringToks; ++i)
319 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000320
Chris Lattnera6dcce32008-02-11 00:02:17 +0000321 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000322 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000323 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000324
325 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
326 if (getLangOptions().CPlusPlus)
327 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000328
Chris Lattnera6dcce32008-02-11 00:02:17 +0000329 // Get an array type for the string, according to C99 6.4.5. This includes
330 // the nul terminator character as well as the string length for pascal
331 // strings.
332 StrTy = Context.getConstantArrayType(StrTy,
333 llvm::APInt(32, Literal.GetStringLength()+1),
334 ArrayType::Normal, 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000335
Chris Lattner4b009652007-07-25 00:24:17 +0000336 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Ted Kremenek4f530a92009-02-06 19:55:15 +0000337 return Owned(new (Context) StringLiteral(Context, Literal.GetString(),
Steve Naroff774e4152009-01-21 00:14:39 +0000338 Literal.GetStringLength(),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000339 Literal.AnyWide, StrTy,
340 StringToks[0].getLocation(),
341 StringToks[NumStringToks-1].getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000342}
343
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000344/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
345/// CurBlock to VD should cause it to be snapshotted (as we do for auto
346/// variables defined outside the block) or false if this is not needed (e.g.
347/// for values inside the block or for globals).
348///
349/// FIXME: This will create BlockDeclRefExprs for global variables,
350/// function references, etc which is suboptimal :) and breaks
351/// things like "integer constant expression" tests.
352static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
353 ValueDecl *VD) {
354 // If the value is defined inside the block, we couldn't snapshot it even if
355 // we wanted to.
356 if (CurBlock->TheDecl == VD->getDeclContext())
357 return false;
358
359 // If this is an enum constant or function, it is constant, don't snapshot.
360 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
361 return false;
362
363 // If this is a reference to an extern, static, or global variable, no need to
364 // snapshot it.
365 // FIXME: What about 'const' variables in C++?
366 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
367 return Var->hasLocalStorage();
368
369 return true;
370}
371
372
373
Steve Naroff0acc9c92007-09-15 18:49:24 +0000374/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000375/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000376/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000377/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000378/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000379Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
380 IdentifierInfo &II,
381 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000382 const CXXScopeSpec *SS,
383 bool isAddressOfOperand) {
384 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000385 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000386}
387
Douglas Gregor566782a2009-01-06 05:10:23 +0000388/// BuildDeclRefExpr - Build either a DeclRefExpr or a
389/// QualifiedDeclRefExpr based on whether or not SS is a
390/// nested-name-specifier.
Sebastian Redl0c9da212009-02-03 20:19:35 +0000391DeclRefExpr *
392Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
393 bool TypeDependent, bool ValueDependent,
394 const CXXScopeSpec *SS) {
Steve Naroff774e4152009-01-21 00:14:39 +0000395 if (SS && !SS->isEmpty())
396 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000397 ValueDependent, SS->getRange().getBegin());
Steve Naroff774e4152009-01-21 00:14:39 +0000398 else
399 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000400}
401
Douglas Gregor723d3332009-01-07 00:43:41 +0000402/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
403/// variable corresponding to the anonymous union or struct whose type
404/// is Record.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000405static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000406 assert(Record->isAnonymousStructOrUnion() &&
407 "Record must be an anonymous struct or union!");
408
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000409 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000410 // be an O(1) operation rather than a slow walk through DeclContext's
411 // vector (which itself will be eliminated). DeclGroups might make
412 // this even better.
413 DeclContext *Ctx = Record->getDeclContext();
414 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
415 DEnd = Ctx->decls_end();
416 D != DEnd; ++D) {
417 if (*D == Record) {
418 // The object for the anonymous struct/union directly
419 // follows its type in the list of declarations.
420 ++D;
421 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000422 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000423 return *D;
424 }
425 }
426
427 assert(false && "Missing object for anonymous record");
428 return 0;
429}
430
Sebastian Redlcd883f72009-01-18 18:53:16 +0000431Sema::OwningExprResult
Douglas Gregor723d3332009-01-07 00:43:41 +0000432Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
433 FieldDecl *Field,
434 Expr *BaseObjectExpr,
435 SourceLocation OpLoc) {
436 assert(Field->getDeclContext()->isRecord() &&
437 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
438 && "Field must be stored inside an anonymous struct or union");
439
440 // Construct the sequence of field member references
441 // we'll have to perform to get to the field in the anonymous
442 // union/struct. The list of members is built from the field
443 // outward, so traverse it backwards to go from an object in
444 // the current context to the field we found.
445 llvm::SmallVector<FieldDecl *, 4> AnonFields;
446 AnonFields.push_back(Field);
447 VarDecl *BaseObject = 0;
448 DeclContext *Ctx = Field->getDeclContext();
449 do {
450 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000451 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000452 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
453 AnonFields.push_back(AnonField);
454 else {
455 BaseObject = cast<VarDecl>(AnonObject);
456 break;
457 }
458 Ctx = Ctx->getParent();
459 } while (Ctx->isRecord() &&
460 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
461
462 // Build the expression that refers to the base object, from
463 // which we will build a sequence of member references to each
464 // of the anonymous union objects and, eventually, the field we
465 // found via name lookup.
466 bool BaseObjectIsPointer = false;
467 unsigned ExtraQuals = 0;
468 if (BaseObject) {
469 // BaseObject is an anonymous struct/union variable (and is,
470 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000471 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff774e4152009-01-21 00:14:39 +0000472 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000473 SourceLocation());
474 ExtraQuals
475 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
476 } else if (BaseObjectExpr) {
477 // The caller provided the base object expression. Determine
478 // whether its a pointer and whether it adds any qualifiers to the
479 // anonymous struct/union fields we're looking into.
480 QualType ObjectType = BaseObjectExpr->getType();
481 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
482 BaseObjectIsPointer = true;
483 ObjectType = ObjectPtr->getPointeeType();
484 }
485 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
486 } else {
487 // We've found a member of an anonymous struct/union that is
488 // inside a non-anonymous struct/union, so in a well-formed
489 // program our base object expression is "this".
490 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
491 if (!MD->isStatic()) {
492 QualType AnonFieldType
493 = Context.getTagDeclType(
494 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
495 QualType ThisType = Context.getTagDeclType(MD->getParent());
496 if ((Context.getCanonicalType(AnonFieldType)
497 == Context.getCanonicalType(ThisType)) ||
498 IsDerivedFrom(ThisType, AnonFieldType)) {
499 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000500 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor723d3332009-01-07 00:43:41 +0000501 MD->getThisType(Context));
502 BaseObjectIsPointer = true;
503 }
504 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000505 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
506 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000507 }
508 ExtraQuals = MD->getTypeQualifiers();
509 }
510
511 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000512 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
513 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000514 }
515
516 // Build the implicit member references to the field of the
517 // anonymous struct/union.
518 Expr *Result = BaseObjectExpr;
519 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
520 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
521 FI != FIEnd; ++FI) {
522 QualType MemberType = (*FI)->getType();
523 if (!(*FI)->isMutable()) {
524 unsigned combinedQualifiers
525 = MemberType.getCVRQualifiers() | ExtraQuals;
526 MemberType = MemberType.getQualifiedType(combinedQualifiers);
527 }
Steve Naroff774e4152009-01-21 00:14:39 +0000528 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
529 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000530 BaseObjectIsPointer = false;
531 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
532 OpLoc = SourceLocation();
533 }
534
Sebastian Redlcd883f72009-01-18 18:53:16 +0000535 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000536}
537
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000538/// ActOnDeclarationNameExpr - The parser has read some kind of name
539/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
540/// performs lookup on that name and returns an expression that refers
541/// to that name. This routine isn't directly called from the parser,
542/// because the parser doesn't know about DeclarationName. Rather,
543/// this routine is called by ActOnIdentifierExpr,
544/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
545/// which form the DeclarationName from the corresponding syntactic
546/// forms.
547///
548/// HasTrailingLParen indicates whether this identifier is used in a
549/// function call context. LookupCtx is only used for a C++
550/// qualified-id (foo::bar) to indicate the class or namespace that
551/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000552///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000553/// isAddressOfOperand means that this expression is the direct operand
554/// of an address-of operator. This matters because this is the only
555/// situation where a qualified name referencing a non-static member may
556/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000557Sema::OwningExprResult
558Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
559 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000560 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000561 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000562 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000563 if (SS && SS->isInvalid())
564 return ExprError();
Douglas Gregor411889e2009-02-13 23:20:09 +0000565 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
566 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000567
Douglas Gregor09be81b2009-02-04 17:27:36 +0000568 NamedDecl *D = 0;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000569 if (Lookup.isAmbiguous()) {
570 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
571 SS && SS->isSet() ? SS->getRange()
572 : SourceRange());
573 return ExprError();
574 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000575 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000576
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000577 // If this reference is in an Objective-C method, then ivar lookup happens as
578 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000579 IdentifierInfo *II = Name.getAsIdentifierInfo();
580 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000581 // There are two cases to handle here. 1) scoped lookup could have failed,
582 // in which case we should look for an ivar. 2) scoped lookup could have
583 // found a decl, but that decl is outside the current method (i.e. a global
584 // variable). In these two cases, we do a lookup for an ivar with this
585 // name, if the lookup suceeds, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000586 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000587 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000588 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000589 // Check if referencing a field with __attribute__((deprecated)).
590 DiagnoseUseOfDeprecatedDecl(IV, Loc);
591
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000592 // FIXME: This should use a new expr for a direct reference, don't turn
593 // this into Self->ivar, just return a BareIVarExpr or something.
594 IdentifierInfo &II = Context.Idents.get("self");
Sebastian Redlcd883f72009-01-18 18:53:16 +0000595 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Steve Naroff774e4152009-01-21 00:14:39 +0000596 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
597 Loc, static_cast<Expr*>(SelfExpr.release()),
Sebastian Redlcd883f72009-01-18 18:53:16 +0000598 true, true);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000599 Context.setFieldDecl(IFace, IV, MRef);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000600 return Owned(MRef);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000601 }
602 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000603 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000604 if (D == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000605 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000606 getCurMethodDecl()->getClassInterface()));
Steve Naroff774e4152009-01-21 00:14:39 +0000607 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000608 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000609 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000610
611 if (getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
612 HasTrailingLParen && D == 0) {
613 // We've seen something of the form
614 //
615 // identifier(
616 //
617 // and we did not find any entity by the name
618 // "identifier". However, this identifier is still subject to
619 // argument-dependent lookup, so keep track of the name.
620 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
621 Context.OverloadTy,
622 Loc));
623 }
624
Chris Lattner4b009652007-07-25 00:24:17 +0000625 if (D == 0) {
626 // Otherwise, this could be an implicitly declared function reference (legal
627 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000628 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000629 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000630 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000631 else {
632 // If this name wasn't predeclared and if this is not a function call,
633 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000634 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000635 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
636 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000637 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
638 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000639 return ExprError(Diag(Loc, diag::err_undeclared_use)
640 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000641 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000642 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000643 }
644 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000645
Sebastian Redl0c9da212009-02-03 20:19:35 +0000646 // If this is an expression of the form &Class::member, don't build an
647 // implicit member ref, because we want a pointer to the member in general,
648 // not any specific instance's member.
649 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000650 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
Douglas Gregor09be81b2009-02-04 17:27:36 +0000651 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000652 QualType DType;
653 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
654 DType = FD->getType().getNonReferenceType();
655 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
656 DType = Method->getType();
657 } else if (isa<OverloadedFunctionDecl>(D)) {
658 DType = Context.OverloadTy;
659 }
660 // Could be an inner type. That's diagnosed below, so ignore it here.
661 if (!DType.isNull()) {
662 // The pointer is type- and value-dependent if it points into something
663 // dependent.
664 bool Dependent = false;
665 for (; DC; DC = DC->getParent()) {
666 // FIXME: could stop early at namespace scope.
667 if (DC->isRecord()) {
668 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
669 if (Context.getTypeDeclType(Record)->isDependentType()) {
670 Dependent = true;
671 break;
672 }
673 }
674 }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000675 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000676 }
677 }
678 }
679
Douglas Gregor723d3332009-01-07 00:43:41 +0000680 // We may have found a field within an anonymous union or struct
681 // (C++ [class.union]).
682 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
683 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
684 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000685
Douglas Gregor3257fb52008-12-22 05:46:06 +0000686 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
687 if (!MD->isStatic()) {
688 // C++ [class.mfct.nonstatic]p2:
689 // [...] if name lookup (3.4.1) resolves the name in the
690 // id-expression to a nonstatic nontype member of class X or of
691 // a base class of X, the id-expression is transformed into a
692 // class member access expression (5.2.5) using (*this) (9.3.2)
693 // as the postfix-expression to the left of the '.' operator.
694 DeclContext *Ctx = 0;
695 QualType MemberType;
696 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
697 Ctx = FD->getDeclContext();
698 MemberType = FD->getType();
699
700 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
701 MemberType = RefType->getPointeeType();
702 else if (!FD->isMutable()) {
703 unsigned combinedQualifiers
704 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
705 MemberType = MemberType.getQualifiedType(combinedQualifiers);
706 }
707 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
708 if (!Method->isStatic()) {
709 Ctx = Method->getParent();
710 MemberType = Method->getType();
711 }
712 } else if (OverloadedFunctionDecl *Ovl
713 = dyn_cast<OverloadedFunctionDecl>(D)) {
714 for (OverloadedFunctionDecl::function_iterator
715 Func = Ovl->function_begin(),
716 FuncEnd = Ovl->function_end();
717 Func != FuncEnd; ++Func) {
718 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
719 if (!DMethod->isStatic()) {
720 Ctx = Ovl->getDeclContext();
721 MemberType = Context.OverloadTy;
722 break;
723 }
724 }
725 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000726
727 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000728 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
729 QualType ThisType = Context.getTagDeclType(MD->getParent());
730 if ((Context.getCanonicalType(CtxType)
731 == Context.getCanonicalType(ThisType)) ||
732 IsDerivedFrom(ThisType, CtxType)) {
733 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000734 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Douglas Gregor3257fb52008-12-22 05:46:06 +0000735 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +0000736 return Owned(new (Context) MemberExpr(This, true, D,
Sebastian Redlcd883f72009-01-18 18:53:16 +0000737 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000738 }
739 }
740 }
741 }
742
Douglas Gregor8acb7272008-12-11 16:49:14 +0000743 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000744 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
745 if (MD->isStatic())
746 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000747 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
748 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000749 }
750
Douglas Gregor3257fb52008-12-22 05:46:06 +0000751 // Any other ways we could have found the field in a well-formed
752 // program would have been turned into implicit member expressions
753 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000754 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
755 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000756 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000757
Chris Lattner4b009652007-07-25 00:24:17 +0000758 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000759 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000760 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000761 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000762 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000763 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000764
Steve Naroffd6163f32008-09-05 22:11:13 +0000765 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000766 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000767 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
768 false, false, SS));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000769 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
770 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
771 false, false, SS));
Steve Naroffd6163f32008-09-05 22:11:13 +0000772 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000773
Chris Lattnerd9037472009-02-15 01:38:09 +0000774 // Check if referencing an identifier with __attribute__((deprecated)).
Chris Lattner2cb744b2009-02-15 22:43:40 +0000775 DiagnoseUseOfDeprecatedDecl(VD, Loc);
Chris Lattnerd9037472009-02-15 01:38:09 +0000776
Douglas Gregor48840c72008-12-10 23:01:14 +0000777 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000778 // Warn about constructs like:
779 // if (void *X = foo()) { ... } else { X }.
780 // In the else block, the pointer is always false.
Douglas Gregor48840c72008-12-10 23:01:14 +0000781 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
782 Scope *CheckS = S;
783 while (CheckS) {
784 if (CheckS->isWithinElse() &&
785 CheckS->getControlParent()->isDeclScope(Var)) {
786 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000787 ExprError(Diag(Loc, diag::warn_value_always_false)
788 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000789 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000790 ExprError(Diag(Loc, diag::warn_value_always_zero)
791 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000792 break;
793 }
794
795 // Move up one more control parent to check again.
796 CheckS = CheckS->getControlParent();
797 if (CheckS)
798 CheckS = CheckS->getParent();
799 }
800 }
801 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000802
803 // Only create DeclRefExpr's for valid Decl's.
804 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000805 return ExprError();
806
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000807 // If the identifier reference is inside a block, and it refers to a value
808 // that is outside the block, create a BlockDeclRefExpr instead of a
809 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
810 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000811 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000812 // We do not do this for things like enum constants, global variables, etc,
813 // as they do not get snapshotted.
814 //
815 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000816 // The BlocksAttr indicates the variable is bound by-reference.
817 if (VD->getAttr<BlocksAttr>())
Steve Naroff774e4152009-01-21 00:14:39 +0000818 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000819 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000820
Steve Naroff52059382008-10-10 01:28:17 +0000821 // Variable will be bound by-copy, make it const within the closure.
822 VD->getType().addConst();
Steve Naroff774e4152009-01-21 00:14:39 +0000823 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000824 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000825 }
826 // If this reference is not in a block or if the referenced variable is
827 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000828
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000829 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000830 bool ValueDependent = false;
831 if (getLangOptions().CPlusPlus) {
832 // C++ [temp.dep.expr]p3:
833 // An id-expression is type-dependent if it contains:
834 // - an identifier that was declared with a dependent type,
835 if (VD->getType()->isDependentType())
836 TypeDependent = true;
837 // - FIXME: a template-id that is dependent,
838 // - a conversion-function-id that specifies a dependent type,
839 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
840 Name.getCXXNameType()->isDependentType())
841 TypeDependent = true;
842 // - a nested-name-specifier that contains a class-name that
843 // names a dependent type.
844 else if (SS && !SS->isEmpty()) {
845 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
846 DC; DC = DC->getParent()) {
847 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000848 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000849 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
850 if (Context.getTypeDeclType(Record)->isDependentType()) {
851 TypeDependent = true;
852 break;
853 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000854 }
855 }
856 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000857
Douglas Gregora5d84612008-12-10 20:57:37 +0000858 // C++ [temp.dep.constexpr]p2:
859 //
860 // An identifier is value-dependent if it is:
861 // - a name declared with a dependent type,
862 if (TypeDependent)
863 ValueDependent = true;
864 // - the name of a non-type template parameter,
865 else if (isa<NonTypeTemplateParmDecl>(VD))
866 ValueDependent = true;
867 // - a constant with integral or enumeration type and is
868 // initialized with an expression that is value-dependent
869 // (FIXME!).
870 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000871
Sebastian Redlcd883f72009-01-18 18:53:16 +0000872 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
873 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000874}
875
Sebastian Redlcd883f72009-01-18 18:53:16 +0000876Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
877 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000878 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000879
Chris Lattner4b009652007-07-25 00:24:17 +0000880 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000881 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000882 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
883 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
884 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000885 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000886
Chris Lattner7e637512008-01-12 08:14:25 +0000887 // Pre-defined identifiers are of type char[x], where x is the length of the
888 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000889 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000890 if (FunctionDecl *FD = getCurFunctionDecl())
891 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000892 else if (ObjCMethodDecl *MD = getCurMethodDecl())
893 Length = MD->getSynthesizedMethodSize();
894 else {
895 Diag(Loc, diag::ext_predef_outside_function);
896 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
897 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
898 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000899
900
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000901 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000902 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000903 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +0000904 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +0000905}
906
Sebastian Redlcd883f72009-01-18 18:53:16 +0000907Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000908 llvm::SmallString<16> CharBuffer;
909 CharBuffer.resize(Tok.getLength());
910 const char *ThisTokBegin = &CharBuffer[0];
911 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000912
Chris Lattner4b009652007-07-25 00:24:17 +0000913 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
914 Tok.getLocation(), PP);
915 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000916 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +0000917
918 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
919
Sebastian Redl75324932009-01-20 22:23:13 +0000920 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
921 Literal.isWide(),
922 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000923}
924
Sebastian Redlcd883f72009-01-18 18:53:16 +0000925Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
926 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +0000927 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
928 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +0000929 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +0000930 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +0000931 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +0000932 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +0000933 }
Ted Kremenekdbde2282009-01-13 23:19:12 +0000934
Chris Lattner4b009652007-07-25 00:24:17 +0000935 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000936 // Add padding so that NumericLiteralParser can overread by one character.
937 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000938 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +0000939
Chris Lattner4b009652007-07-25 00:24:17 +0000940 // Get the spelling of the token, which eliminates trigraphs, etc.
941 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000942
Chris Lattner4b009652007-07-25 00:24:17 +0000943 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
944 Tok.getLocation(), PP);
945 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000946 return ExprError();
947
Chris Lattner1de66eb2007-08-26 03:42:43 +0000948 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000949
Chris Lattner1de66eb2007-08-26 03:42:43 +0000950 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000951 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000952 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000953 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000954 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000955 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000956 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000957 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000958
959 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
960
Ted Kremenekddedbe22007-11-29 00:56:49 +0000961 // isExact will be set by GetFloatValue().
962 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +0000963 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
964 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +0000965
Chris Lattner1de66eb2007-08-26 03:42:43 +0000966 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000967 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +0000968 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000969 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000970
Neil Booth7421e9c2007-08-29 22:00:19 +0000971 // long long is a C99 feature.
972 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000973 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000974 Diag(Tok.getLocation(), diag::ext_longlong);
975
Chris Lattner4b009652007-07-25 00:24:17 +0000976 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000977 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000978
Chris Lattner4b009652007-07-25 00:24:17 +0000979 if (Literal.GetIntegerValue(ResultVal)) {
980 // If this value didn't fit into uintmax_t, warn and force to ull.
981 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000982 Ty = Context.UnsignedLongLongTy;
983 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000984 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000985 } else {
986 // If this value fits into a ULL, try to figure out what else it fits into
987 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000988
Chris Lattner4b009652007-07-25 00:24:17 +0000989 // Octal, Hexadecimal, and integers with a U suffix are allowed to
990 // be an unsigned int.
991 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
992
993 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000994 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000995 if (!Literal.isLong && !Literal.isLongLong) {
996 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000997 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000998
Chris Lattner4b009652007-07-25 00:24:17 +0000999 // Does it fit in a unsigned int?
1000 if (ResultVal.isIntN(IntSize)) {
1001 // Does it fit in a signed int?
1002 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001003 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001004 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001005 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001006 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001007 }
Chris Lattner4b009652007-07-25 00:24:17 +00001008 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001009
Chris Lattner4b009652007-07-25 00:24:17 +00001010 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001011 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001012 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001013
Chris Lattner4b009652007-07-25 00:24:17 +00001014 // Does it fit in a unsigned long?
1015 if (ResultVal.isIntN(LongSize)) {
1016 // Does it fit in a signed long?
1017 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001018 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001019 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001020 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001021 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001022 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001023 }
1024
Chris Lattner4b009652007-07-25 00:24:17 +00001025 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001026 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001027 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001028
Chris Lattner4b009652007-07-25 00:24:17 +00001029 // Does it fit in a unsigned long long?
1030 if (ResultVal.isIntN(LongLongSize)) {
1031 // Does it fit in a signed long long?
1032 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001033 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001034 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001035 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001036 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001037 }
1038 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001039
Chris Lattner4b009652007-07-25 00:24:17 +00001040 // If we still couldn't decide a type, we probably have something that
1041 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001042 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001043 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001044 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001045 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001046 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001047
Chris Lattnere4068872008-05-09 05:59:00 +00001048 if (ResultVal.getBitWidth() != Width)
1049 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001050 }
Sebastian Redl75324932009-01-20 22:23:13 +00001051 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001052 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001053
Chris Lattner1de66eb2007-08-26 03:42:43 +00001054 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1055 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001056 Res = new (Context) ImaginaryLiteral(Res,
1057 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001058
1059 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001060}
1061
Sebastian Redlcd883f72009-01-18 18:53:16 +00001062Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1063 SourceLocation R, ExprArg Val) {
1064 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001065 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001066 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001067}
1068
1069/// The UsualUnaryConversions() function is *not* called by this routine.
1070/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001071bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1072 SourceLocation OpLoc,
1073 const SourceRange &ExprRange,
1074 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +00001075 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001076 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001077 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001078 if (isSizeof)
1079 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1080 return false;
1081 }
1082
1083 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001084 Diag(OpLoc, diag::ext_sizeof_void_type)
1085 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001086 return false;
1087 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001088
Chris Lattner159fe082009-01-24 19:46:37 +00001089 return DiagnoseIncompleteType(OpLoc, exprType,
1090 isSizeof ? diag::err_sizeof_incomplete_type :
1091 diag::err_alignof_incomplete_type,
1092 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001093}
1094
Chris Lattner8d9f7962009-01-24 20:17:12 +00001095bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1096 const SourceRange &ExprRange) {
1097 E = E->IgnoreParens();
1098
1099 // alignof decl is always ok.
1100 if (isa<DeclRefExpr>(E))
1101 return false;
1102
1103 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1104 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1105 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001106 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001107 return true;
1108 }
1109 // Other fields are ok.
1110 return false;
1111 }
1112 }
1113 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1114}
1115
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001116/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1117/// the same for @c alignof and @c __alignof
1118/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001119Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001120Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1121 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001122 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001123 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001124
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001125 QualType ArgTy;
1126 SourceRange Range;
1127 if (isType) {
1128 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1129 Range = ArgRange;
Chris Lattnera78909b2009-01-24 19:49:13 +00001130
1131 // Verify that the operand is valid.
1132 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1133 return ExprError();
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001134 } else {
1135 // Get the end location.
1136 Expr *ArgEx = (Expr *)TyOrEx;
1137 Range = ArgEx->getSourceRange();
1138 ArgTy = ArgEx->getType();
Chris Lattnera78909b2009-01-24 19:49:13 +00001139
1140 // Verify that the operand is valid.
Chris Lattner8d9f7962009-01-24 20:17:12 +00001141 bool isInvalid;
Chris Lattner364a42d2009-01-24 21:29:22 +00001142 if (!isSizeof) {
Chris Lattner8d9f7962009-01-24 20:17:12 +00001143 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattner364a42d2009-01-24 21:29:22 +00001144 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1145 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1146 isInvalid = true;
1147 } else {
1148 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1149 }
Chris Lattner8d9f7962009-01-24 20:17:12 +00001150
1151 if (isInvalid) {
Chris Lattnera78909b2009-01-24 19:49:13 +00001152 DeleteExpr(ArgEx);
1153 return ExprError();
1154 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001155 }
1156
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001157 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff774e4152009-01-21 00:14:39 +00001158 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner159fe082009-01-24 19:46:37 +00001159 Context.getSizeType(), OpLoc,
1160 Range.getEnd()));
Chris Lattner4b009652007-07-25 00:24:17 +00001161}
1162
Chris Lattner5110ad52007-08-24 21:41:10 +00001163QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +00001164 DefaultFunctionArrayConversion(V);
1165
Chris Lattnera16e42d2007-08-26 05:39:26 +00001166 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001167 if (const ComplexType *CT = V->getType()->getAsComplexType())
1168 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001169
1170 // Otherwise they pass through real integer and floating point types here.
1171 if (V->getType()->isArithmeticType())
1172 return V->getType();
1173
1174 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +00001175 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001176 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001177}
1178
1179
Chris Lattner4b009652007-07-25 00:24:17 +00001180
Sebastian Redl8b769972009-01-19 00:08:26 +00001181Action::OwningExprResult
1182Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1183 tok::TokenKind Kind, ExprArg Input) {
1184 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001185
Chris Lattner4b009652007-07-25 00:24:17 +00001186 UnaryOperator::Opcode Opc;
1187 switch (Kind) {
1188 default: assert(0 && "Unknown unary op!");
1189 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1190 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1191 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001192
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001193 if (getLangOptions().CPlusPlus &&
1194 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1195 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001196 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001197 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1198
1199 // C++ [over.inc]p1:
1200 //
1201 // [...] If the function is a member function with one
1202 // parameter (which shall be of type int) or a non-member
1203 // function with two parameters (the second of which shall be
1204 // of type int), it defines the postfix increment operator ++
1205 // for objects of that type. When the postfix increment is
1206 // called as a result of using the ++ operator, the int
1207 // argument will have value zero.
1208 Expr *Args[2] = {
1209 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001210 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1211 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001212 };
1213
1214 // Build the candidate set for overloading
1215 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00001216 if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet))
1217 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001218
1219 // Perform overload resolution.
1220 OverloadCandidateSet::iterator Best;
1221 switch (BestViableFunction(CandidateSet, Best)) {
1222 case OR_Success: {
1223 // We found a built-in operator or an overloaded operator.
1224 FunctionDecl *FnDecl = Best->Function;
1225
1226 if (FnDecl) {
1227 // We matched an overloaded operator. Build a call to that
1228 // operator.
1229
1230 // Convert the arguments.
1231 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1232 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001233 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001234 } else {
1235 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001236 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001237 FnDecl->getParamDecl(0)->getType(),
1238 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001239 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001240 }
1241
1242 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001243 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001244 = FnDecl->getType()->getAsFunctionType()->getResultType();
1245 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001246
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001247 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001248 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001249 SourceLocation());
1250 UsualUnaryConversions(FnExpr);
1251
Sebastian Redl8b769972009-01-19 00:08:26 +00001252 Input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001253 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
1254 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001255 } else {
1256 // We matched a built-in operator. Convert the arguments, then
1257 // break out so that we will build the appropriate built-in
1258 // operator node.
1259 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1260 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001261 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001262
1263 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001264 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001265 }
1266
1267 case OR_No_Viable_Function:
1268 // No viable function; fall through to handling this as a
1269 // built-in operator, which will produce an error message for us.
1270 break;
1271
1272 case OR_Ambiguous:
1273 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1274 << UnaryOperator::getOpcodeStr(Opc)
1275 << Arg->getSourceRange();
1276 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001277 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001278 }
1279
1280 // Either we found no viable overloaded operator or we matched a
1281 // built-in operator. In either case, fall through to trying to
1282 // build a built-in operation.
1283 }
1284
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001285 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1286 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001287 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001288 return ExprError();
1289 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001290 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001291}
1292
Sebastian Redl8b769972009-01-19 00:08:26 +00001293Action::OwningExprResult
1294Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1295 ExprArg Idx, SourceLocation RLoc) {
1296 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1297 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001298
Douglas Gregor80723c52008-11-19 17:17:41 +00001299 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001300 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001301 LHSExp->getType()->isEnumeralType() ||
1302 RHSExp->getType()->isRecordType() ||
1303 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001304 // Add the appropriate overloaded operators (C++ [over.match.oper])
1305 // to the candidate set.
1306 OverloadCandidateSet CandidateSet;
1307 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor48a87322009-02-04 16:44:47 +00001308 if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1309 SourceRange(LLoc, RLoc)))
1310 return ExprError();
Sebastian Redl8b769972009-01-19 00:08:26 +00001311
Douglas Gregor80723c52008-11-19 17:17:41 +00001312 // Perform overload resolution.
1313 OverloadCandidateSet::iterator Best;
1314 switch (BestViableFunction(CandidateSet, Best)) {
1315 case OR_Success: {
1316 // We found a built-in operator or an overloaded operator.
1317 FunctionDecl *FnDecl = Best->Function;
1318
1319 if (FnDecl) {
1320 // We matched an overloaded operator. Build a call to that
1321 // operator.
1322
1323 // Convert the arguments.
1324 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1325 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1326 PerformCopyInitialization(RHSExp,
1327 FnDecl->getParamDecl(0)->getType(),
1328 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001329 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001330 } else {
1331 // Convert the arguments.
1332 if (PerformCopyInitialization(LHSExp,
1333 FnDecl->getParamDecl(0)->getType(),
1334 "passing") ||
1335 PerformCopyInitialization(RHSExp,
1336 FnDecl->getParamDecl(1)->getType(),
1337 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001338 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001339 }
1340
1341 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001342 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001343 = FnDecl->getType()->getAsFunctionType()->getResultType();
1344 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001345
Douglas Gregor80723c52008-11-19 17:17:41 +00001346 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001347 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Douglas Gregor80723c52008-11-19 17:17:41 +00001348 SourceLocation());
1349 UsualUnaryConversions(FnExpr);
1350
Sebastian Redl8b769972009-01-19 00:08:26 +00001351 Base.release();
1352 Idx.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001353 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001354 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001355 } else {
1356 // We matched a built-in operator. Convert the arguments, then
1357 // break out so that we will build the appropriate built-in
1358 // operator node.
1359 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1360 "passing") ||
1361 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1362 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001363 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001364
1365 break;
1366 }
1367 }
1368
1369 case OR_No_Viable_Function:
1370 // No viable function; fall through to handling this as a
1371 // built-in operator, which will produce an error message for us.
1372 break;
1373
1374 case OR_Ambiguous:
1375 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1376 << "[]"
1377 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1378 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001379 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001380 }
1381
1382 // Either we found no viable overloaded operator or we matched a
1383 // built-in operator. In either case, fall through to trying to
1384 // build a built-in operation.
1385 }
1386
Chris Lattner4b009652007-07-25 00:24:17 +00001387 // Perform default conversions.
1388 DefaultFunctionArrayConversion(LHSExp);
1389 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001390
Chris Lattner4b009652007-07-25 00:24:17 +00001391 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1392
1393 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001394 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001395 // in the subscript position. As a result, we need to derive the array base
1396 // and index from the expression types.
1397 Expr *BaseExpr, *IndexExpr;
1398 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001399 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001400 BaseExpr = LHSExp;
1401 IndexExpr = RHSExp;
1402 // FIXME: need to deal with const...
1403 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001404 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001405 // Handle the uncommon case of "123[Ptr]".
1406 BaseExpr = RHSExp;
1407 IndexExpr = LHSExp;
1408 // FIXME: need to deal with const...
1409 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001410 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1411 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001412 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001413
Chris Lattner4b009652007-07-25 00:24:17 +00001414 // FIXME: need to deal with const...
1415 ResultType = VTy->getElementType();
1416 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001417 return ExprError(Diag(LHSExp->getLocStart(),
1418 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1419 }
Chris Lattner4b009652007-07-25 00:24:17 +00001420 // C99 6.5.2.1p1
1421 if (!IndexExpr->getType()->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001422 return ExprError(Diag(IndexExpr->getLocStart(),
1423 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001424
1425 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1426 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001427 // void (*)(int)) and pointers to incomplete types. Functions are not
1428 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001429 if (!ResultType->isObjectType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001430 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001431 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001432 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001433
Sebastian Redl8b769972009-01-19 00:08:26 +00001434 Base.release();
1435 Idx.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001436 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1437 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001438}
1439
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001440QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001441CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001442 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001443 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001444
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001445 // The vector accessor can't exceed the number of elements.
1446 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001447
1448 // This flag determines whether or not the component is one of the four
1449 // special names that indicate a subset of exactly half the elements are
1450 // to be selected.
1451 bool HalvingSwizzle = false;
1452
1453 // This flag determines whether or not CompName has an 's' char prefix,
1454 // indicating that it is a string of hex values to be used as vector indices.
1455 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001456
1457 // Check that we've found one of the special components, or that the component
1458 // names must come from the same set.
1459 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001460 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1461 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001462 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001463 do
1464 compStr++;
1465 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001466 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001467 do
1468 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001469 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001470 }
Nate Begeman1486b502009-01-18 01:47:54 +00001471
1472 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001473 // We didn't get to the end of the string. This means the component names
1474 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001475 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1476 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001477 return QualType();
1478 }
Nate Begeman1486b502009-01-18 01:47:54 +00001479
1480 // Ensure no component accessor exceeds the width of the vector type it
1481 // operates on.
1482 if (!HalvingSwizzle) {
1483 compStr = CompName.getName();
1484
1485 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001486 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001487
1488 while (*compStr) {
1489 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1490 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1491 << baseType << SourceRange(CompLoc);
1492 return QualType();
1493 }
1494 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001495 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001496
Nate Begeman1486b502009-01-18 01:47:54 +00001497 // If this is a halving swizzle, verify that the base type has an even
1498 // number of elements.
1499 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001500 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001501 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001502 return QualType();
1503 }
1504
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001505 // The component accessor looks fine - now we need to compute the actual type.
1506 // The vector type is implied by the component accessor. For example,
1507 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001508 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001509 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001510 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1511 : CompName.getLength();
1512 if (HexSwizzle)
1513 CompSize--;
1514
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001515 if (CompSize == 1)
1516 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001517
Nate Begemanaf6ed502008-04-18 23:10:10 +00001518 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001519 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001520 // diagostics look bad. We want extended vector types to appear built-in.
1521 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1522 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1523 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001524 }
1525 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001526}
1527
Chris Lattner2cb744b2009-02-15 22:43:40 +00001528
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001529/// constructSetterName - Return the setter name for the given
1530/// identifier, i.e. "set" + Name where the initial character of Name
1531/// has been capitalized.
1532// FIXME: Merge with same routine in Parser. But where should this
1533// live?
1534static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1535 const IdentifierInfo *Name) {
1536 llvm::SmallString<100> SelectorName;
1537 SelectorName = "set";
1538 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1539 SelectorName[3] = toupper(SelectorName[3]);
1540 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1541}
1542
Sebastian Redl8b769972009-01-19 00:08:26 +00001543Action::OwningExprResult
1544Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1545 tok::TokenKind OpKind, SourceLocation MemberLoc,
1546 IdentifierInfo &Member) {
1547 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001548 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001549
1550 // Perform default conversions.
1551 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001552
Steve Naroff2cb66382007-07-26 03:11:44 +00001553 QualType BaseType = BaseExpr->getType();
1554 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001555
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001556 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1557 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001558 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001559 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001560 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001561 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001562 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1563 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001564 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001565 return ExprError(Diag(MemberLoc,
1566 diag::err_typecheck_member_reference_arrow)
1567 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001568 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001569
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001570 // Handle field access to simple records. This also handles access to fields
1571 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001572 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001573 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001574 if (DiagnoseIncompleteType(OpLoc, BaseType,
1575 diag::err_typecheck_incomplete_tag,
1576 BaseExpr->getSourceRange()))
1577 return ExprError();
1578
Steve Naroff2cb66382007-07-26 03:11:44 +00001579 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001580 // FIXME: Qualified name lookup for C++ is a bit more complicated
1581 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001582 LookupResult Result
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001583 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001584 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001585
Douglas Gregor09be81b2009-02-04 17:27:36 +00001586 NamedDecl *MemberDecl = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001587 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001588 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1589 << &Member << BaseExpr->getSourceRange());
1590 else if (Result.isAmbiguous()) {
1591 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1592 MemberLoc, BaseExpr->getSourceRange());
1593 return ExprError();
1594 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001595 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001596
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001597 // If the decl being referenced had an error, return an error for this
1598 // sub-expr without emitting another error, in order to avoid cascading
1599 // error cases.
1600 if (MemberDecl->isInvalidDecl())
1601 return ExprError();
Chris Lattnerb63f8132009-02-16 17:07:21 +00001602
1603 // Check if referencing a field with __attribute__((deprecated)).
1604 DiagnoseUseOfDeprecatedDecl(MemberDecl, MemberLoc);
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001605
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001606 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001607 // We may have found a field within an anonymous union or struct
1608 // (C++ [class.union]).
1609 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001610 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001611 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001612
Douglas Gregor82d44772008-12-20 23:49:58 +00001613 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1614 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001615 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001616 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1617 MemberType = Ref->getPointeeType();
1618 else {
1619 unsigned combinedQualifiers =
1620 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001621 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001622 combinedQualifiers &= ~QualType::Const;
1623 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1624 }
Eli Friedman76b49832008-02-06 22:48:16 +00001625
Steve Naroff774e4152009-01-21 00:14:39 +00001626 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1627 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001628 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001629 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001630 Var, MemberLoc,
1631 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001632 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001633 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1634 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001635 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001636 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001637 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001638 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001639 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001640 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Enum,
Sebastian Redl8b769972009-01-19 00:08:26 +00001641 MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001642 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001643 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1644 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001645
Douglas Gregor82d44772008-12-20 23:49:58 +00001646 // We found a declaration kind that we didn't expect. This is a
1647 // generic error message that tells the user that she can't refer
1648 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001649 return ExprError(Diag(MemberLoc,
1650 diag::err_typecheck_member_reference_unknown)
1651 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001652 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001653
Chris Lattnere9d71612008-07-21 04:59:05 +00001654 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1655 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001656 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001657 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001658 // If the decl being referenced had an error, return an error for this
1659 // sub-expr without emitting another error, in order to avoid cascading
1660 // error cases.
1661 if (IV->isInvalidDecl())
1662 return ExprError();
1663
Chris Lattner2a3bef92009-02-16 17:19:12 +00001664 // Check if referencing a field with __attribute__((deprecated)).
1665 DiagnoseUseOfDeprecatedDecl(IV, MemberLoc);
1666
Steve Naroff774e4152009-01-21 00:14:39 +00001667 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1668 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001669 OpKind == tok::arrow);
1670 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001671 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001672 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001673 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1674 << IFTy->getDecl()->getDeclName() << &Member
1675 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001676 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001677
Chris Lattnere9d71612008-07-21 04:59:05 +00001678 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1679 // pointer to a (potentially qualified) interface type.
1680 const PointerType *PTy;
1681 const ObjCInterfaceType *IFTy;
1682 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1683 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1684 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001685
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001686 // Search for a declared property first.
Chris Lattner51f6fb32009-02-16 18:35:08 +00001687 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
1688 // Check if referencing a property with __attribute__((deprecated)).
1689 DiagnoseUseOfDeprecatedDecl(PD, MemberLoc);
1690
Steve Naroff774e4152009-01-21 00:14:39 +00001691 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001692 MemberLoc, BaseExpr));
1693 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001694
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001695 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001696 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1697 E = IFTy->qual_end(); I != E; ++I)
Chris Lattner51f6fb32009-02-16 18:35:08 +00001698 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
1699 // Check if referencing a property with __attribute__((deprecated)).
1700 DiagnoseUseOfDeprecatedDecl(PD, MemberLoc);
1701
Steve Naroff774e4152009-01-21 00:14:39 +00001702 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001703 MemberLoc, BaseExpr));
1704 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001705
1706 // If that failed, look for an "implicit" property by seeing if the nullary
1707 // selector is implemented.
1708
1709 // FIXME: The logic for looking up nullary and unary selectors should be
1710 // shared with the code in ActOnInstanceMessage.
1711
1712 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1713 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001714
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001715 // If this reference is in an @implementation, check for 'private' methods.
1716 if (!Getter)
1717 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1718 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1719 if (ObjCImplementationDecl *ImpDecl =
1720 ObjCImplementations[ClassDecl->getIdentifier()])
1721 Getter = ImpDecl->getInstanceMethod(Sel);
1722
Steve Naroff04151f32008-10-22 19:16:27 +00001723 // Look through local category implementations associated with the class.
1724 if (!Getter) {
1725 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1726 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1727 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1728 }
1729 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001730 if (Getter) {
Chris Lattner51f6fb32009-02-16 18:35:08 +00001731 // Check if referencing a property with __attribute__((deprecated)).
1732 DiagnoseUseOfDeprecatedDecl(Getter, MemberLoc);
1733
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001734 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001735 // will look for the matching setter, in case it is needed.
1736 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1737 &Member);
1738 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1739 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1740 if (!Setter) {
1741 // If this reference is in an @implementation, also check for 'private'
1742 // methods.
1743 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1744 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1745 if (ObjCImplementationDecl *ImpDecl =
1746 ObjCImplementations[ClassDecl->getIdentifier()])
1747 Setter = ImpDecl->getInstanceMethod(SetterSel);
1748 }
1749 // Look through local category implementations associated with the class.
1750 if (!Setter) {
1751 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1752 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1753 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1754 }
1755 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001756
Chris Lattner51f6fb32009-02-16 18:35:08 +00001757 if (Setter)
1758 // Check if referencing a property with __attribute__((deprecated)).
1759 DiagnoseUseOfDeprecatedDecl(Setter, MemberLoc);
1760
1761
Sebastian Redl8b769972009-01-19 00:08:26 +00001762 // FIXME: we must check that the setter has property type.
Steve Naroff774e4152009-01-21 00:14:39 +00001763 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
1764 Setter, MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001765 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001766
1767 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1768 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001769 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001770 // Handle properties on qualified "id" protocols.
1771 const ObjCQualifiedIdType *QIdTy;
1772 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1773 // Check protocols on qualified interfaces.
1774 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001775 E = QIdTy->qual_end(); I != E; ++I) {
Chris Lattner51f6fb32009-02-16 18:35:08 +00001776 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
1777 // Check if referencing a property with __attribute__((deprecated)).
1778 DiagnoseUseOfDeprecatedDecl(PD, MemberLoc);
1779
Steve Naroff774e4152009-01-21 00:14:39 +00001780 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001781 MemberLoc, BaseExpr));
1782 }
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001783 // Also must look for a getter name which uses property syntax.
1784 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1785 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Chris Lattner51f6fb32009-02-16 18:35:08 +00001786 // Check if referencing a property with __attribute__((deprecated)).
1787 DiagnoseUseOfDeprecatedDecl(OMD, MemberLoc);
1788
Steve Naroff774e4152009-01-21 00:14:39 +00001789 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
1790 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001791 }
1792 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001793
1794 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1795 << &Member << BaseType);
1796 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001797 // Handle 'field access' to vectors, such as 'V.xx'.
1798 if (BaseType->isExtVectorType() && OpKind == tok::period) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001799 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1800 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001801 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00001802 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
1803 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001804 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001805
1806 return ExprError(Diag(MemberLoc,
1807 diag::err_typecheck_member_reference_struct_union)
1808 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001809}
1810
Douglas Gregor3257fb52008-12-22 05:46:06 +00001811/// ConvertArgumentsForCall - Converts the arguments specified in
1812/// Args/NumArgs to the parameter types of the function FDecl with
1813/// function prototype Proto. Call is the call expression itself, and
1814/// Fn is the function expression. For a C++ member function, this
1815/// routine does not attempt to convert the object argument. Returns
1816/// true if the call is ill-formed.
1817bool
1818Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1819 FunctionDecl *FDecl,
1820 const FunctionTypeProto *Proto,
1821 Expr **Args, unsigned NumArgs,
1822 SourceLocation RParenLoc) {
1823 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1824 // assignment, to the types of the corresponding parameter, ...
1825 unsigned NumArgsInProto = Proto->getNumArgs();
1826 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001827 bool Invalid = false;
1828
Douglas Gregor3257fb52008-12-22 05:46:06 +00001829 // If too few arguments are available (and we don't have default
1830 // arguments for the remaining parameters), don't make the call.
1831 if (NumArgs < NumArgsInProto) {
1832 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1833 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1834 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1835 // Use default arguments for missing arguments
1836 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001837 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001838 }
1839
1840 // If too many are passed and not variadic, error on the extras and drop
1841 // them.
1842 if (NumArgs > NumArgsInProto) {
1843 if (!Proto->isVariadic()) {
1844 Diag(Args[NumArgsInProto]->getLocStart(),
1845 diag::err_typecheck_call_too_many_args)
1846 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1847 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1848 Args[NumArgs-1]->getLocEnd());
1849 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001850 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001851 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001852 }
1853 NumArgsToCheck = NumArgsInProto;
1854 }
1855
1856 // Continue to check argument types (even if we have too few/many args).
1857 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1858 QualType ProtoArgType = Proto->getArgType(i);
1859
1860 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001861 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001862 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001863
1864 // Pass the argument.
1865 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1866 return true;
1867 } else
1868 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00001869 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001870 QualType ArgType = Arg->getType();
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001871
Douglas Gregor3257fb52008-12-22 05:46:06 +00001872 Call->setArg(i, Arg);
1873 }
1874
1875 // If this is a variadic call, handle args passed through "...".
1876 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001877 VariadicCallType CallType = VariadicFunction;
1878 if (Fn->getType()->isBlockPointerType())
1879 CallType = VariadicBlock; // Block
1880 else if (isa<MemberExpr>(Fn))
1881 CallType = VariadicMethod;
1882
Douglas Gregor3257fb52008-12-22 05:46:06 +00001883 // Promote the arguments (C99 6.5.2.2p7).
1884 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1885 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00001886 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001887 Call->setArg(i, Arg);
1888 }
1889 }
1890
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001891 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001892}
1893
Steve Naroff87d58b42007-09-16 03:34:24 +00001894/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001895/// This provides the location of the left/right parens and a list of comma
1896/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00001897Action::OwningExprResult
1898Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1899 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001900 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001901 unsigned NumArgs = args.size();
1902 Expr *Fn = static_cast<Expr *>(fn.release());
1903 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00001904 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001905 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001906 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001907
Douglas Gregor3257fb52008-12-22 05:46:06 +00001908 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001909 // Determine whether this is a dependent call inside a C++ template,
1910 // in which case we won't do any semantic analysis now.
1911 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
1912 bool Dependent = false;
1913 if (Fn->isTypeDependent())
1914 Dependent = true;
1915 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1916 Dependent = true;
1917
1918 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00001919 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001920 Context.DependentTy, RParenLoc));
1921
1922 // Determine whether this is a call to an object (C++ [over.call.object]).
1923 if (Fn->getType()->isRecordType())
1924 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1925 CommaLocs, RParenLoc));
1926
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001927 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00001928 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1929 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1930 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00001931 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1932 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001933 }
1934
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001935 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00001936 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001937 Expr *FnExpr = Fn;
1938 bool ADL = true;
1939 while (true) {
1940 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
1941 FnExpr = IcExpr->getSubExpr();
1942 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001943 // Parentheses around a function disable ADL
1944 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001945 ADL = false;
1946 FnExpr = PExpr->getSubExpr();
1947 } else if (isa<UnaryOperator>(FnExpr) &&
1948 cast<UnaryOperator>(FnExpr)->getOpcode()
1949 == UnaryOperator::AddrOf) {
1950 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00001951 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
1952 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
1953 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
1954 break;
1955 } else if (UnresolvedFunctionNameExpr *DepName
1956 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
1957 UnqualifiedName = DepName->getName();
1958 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001959 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00001960 // Any kind of name that does not refer to a declaration (or
1961 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
1962 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001963 break;
1964 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001965 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001966
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001967 OverloadedFunctionDecl *Ovl = 0;
1968 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001969 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001970 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1971 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001972
Douglas Gregorfcb19192009-02-11 23:02:49 +00001973 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00001974 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00001975 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001976 ADL = false;
1977
Douglas Gregorfcb19192009-02-11 23:02:49 +00001978 // We don't perform ADL in C.
1979 if (!getLangOptions().CPlusPlus)
1980 ADL = false;
1981
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001982 if (Ovl || ADL) {
1983 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
1984 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001985 NumArgs, CommaLocs, RParenLoc, ADL);
1986 if (!FDecl)
1987 return ExprError();
1988
1989 // Update Fn to refer to the actual function selected.
1990 Expr *NewFn = 0;
1991 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00001992 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00001993 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
1994 QDRExpr->getLocation(),
1995 false, false,
1996 QDRExpr->getSourceRange().getBegin());
1997 else
1998 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
1999 Fn->getSourceRange().getBegin());
2000 Fn->Destroy(Context);
2001 Fn = NewFn;
2002 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002003 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002004
2005 // Promote the function operand.
2006 UsualUnaryConversions(Fn);
2007
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002008 // Make the call expr early, before semantic checks. This guarantees cleanup
2009 // of arguments and function on error.
Sebastian Redl8b769972009-01-19 00:08:26 +00002010 // FIXME: Except that llvm::OwningPtr uses delete, when it really must be
2011 // Destroy(), or nothing gets cleaned up.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002012 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2013 Args, NumArgs,
2014 Context.BoolTy,
2015 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002016
Steve Naroffd6163f32008-09-05 22:11:13 +00002017 const FunctionType *FuncT;
2018 if (!Fn->getType()->isBlockPointerType()) {
2019 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2020 // have type pointer to function".
2021 const PointerType *PT = Fn->getType()->getAsPointerType();
2022 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002023 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2024 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002025 FuncT = PT->getPointeeType()->getAsFunctionType();
2026 } else { // This is a block call.
2027 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2028 getAsFunctionType();
2029 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002030 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002031 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2032 << Fn->getType() << Fn->getSourceRange());
2033
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002034 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002035 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002036
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002037 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002038 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
2039 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002040 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002041 } else {
2042 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002043
Steve Naroffdb65e052007-08-28 23:30:39 +00002044 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002045 for (unsigned i = 0; i != NumArgs; i++) {
2046 Expr *Arg = Args[i];
2047 DefaultArgumentPromotion(Arg);
2048 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002049 }
Chris Lattner4b009652007-07-25 00:24:17 +00002050 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002051
Douglas Gregor3257fb52008-12-22 05:46:06 +00002052 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2053 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002054 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2055 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002056
Chris Lattner2e64c072007-08-10 20:18:51 +00002057 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00002058 if (FDecl)
2059 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002060
Sebastian Redl8b769972009-01-19 00:08:26 +00002061 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002062}
2063
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002064Action::OwningExprResult
2065Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2066 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002067 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002068 QualType literalType = QualType::getFromOpaquePtr(Ty);
2069 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002070 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002071 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002072
Eli Friedman8c2173d2008-05-20 05:22:08 +00002073 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002074 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002075 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2076 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002077 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2078 diag::err_typecheck_decl_incomplete_type,
2079 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002080 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002081
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002082 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002083 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002084 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002085
Chris Lattnere5cb5862008-12-04 23:50:19 +00002086 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002087 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002088 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002089 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002090 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002091 InitExpr.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002092 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
2093 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002094}
2095
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002096Action::OwningExprResult
2097Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2098 InitListDesignations &Designators,
2099 SourceLocation RBraceLoc) {
2100 unsigned NumInit = initlist.size();
2101 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002102
Steve Naroff0acc9c92007-09-15 18:49:24 +00002103 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00002104 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002105
Steve Naroff774e4152009-01-21 00:14:39 +00002106 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002107 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002108 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002109 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002110}
2111
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002112/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002113bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002114 UsualUnaryConversions(castExpr);
2115
2116 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2117 // type needs to be scalar.
2118 if (castType->isVoidType()) {
2119 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002120 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2121 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002122 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002123 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2124 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2125 (castType->isStructureType() || castType->isUnionType())) {
2126 // GCC struct/union extension: allow cast to self.
2127 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2128 << castType << castExpr->getSourceRange();
2129 } else if (castType->isUnionType()) {
2130 // GCC cast to union extension
2131 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2132 RecordDecl::field_iterator Field, FieldEnd;
2133 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2134 Field != FieldEnd; ++Field) {
2135 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2136 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2137 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2138 << castExpr->getSourceRange();
2139 break;
2140 }
2141 }
2142 if (Field == FieldEnd)
2143 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2144 << castExpr->getType() << castExpr->getSourceRange();
2145 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002146 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002147 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002148 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002149 }
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002150 } else if (!castExpr->getType()->isScalarType() &&
2151 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002152 return Diag(castExpr->getLocStart(),
2153 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002154 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002155 } else if (castExpr->getType()->isVectorType()) {
2156 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2157 return true;
2158 } else if (castType->isVectorType()) {
2159 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2160 return true;
2161 }
2162 return false;
2163}
2164
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002165bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002166 assert(VectorTy->isVectorType() && "Not a vector type!");
2167
2168 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002169 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002170 return Diag(R.getBegin(),
2171 Ty->isVectorType() ?
2172 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002173 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002174 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002175 } else
2176 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002177 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002178 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002179
2180 return false;
2181}
2182
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002183Action::OwningExprResult
2184Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2185 SourceLocation RParenLoc, ExprArg Op) {
2186 assert((Ty != 0) && (Op.get() != 0) &&
2187 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002188
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002189 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002190 QualType castType = QualType::getFromOpaquePtr(Ty);
2191
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002192 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002193 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002194 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002195 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002196}
2197
Chris Lattner98a425c2007-11-26 01:40:58 +00002198/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2199/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00002200inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
2201 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
2202 UsualUnaryConversions(cond);
2203 UsualUnaryConversions(lex);
2204 UsualUnaryConversions(rex);
2205 QualType condT = cond->getType();
2206 QualType lexT = lex->getType();
2207 QualType rexT = rex->getType();
2208
2209 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002210 if (!cond->isTypeDependent()) {
2211 if (!condT->isScalarType()) { // C99 6.5.15p2
2212 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
2213 return QualType();
2214 }
Chris Lattner4b009652007-07-25 00:24:17 +00002215 }
Chris Lattner992ae932008-01-06 22:42:25 +00002216
2217 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002218 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
2219 return Context.DependentTy;
2220
Chris Lattner992ae932008-01-06 22:42:25 +00002221 // If both operands have arithmetic type, do the usual arithmetic conversions
2222 // to find a common type: C99 6.5.15p3,5.
2223 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002224 UsualArithmeticConversions(lex, rex);
2225 return lex->getType();
2226 }
Chris Lattner992ae932008-01-06 22:42:25 +00002227
2228 // If both operands are the same structure or union type, the result is that
2229 // type.
Chris Lattner71225142007-07-31 21:27:01 +00002230 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00002231 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002232 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00002233 // "If both the operands have structure or union type, the result has
2234 // that type." This implies that CV qualifiers are dropped.
2235 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002236 }
Chris Lattner992ae932008-01-06 22:42:25 +00002237
2238 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002239 // The following || allows only one side to be void (a GCC-ism).
2240 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00002241 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002242 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2243 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00002244 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00002245 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2246 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00002247 ImpCastExprToType(lex, Context.VoidTy);
2248 ImpCastExprToType(rex, Context.VoidTy);
2249 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002250 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002251 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2252 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002253 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2254 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002255 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002256 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002257 return lexT;
2258 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002259 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2260 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00002261 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002262 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00002263 return rexT;
2264 }
Chris Lattner0ac51632008-01-06 22:50:31 +00002265 // Handle the case where both operands are pointers before we handle null
2266 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00002267 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2268 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2269 // get the "pointed to" types
2270 QualType lhptee = LHSPT->getPointeeType();
2271 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002272
Chris Lattner71225142007-07-31 21:27:01 +00002273 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2274 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002275 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002276 // Figure out necessary qualifiers (C99 6.5.15p6)
2277 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002278 QualType destType = Context.getPointerType(destPointee);
2279 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2280 ImpCastExprToType(rex, destType); // promote to void*
2281 return destType;
2282 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002283 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002284 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002285 QualType destType = Context.getPointerType(destPointee);
2286 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2287 ImpCastExprToType(rex, destType); // promote to void*
2288 return destType;
2289 }
Chris Lattner4b009652007-07-25 00:24:17 +00002290
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002291 QualType compositeType = lexT;
2292
2293 // If either type is an Objective-C object type then check
2294 // compatibility according to Objective-C.
2295 if (Context.isObjCObjectPointerType(lexT) ||
2296 Context.isObjCObjectPointerType(rexT)) {
2297 // If both operands are interfaces and either operand can be
2298 // assigned to the other, use that type as the composite
2299 // type. This allows
2300 // xxx ? (A*) a : (B*) b
2301 // where B is a subclass of A.
2302 //
2303 // Additionally, as for assignment, if either type is 'id'
2304 // allow silent coercion. Finally, if the types are
2305 // incompatible then make sure to use 'id' as the composite
2306 // type so the result is acceptable for sending messages to.
2307
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002308 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
2309 // It could return the composite type.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002310 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2311 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2312 if (LHSIface && RHSIface &&
2313 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2314 compositeType = lexT;
2315 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002316 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002317 compositeType = rexT;
Steve Naroff17c03822009-02-12 17:52:19 +00002318 } else if (Context.isObjCIdStructType(lhptee) ||
2319 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002320 compositeType = Context.getObjCIdType();
2321 } else {
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002322 Diag(questionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
2323 << lexT << rexT
2324 << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002325 QualType incompatTy = Context.getObjCIdType();
2326 ImpCastExprToType(lex, incompatTy);
2327 ImpCastExprToType(rex, incompatTy);
2328 return incompatTy;
2329 }
2330 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2331 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002332 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002333 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002334 // In this situation, we assume void* type. No especially good
2335 // reason, but this is what gcc does, and we do have to pick
2336 // to get a consistent AST.
2337 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002338 ImpCastExprToType(lex, incompatTy);
2339 ImpCastExprToType(rex, incompatTy);
2340 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002341 }
2342 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002343 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2344 // differently qualified versions of compatible types, the result type is
2345 // a pointer to an appropriately qualified version of the *composite*
2346 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002347 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002348 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00002349 ImpCastExprToType(lex, compositeType);
2350 ImpCastExprToType(rex, compositeType);
2351 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002352 }
Chris Lattner4b009652007-07-25 00:24:17 +00002353 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002354 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2355 // evaluates to "struct objc_object *" (and is handled above when comparing
2356 // id with statically typed objects).
2357 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2358 // GCC allows qualified id and any Objective-C type to devolve to
2359 // id. Currently localizing to here until clear this should be
2360 // part of ObjCQualifiedIdTypesAreCompatible.
2361 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2362 (lexT->isObjCQualifiedIdType() &&
2363 Context.isObjCObjectPointerType(rexT)) ||
2364 (rexT->isObjCQualifiedIdType() &&
2365 Context.isObjCObjectPointerType(lexT))) {
2366 // FIXME: This is not the correct composite type. This only
2367 // happens to work because id can more or less be used anywhere,
2368 // however this may change the type of method sends.
2369 // FIXME: gcc adds some type-checking of the arguments and emits
2370 // (confusing) incompatible comparison warnings in some
2371 // cases. Investigate.
2372 QualType compositeType = Context.getObjCIdType();
2373 ImpCastExprToType(lex, compositeType);
2374 ImpCastExprToType(rex, compositeType);
2375 return compositeType;
2376 }
2377 }
2378
Steve Naroff3eac7692008-09-10 19:17:48 +00002379 // Selection between block pointer types is ok as long as they are the same.
2380 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2381 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2382 return lexT;
2383
Chris Lattner992ae932008-01-06 22:42:25 +00002384 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00002385 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002386 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002387 return QualType();
2388}
2389
Steve Naroff87d58b42007-09-16 03:34:24 +00002390/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002391/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002392Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2393 SourceLocation ColonLoc,
2394 ExprArg Cond, ExprArg LHS,
2395 ExprArg RHS) {
2396 Expr *CondExpr = (Expr *) Cond.get();
2397 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002398
2399 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2400 // was the condition.
2401 bool isLHSNull = LHSExpr == 0;
2402 if (isLHSNull)
2403 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002404
2405 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002406 RHSExpr, QuestionLoc);
2407 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002408 return ExprError();
2409
2410 Cond.release();
2411 LHS.release();
2412 RHS.release();
Steve Naroff774e4152009-01-21 00:14:39 +00002413 return Owned(new (Context) ConditionalOperator(CondExpr,
2414 isLHSNull ? 0 : LHSExpr,
2415 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002416}
2417
Chris Lattner4b009652007-07-25 00:24:17 +00002418
2419// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2420// being closely modeled after the C99 spec:-). The odd characteristic of this
2421// routine is it effectively iqnores the qualifiers on the top level pointee.
2422// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2423// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00002424Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002425Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2426 QualType lhptee, rhptee;
2427
2428 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002429 lhptee = lhsType->getAsPointerType()->getPointeeType();
2430 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002431
2432 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002433 lhptee = Context.getCanonicalType(lhptee);
2434 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002435
Chris Lattner005ed752008-01-04 18:04:52 +00002436 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002437
2438 // C99 6.5.16.1p1: This following citation is common to constraints
2439 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2440 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00002441 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002442 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002443 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002444
2445 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2446 // incomplete type and the other is a pointer to a qualified or unqualified
2447 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002448 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002449 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002450 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002451
2452 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002453 assert(rhptee->isFunctionType());
2454 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002455 }
2456
2457 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002458 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002459 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002460
2461 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002462 assert(lhptee->isFunctionType());
2463 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002464 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002465
2466 // Check for ObjC interfaces
2467 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2468 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2469 if (LHSIface && RHSIface &&
2470 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2471 return ConvTy;
2472
2473 // ID acts sort of like void* for ObjC interfaces
Steve Naroff17c03822009-02-12 17:52:19 +00002474 if (LHSIface && Context.isObjCIdStructType(rhptee))
Eli Friedman0d9549b2008-08-22 00:56:42 +00002475 return ConvTy;
Steve Naroff17c03822009-02-12 17:52:19 +00002476 if (RHSIface && Context.isObjCIdStructType(lhptee))
Eli Friedman0d9549b2008-08-22 00:56:42 +00002477 return ConvTy;
2478
Chris Lattner4b009652007-07-25 00:24:17 +00002479 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2480 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002481 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2482 rhptee.getUnqualifiedType()))
2483 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002484 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002485}
2486
Steve Naroff3454b6c2008-09-04 15:10:53 +00002487/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2488/// block pointer types are compatible or whether a block and normal pointer
2489/// are compatible. It is more restrict than comparing two function pointer
2490// types.
2491Sema::AssignConvertType
2492Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2493 QualType rhsType) {
2494 QualType lhptee, rhptee;
2495
2496 // get the "pointed to" type (ignoring qualifiers at the top level)
2497 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2498 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2499
2500 // make sure we operate on the canonical type
2501 lhptee = Context.getCanonicalType(lhptee);
2502 rhptee = Context.getCanonicalType(rhptee);
2503
2504 AssignConvertType ConvTy = Compatible;
2505
2506 // For blocks we enforce that qualifiers are identical.
2507 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2508 ConvTy = CompatiblePointerDiscardsQualifiers;
2509
2510 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2511 return IncompatibleBlockPointer;
2512 return ConvTy;
2513}
2514
Chris Lattner4b009652007-07-25 00:24:17 +00002515/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2516/// has code to accommodate several GCC extensions when type checking
2517/// pointers. Here are some objectionable examples that GCC considers warnings:
2518///
2519/// int a, *pint;
2520/// short *pshort;
2521/// struct foo *pfoo;
2522///
2523/// pint = pshort; // warning: assignment from incompatible pointer type
2524/// a = pint; // warning: assignment makes integer from pointer without a cast
2525/// pint = a; // warning: assignment makes pointer from integer without a cast
2526/// pint = pfoo; // warning: assignment from incompatible pointer type
2527///
2528/// As a result, the code for dealing with pointers is more complex than the
2529/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002530///
Chris Lattner005ed752008-01-04 18:04:52 +00002531Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002532Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002533 // Get canonical types. We're not formatting these types, just comparing
2534 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002535 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2536 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002537
2538 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002539 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002540
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002541 // If the left-hand side is a reference type, then we are in a
2542 // (rare!) case where we've allowed the use of references in C,
2543 // e.g., as a parameter type in a built-in function. In this case,
2544 // just make sure that the type referenced is compatible with the
2545 // right-hand side type. The caller is responsible for adjusting
2546 // lhsType so that the resulting expression does not have reference
2547 // type.
2548 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2549 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002550 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002551 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002552 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002553
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002554 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2555 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002556 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002557 // Relax integer conversions like we do for pointers below.
2558 if (rhsType->isIntegerType())
2559 return IntToPointer;
2560 if (lhsType->isIntegerType())
2561 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002562 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002563 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002564
Nate Begemanc5f0f652008-07-14 18:02:46 +00002565 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002566 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002567 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2568 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002569 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002570
Nate Begemanc5f0f652008-07-14 18:02:46 +00002571 // If we are allowing lax vector conversions, and LHS and RHS are both
2572 // vectors, the total size only needs to be the same. This is a bitcast;
2573 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002574 if (getLangOptions().LaxVectorConversions &&
2575 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002576 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002577 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002578 }
2579 return Incompatible;
2580 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002581
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002582 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002583 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002584
Chris Lattner390564e2008-04-07 06:49:41 +00002585 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002586 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002587 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002588
Chris Lattner390564e2008-04-07 06:49:41 +00002589 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002590 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002591
Steve Naroffa982c712008-09-29 18:10:17 +00002592 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002593 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002594 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002595
2596 // Treat block pointers as objects.
2597 if (getLangOptions().ObjC1 &&
2598 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2599 return Compatible;
2600 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002601 return Incompatible;
2602 }
2603
2604 if (isa<BlockPointerType>(lhsType)) {
2605 if (rhsType->isIntegerType())
2606 return IntToPointer;
2607
Steve Naroffa982c712008-09-29 18:10:17 +00002608 // Treat block pointers as objects.
2609 if (getLangOptions().ObjC1 &&
2610 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2611 return Compatible;
2612
Steve Naroff3454b6c2008-09-04 15:10:53 +00002613 if (rhsType->isBlockPointerType())
2614 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2615
2616 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2617 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002618 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002619 }
Chris Lattner1853da22008-01-04 23:18:45 +00002620 return Incompatible;
2621 }
2622
Chris Lattner390564e2008-04-07 06:49:41 +00002623 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002624 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002625 if (lhsType == Context.BoolTy)
2626 return Compatible;
2627
2628 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002629 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002630
Chris Lattner390564e2008-04-07 06:49:41 +00002631 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002632 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002633
2634 if (isa<BlockPointerType>(lhsType) &&
2635 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002636 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002637 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002638 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002639
Chris Lattner1853da22008-01-04 23:18:45 +00002640 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002641 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002642 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002643 }
2644 return Incompatible;
2645}
2646
Chris Lattner005ed752008-01-04 18:04:52 +00002647Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002648Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002649 if (getLangOptions().CPlusPlus) {
2650 if (!lhsType->isRecordType()) {
2651 // C++ 5.17p3: If the left operand is not of class type, the
2652 // expression is implicitly converted (C++ 4) to the
2653 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002654 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2655 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002656 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002657 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002658 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002659 }
2660
2661 // FIXME: Currently, we fall through and treat C++ classes like C
2662 // structures.
2663 }
2664
Steve Naroffcdee22d2007-11-27 17:58:44 +00002665 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2666 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002667 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2668 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002669 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002670 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002671 return Compatible;
2672 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002673
2674 // We don't allow conversion of non-null-pointer constants to integers.
2675 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2676 return IntToBlockPointer;
2677
Chris Lattner5f505bf2007-10-16 02:55:40 +00002678 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002679 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002680 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002681 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002682 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002683 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002684 if (!lhsType->isReferenceType())
2685 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002686
Chris Lattner005ed752008-01-04 18:04:52 +00002687 Sema::AssignConvertType result =
2688 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002689
2690 // C99 6.5.16.1p2: The value of the right operand is converted to the
2691 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002692 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2693 // so that we can use references in built-in functions even in C.
2694 // The getNonReferenceType() call makes sure that the resulting expression
2695 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002696 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002697 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002698 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002699}
2700
Chris Lattner005ed752008-01-04 18:04:52 +00002701Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002702Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2703 return CheckAssignmentConstraints(lhsType, rhsType);
2704}
2705
Chris Lattner1eafdea2008-11-18 01:30:42 +00002706QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002707 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002708 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002709 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002710 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002711}
2712
Chris Lattner1eafdea2008-11-18 01:30:42 +00002713inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002714 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002715 // For conversion purposes, we ignore any qualifiers.
2716 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002717 QualType lhsType =
2718 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2719 QualType rhsType =
2720 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002721
Nate Begemanc5f0f652008-07-14 18:02:46 +00002722 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002723 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002724 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002725
Nate Begemanc5f0f652008-07-14 18:02:46 +00002726 // Handle the case of a vector & extvector type of the same size and element
2727 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00002728 if (getLangOptions().LaxVectorConversions) {
2729 // FIXME: Should we warn here?
2730 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002731 if (const VectorType *RV = rhsType->getAsVectorType())
2732 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00002733 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002734 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00002735 }
2736 }
2737 }
2738
Nate Begemanc5f0f652008-07-14 18:02:46 +00002739 // If the lhs is an extended vector and the rhs is a scalar of the same type
2740 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002741 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002742 QualType eltType = V->getElementType();
2743
2744 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2745 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2746 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002747 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002748 return lhsType;
2749 }
2750 }
2751
Nate Begemanc5f0f652008-07-14 18:02:46 +00002752 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002753 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002754 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002755 QualType eltType = V->getElementType();
2756
2757 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2758 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2759 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002760 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002761 return rhsType;
2762 }
2763 }
2764
Chris Lattner4b009652007-07-25 00:24:17 +00002765 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002766 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002767 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002768 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002769 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00002770}
2771
Chris Lattner4b009652007-07-25 00:24:17 +00002772inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002773 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002774{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002775 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002776 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002777
Steve Naroff8f708362007-08-24 19:07:16 +00002778 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002779
Chris Lattner4b009652007-07-25 00:24:17 +00002780 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002781 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002782 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002783}
2784
2785inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002786 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002787{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002788 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2789 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2790 return CheckVectorOperands(Loc, lex, rex);
2791 return InvalidOperands(Loc, lex, rex);
2792 }
Chris Lattner4b009652007-07-25 00:24:17 +00002793
Steve Naroff8f708362007-08-24 19:07:16 +00002794 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002795
Chris Lattner4b009652007-07-25 00:24:17 +00002796 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002797 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002798 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002799}
2800
2801inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002802 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002803{
2804 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002805 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002806
Steve Naroff8f708362007-08-24 19:07:16 +00002807 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002808
Chris Lattner4b009652007-07-25 00:24:17 +00002809 // handle the common case first (both operands are arithmetic).
2810 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002811 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002812
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002813 // Put any potential pointer into PExp
2814 Expr* PExp = lex, *IExp = rex;
2815 if (IExp->getType()->isPointerType())
2816 std::swap(PExp, IExp);
2817
2818 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2819 if (IExp->getType()->isIntegerType()) {
2820 // Check for arithmetic on pointers to incomplete types
2821 if (!PTy->getPointeeType()->isObjectType()) {
2822 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002823 if (getLangOptions().CPlusPlus) {
2824 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2825 << lex->getSourceRange() << rex->getSourceRange();
2826 return QualType();
2827 }
2828
2829 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00002830 Diag(Loc, diag::ext_gnu_void_ptr)
2831 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002832 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002833 if (getLangOptions().CPlusPlus) {
2834 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2835 << lex->getType() << lex->getSourceRange();
2836 return QualType();
2837 }
2838
2839 // GNU extension: arithmetic on pointer to function
2840 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002841 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002842 } else {
2843 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2844 diag::err_typecheck_arithmetic_incomplete_type,
2845 lex->getSourceRange(), SourceRange(),
2846 lex->getType());
2847 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002848 }
2849 }
2850 return PExp->getType();
2851 }
2852 }
2853
Chris Lattner1eafdea2008-11-18 01:30:42 +00002854 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002855}
2856
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002857// C99 6.5.6
2858QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002859 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002860 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002861 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002862
Steve Naroff8f708362007-08-24 19:07:16 +00002863 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002864
Chris Lattnerf6da2912007-12-09 21:53:25 +00002865 // Enforce type constraints: C99 6.5.6p3.
2866
2867 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002868 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002869 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002870
2871 // Either ptr - int or ptr - ptr.
2872 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002873 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002874
Chris Lattnerf6da2912007-12-09 21:53:25 +00002875 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002876 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002877 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002878 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002879 Diag(Loc, diag::ext_gnu_void_ptr)
2880 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00002881 } else if (lpointee->isFunctionType()) {
2882 if (getLangOptions().CPlusPlus) {
2883 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2884 << lex->getType() << lex->getSourceRange();
2885 return QualType();
2886 }
2887
2888 // GNU extension: arithmetic on pointer to function
2889 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2890 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002891 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002892 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002893 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002894 return QualType();
2895 }
2896 }
2897
2898 // The result type of a pointer-int computation is the pointer type.
2899 if (rex->getType()->isIntegerType())
2900 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002901
Chris Lattnerf6da2912007-12-09 21:53:25 +00002902 // Handle pointer-pointer subtractions.
2903 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002904 QualType rpointee = RHSPTy->getPointeeType();
2905
Chris Lattnerf6da2912007-12-09 21:53:25 +00002906 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002907 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002908 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002909 if (rpointee->isVoidType()) {
2910 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002911 Diag(Loc, diag::ext_gnu_void_ptr)
2912 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00002913 } else if (rpointee->isFunctionType()) {
2914 if (getLangOptions().CPlusPlus) {
2915 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2916 << rex->getType() << rex->getSourceRange();
2917 return QualType();
2918 }
2919
2920 // GNU extension: arithmetic on pointer to function
2921 if (!lpointee->isFunctionType())
2922 Diag(Loc, diag::ext_gnu_ptr_func_arith)
2923 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002924 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002925 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002926 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002927 return QualType();
2928 }
2929 }
2930
2931 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002932 if (!Context.typesAreCompatible(
2933 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2934 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002935 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002936 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002937 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002938 return QualType();
2939 }
2940
2941 return Context.getPointerDiffType();
2942 }
2943 }
2944
Chris Lattner1eafdea2008-11-18 01:30:42 +00002945 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002946}
2947
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002948// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002949QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002950 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002951 // C99 6.5.7p2: Each of the operands shall have integer type.
2952 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002953 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002954
Chris Lattner2c8bff72007-12-12 05:47:28 +00002955 // Shifts don't perform usual arithmetic conversions, they just do integer
2956 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002957 if (!isCompAssign)
2958 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002959 UsualUnaryConversions(rex);
2960
2961 // "The type of the result is that of the promoted left operand."
2962 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002963}
2964
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002965// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002966QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002967 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002968 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002969 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002970
Chris Lattner254f3bc2007-08-26 01:18:55 +00002971 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002972 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2973 UsualArithmeticConversions(lex, rex);
2974 else {
2975 UsualUnaryConversions(lex);
2976 UsualUnaryConversions(rex);
2977 }
Chris Lattner4b009652007-07-25 00:24:17 +00002978 QualType lType = lex->getType();
2979 QualType rType = rex->getType();
2980
Ted Kremenek486509e2007-10-29 17:13:39 +00002981 // For non-floating point types, check for self-comparisons of the form
2982 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2983 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002984 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002985 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2986 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002987 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002988 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002989 }
2990
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002991 // The result of comparisons is 'bool' in C++, 'int' in C.
2992 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2993
Chris Lattner254f3bc2007-08-26 01:18:55 +00002994 if (isRelational) {
2995 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002996 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002997 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002998 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002999 if (lType->isFloatingType()) {
3000 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003001 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00003002 }
3003
Chris Lattner254f3bc2007-08-26 01:18:55 +00003004 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003005 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003006 }
Chris Lattner4b009652007-07-25 00:24:17 +00003007
Chris Lattner22be8422007-08-26 01:10:14 +00003008 bool LHSIsNull = lex->isNullPointerConstant(Context);
3009 bool RHSIsNull = rex->isNullPointerConstant(Context);
3010
Chris Lattner254f3bc2007-08-26 01:18:55 +00003011 // All of the following pointer related warnings are GCC extensions, except
3012 // when handling null pointer constants. One day, we can consider making them
3013 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00003014 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003015 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003016 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00003017 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003018 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00003019
Steve Naroff3b435622007-11-13 14:57:38 +00003020 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003021 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3022 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00003023 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00003024 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003025 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003026 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003027 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003028 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003029 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003030 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003031 // Handle block pointer types.
3032 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3033 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3034 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
3035
3036 if (!LHSIsNull && !RHSIsNull &&
3037 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003038 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003039 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003040 }
3041 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003042 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003043 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003044 // Allow block pointers to be compared with null pointer constants.
3045 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3046 (lType->isPointerType() && rType->isBlockPointerType())) {
3047 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003048 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003049 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003050 }
3051 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003052 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003053 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003054
Steve Naroff936c4362008-06-03 14:04:54 +00003055 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003056 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003057 const PointerType *LPT = lType->getAsPointerType();
3058 const PointerType *RPT = rType->getAsPointerType();
3059 bool LPtrToVoid = LPT ?
3060 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
3061 bool RPtrToVoid = RPT ?
3062 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
3063
3064 if (!LPtrToVoid && !RPtrToVoid &&
3065 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003066 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003067 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003068 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003069 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003070 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003071 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003072 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003073 }
Steve Naroff936c4362008-06-03 14:04:54 +00003074 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3075 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003076 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003077 } else {
3078 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003079 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003080 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003081 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003082 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003083 }
Steve Naroff936c4362008-06-03 14:04:54 +00003084 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003085 }
Steve Naroff936c4362008-06-03 14:04:54 +00003086 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
3087 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003088 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003089 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003090 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003091 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003092 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003093 }
Steve Naroff936c4362008-06-03 14:04:54 +00003094 if (lType->isIntegerType() &&
3095 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003096 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003097 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003098 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003099 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003100 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003101 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003102 // Handle block pointers.
3103 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3104 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003105 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003106 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003107 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003108 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003109 }
3110 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3111 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003112 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003113 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003114 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003115 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003116 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003117 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003118}
3119
Nate Begemanc5f0f652008-07-14 18:02:46 +00003120/// CheckVectorCompareOperands - vector comparisons are a clang extension that
3121/// operates on extended vector types. Instead of producing an IntTy result,
3122/// like a scalar comparison, a vector comparison produces a vector of integer
3123/// types.
3124QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003125 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003126 bool isRelational) {
3127 // Check to make sure we're operating on vectors of the same type and width,
3128 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003129 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003130 if (vType.isNull())
3131 return vType;
3132
3133 QualType lType = lex->getType();
3134 QualType rType = rex->getType();
3135
3136 // For non-floating point types, check for self-comparisons of the form
3137 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3138 // often indicate logic errors in the program.
3139 if (!lType->isFloatingType()) {
3140 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3141 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3142 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003143 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003144 }
3145
3146 // Check for comparisons of floating point operands using != and ==.
3147 if (!isRelational && lType->isFloatingType()) {
3148 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003149 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003150 }
3151
3152 // Return the type for the comparison, which is the same as vector type for
3153 // integer vectors, or an integer type of identical size and number of
3154 // elements for floating point vectors.
3155 if (lType->isIntegerType())
3156 return lType;
3157
3158 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003159 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003160 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003161 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003162 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3163 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3164
3165 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3166 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003167 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3168}
3169
Chris Lattner4b009652007-07-25 00:24:17 +00003170inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00003171 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003172{
3173 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003174 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003175
Steve Naroff8f708362007-08-24 19:07:16 +00003176 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00003177
3178 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003179 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003180 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003181}
3182
3183inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00003184 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003185{
3186 UsualUnaryConversions(lex);
3187 UsualUnaryConversions(rex);
3188
Eli Friedmanbea3f842008-05-13 20:16:47 +00003189 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003190 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003191 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003192}
3193
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003194/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3195/// is a read-only property; return true if so. A readonly property expression
3196/// depends on various declarations and thus must be treated specially.
3197///
3198static bool IsReadonlyProperty(Expr *E, Sema &S)
3199{
3200 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3201 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3202 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3203 QualType BaseType = PropExpr->getBase()->getType();
3204 if (const PointerType *PTy = BaseType->getAsPointerType())
3205 if (const ObjCInterfaceType *IFTy =
3206 PTy->getPointeeType()->getAsObjCInterfaceType())
3207 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3208 if (S.isPropertyReadonly(PDecl, IFace))
3209 return true;
3210 }
3211 }
3212 return false;
3213}
3214
Chris Lattner4c2642c2008-11-18 01:22:49 +00003215/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3216/// emit an error and return true. If so, return false.
3217static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003218 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3219 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3220 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003221 if (IsLV == Expr::MLV_Valid)
3222 return false;
3223
3224 unsigned Diag = 0;
3225 bool NeedType = false;
3226 switch (IsLV) { // C99 6.5.16p2
3227 default: assert(0 && "Unknown result from isModifiableLvalue!");
3228 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00003229 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003230 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3231 NeedType = true;
3232 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003233 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003234 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3235 NeedType = true;
3236 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003237 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003238 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3239 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003240 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003241 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3242 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003243 case Expr::MLV_IncompleteType:
3244 case Expr::MLV_IncompleteVoidType:
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003245 return S.DiagnoseIncompleteType(Loc, E->getType(),
3246 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3247 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003248 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003249 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3250 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003251 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003252 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3253 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003254 case Expr::MLV_ReadonlyProperty:
3255 Diag = diag::error_readonly_property_assignment;
3256 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003257 case Expr::MLV_NoSetterProperty:
3258 Diag = diag::error_nosetter_property_assignment;
3259 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003260 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003261
Chris Lattner4c2642c2008-11-18 01:22:49 +00003262 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003263 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003264 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003265 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003266 return true;
3267}
3268
3269
3270
3271// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003272QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3273 SourceLocation Loc,
3274 QualType CompoundType) {
3275 // Verify that LHS is a modifiable lvalue, and emit error if not.
3276 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003277 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003278
3279 QualType LHSType = LHS->getType();
3280 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003281
Chris Lattner005ed752008-01-04 18:04:52 +00003282 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003283 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003284 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003285 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003286 // Special case of NSObject attributes on c-style pointer types.
3287 if (ConvTy == IncompatiblePointer &&
3288 ((Context.isObjCNSObjectType(LHSType) &&
3289 Context.isObjCObjectPointerType(RHSType)) ||
3290 (Context.isObjCNSObjectType(RHSType) &&
3291 Context.isObjCObjectPointerType(LHSType))))
3292 ConvTy = Compatible;
3293
Chris Lattner34c85082008-08-21 18:04:13 +00003294 // If the RHS is a unary plus or minus, check to see if they = and + are
3295 // right next to each other. If so, the user may have typo'd "x =+ 4"
3296 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003297 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003298 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3299 RHSCheck = ICE->getSubExpr();
3300 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3301 if ((UO->getOpcode() == UnaryOperator::Plus ||
3302 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003303 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003304 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003305 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003306 Diag(Loc, diag::warn_not_compound_assign)
3307 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3308 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003309 }
3310 } else {
3311 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003312 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003313 }
Chris Lattner005ed752008-01-04 18:04:52 +00003314
Chris Lattner1eafdea2008-11-18 01:30:42 +00003315 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3316 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003317 return QualType();
3318
Chris Lattner4b009652007-07-25 00:24:17 +00003319 // C99 6.5.16p3: The type of an assignment expression is the type of the
3320 // left operand unless the left operand has qualified type, in which case
3321 // it is the unqualified version of the type of the left operand.
3322 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3323 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003324 // C++ 5.17p1: the type of the assignment expression is that of its left
3325 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003326 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003327}
3328
Chris Lattner1eafdea2008-11-18 01:30:42 +00003329// C99 6.5.17
3330QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3331 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00003332
3333 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003334 DefaultFunctionArrayConversion(RHS);
3335 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003336}
3337
3338/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3339/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003340QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3341 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003342 QualType ResType = Op->getType();
3343 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003344
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003345 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3346 // Decrement of bool is not allowed.
3347 if (!isInc) {
3348 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3349 return QualType();
3350 }
3351 // Increment of bool sets it to true, but is deprecated.
3352 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3353 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003354 // OK!
3355 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3356 // C99 6.5.2.4p2, 6.5.6p2
3357 if (PT->getPointeeType()->isObjectType()) {
3358 // Pointer to object is ok!
3359 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003360 if (getLangOptions().CPlusPlus) {
3361 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3362 << Op->getSourceRange();
3363 return QualType();
3364 }
3365
3366 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003367 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003368 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003369 if (getLangOptions().CPlusPlus) {
3370 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3371 << Op->getType() << Op->getSourceRange();
3372 return QualType();
3373 }
3374
3375 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003376 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003377 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003378 } else {
3379 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3380 diag::err_typecheck_arithmetic_incomplete_type,
3381 Op->getSourceRange(), SourceRange(),
3382 ResType);
3383 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003384 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003385 } else if (ResType->isComplexType()) {
3386 // C99 does not support ++/-- on complex types, we allow as an extension.
3387 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003388 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003389 } else {
3390 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003391 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003392 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003393 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00003394 // At this point, we know we have a real, complex or pointer type.
3395 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003396 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003397 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003398 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003399}
3400
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003401/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003402/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003403/// where the declaration is needed for type checking. We only need to
3404/// handle cases when the expression references a function designator
3405/// or is an lvalue. Here are some examples:
3406/// - &(x) => x
3407/// - &*****f => f for f a function designator.
3408/// - &s.xx => s
3409/// - &s.zz[1].yy -> s, if zz is an array
3410/// - *(x + 1) -> x, if x is an array
3411/// - &"123"[2] -> 0
3412/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003413static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003414 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003415 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003416 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003417 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003418 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003419 // Fields cannot be declared with a 'register' storage class.
3420 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003421 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003422 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003423 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003424 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003425 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003426
Douglas Gregord2baafd2008-10-21 16:13:35 +00003427 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003428 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003429 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003430 return 0;
3431 else
3432 return VD;
3433 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003434 case Stmt::UnaryOperatorClass: {
3435 UnaryOperator *UO = cast<UnaryOperator>(E);
3436
3437 switch(UO->getOpcode()) {
3438 case UnaryOperator::Deref: {
3439 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003440 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3441 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3442 if (!VD || VD->getType()->isPointerType())
3443 return 0;
3444 return VD;
3445 }
3446 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003447 }
3448 case UnaryOperator::Real:
3449 case UnaryOperator::Imag:
3450 case UnaryOperator::Extension:
3451 return getPrimaryDecl(UO->getSubExpr());
3452 default:
3453 return 0;
3454 }
3455 }
3456 case Stmt::BinaryOperatorClass: {
3457 BinaryOperator *BO = cast<BinaryOperator>(E);
3458
3459 // Handle cases involving pointer arithmetic. The result of an
3460 // Assign or AddAssign is not an lvalue so they can be ignored.
3461
3462 // (x + n) or (n + x) => x
3463 if (BO->getOpcode() == BinaryOperator::Add) {
3464 if (BO->getLHS()->getType()->isPointerType()) {
3465 return getPrimaryDecl(BO->getLHS());
3466 } else if (BO->getRHS()->getType()->isPointerType()) {
3467 return getPrimaryDecl(BO->getRHS());
3468 }
3469 }
3470
3471 return 0;
3472 }
Chris Lattner4b009652007-07-25 00:24:17 +00003473 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003474 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003475 case Stmt::ImplicitCastExprClass:
3476 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003477 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003478 default:
3479 return 0;
3480 }
3481}
3482
3483/// CheckAddressOfOperand - The operand of & must be either a function
3484/// designator or an lvalue designating an object. If it is an lvalue, the
3485/// object cannot be declared with storage class register or be a bit field.
3486/// Note: The usual conversions are *not* applied to the operand of the &
3487/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00003488/// In C++, the operand might be an overloaded function name, in which case
3489/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003490QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003491 if (op->isTypeDependent())
3492 return Context.DependentTy;
3493
Steve Naroff9c6c3592008-01-13 17:10:08 +00003494 if (getLangOptions().C99) {
3495 // Implement C99-only parts of addressof rules.
3496 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3497 if (uOp->getOpcode() == UnaryOperator::Deref)
3498 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3499 // (assuming the deref expression is valid).
3500 return uOp->getSubExpr()->getType();
3501 }
3502 // Technically, there should be a check for array subscript
3503 // expressions here, but the result of one is always an lvalue anyway.
3504 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003505 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003506 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003507
Chris Lattner4b009652007-07-25 00:24:17 +00003508 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003509 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3510 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003511 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3512 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003513 return QualType();
3514 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003515 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003516 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3517 if (Field->isBitField()) {
3518 Diag(OpLoc, diag::err_typecheck_address_of)
3519 << "bit-field" << op->getSourceRange();
3520 return QualType();
3521 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003522 }
3523 // Check for Apple extension for accessing vector components.
Nate Begemana9187ab2009-02-15 22:45:20 +00003524 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3525 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Chris Lattner77d52da2008-11-20 06:06:08 +00003526 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00003527 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003528 return QualType();
3529 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00003530 // We have an lvalue with a decl. Make sure the decl is not declared
3531 // with the register storage-class specifier.
3532 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3533 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003534 Diag(OpLoc, diag::err_typecheck_address_of)
3535 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003536 return QualType();
3537 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003538 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003539 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003540 } else if (isa<FieldDecl>(dcl)) {
3541 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00003542 // Could be a pointer to member, though, if there is an explicit
3543 // scope qualifier for the class.
3544 if (isa<QualifiedDeclRefExpr>(op)) {
3545 DeclContext *Ctx = dcl->getDeclContext();
3546 if (Ctx && Ctx->isRecord())
3547 return Context.getMemberPointerType(op->getType(),
3548 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3549 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003550 } else if (isa<FunctionDecl>(dcl)) {
3551 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00003552 // As above.
3553 if (isa<QualifiedDeclRefExpr>(op)) {
3554 DeclContext *Ctx = dcl->getDeclContext();
3555 if (Ctx && Ctx->isRecord())
3556 return Context.getMemberPointerType(op->getType(),
3557 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3558 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003559 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003560 else
Chris Lattner4b009652007-07-25 00:24:17 +00003561 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003562 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00003563
Chris Lattner4b009652007-07-25 00:24:17 +00003564 // If the operand has type "type", the result has type "pointer to type".
3565 return Context.getPointerType(op->getType());
3566}
3567
Chris Lattnerda5c0872008-11-23 09:13:29 +00003568QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3569 UsualUnaryConversions(Op);
3570 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003571
Chris Lattnerda5c0872008-11-23 09:13:29 +00003572 // Note that per both C89 and C99, this is always legal, even if ptype is an
3573 // incomplete type or void. It would be possible to warn about dereferencing
3574 // a void pointer, but it's completely well-defined, and such a warning is
3575 // unlikely to catch any mistakes.
3576 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003577 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00003578
Chris Lattner77d52da2008-11-20 06:06:08 +00003579 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003580 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003581 return QualType();
3582}
3583
3584static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3585 tok::TokenKind Kind) {
3586 BinaryOperator::Opcode Opc;
3587 switch (Kind) {
3588 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00003589 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3590 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003591 case tok::star: Opc = BinaryOperator::Mul; break;
3592 case tok::slash: Opc = BinaryOperator::Div; break;
3593 case tok::percent: Opc = BinaryOperator::Rem; break;
3594 case tok::plus: Opc = BinaryOperator::Add; break;
3595 case tok::minus: Opc = BinaryOperator::Sub; break;
3596 case tok::lessless: Opc = BinaryOperator::Shl; break;
3597 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3598 case tok::lessequal: Opc = BinaryOperator::LE; break;
3599 case tok::less: Opc = BinaryOperator::LT; break;
3600 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3601 case tok::greater: Opc = BinaryOperator::GT; break;
3602 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3603 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3604 case tok::amp: Opc = BinaryOperator::And; break;
3605 case tok::caret: Opc = BinaryOperator::Xor; break;
3606 case tok::pipe: Opc = BinaryOperator::Or; break;
3607 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3608 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3609 case tok::equal: Opc = BinaryOperator::Assign; break;
3610 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3611 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3612 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3613 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3614 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3615 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3616 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3617 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3618 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3619 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3620 case tok::comma: Opc = BinaryOperator::Comma; break;
3621 }
3622 return Opc;
3623}
3624
3625static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3626 tok::TokenKind Kind) {
3627 UnaryOperator::Opcode Opc;
3628 switch (Kind) {
3629 default: assert(0 && "Unknown unary op!");
3630 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3631 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3632 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3633 case tok::star: Opc = UnaryOperator::Deref; break;
3634 case tok::plus: Opc = UnaryOperator::Plus; break;
3635 case tok::minus: Opc = UnaryOperator::Minus; break;
3636 case tok::tilde: Opc = UnaryOperator::Not; break;
3637 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003638 case tok::kw___real: Opc = UnaryOperator::Real; break;
3639 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3640 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3641 }
3642 return Opc;
3643}
3644
Douglas Gregord7f915e2008-11-06 23:29:22 +00003645/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3646/// operator @p Opc at location @c TokLoc. This routine only supports
3647/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003648Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3649 unsigned Op,
3650 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003651 QualType ResultTy; // Result type of the binary operator.
3652 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3653 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3654
3655 switch (Opc) {
3656 default:
3657 assert(0 && "Unknown binary expr!");
3658 case BinaryOperator::Assign:
3659 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3660 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003661 case BinaryOperator::PtrMemD:
3662 case BinaryOperator::PtrMemI:
3663 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3664 Opc == BinaryOperator::PtrMemI);
3665 break;
3666 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003667 case BinaryOperator::Div:
3668 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3669 break;
3670 case BinaryOperator::Rem:
3671 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3672 break;
3673 case BinaryOperator::Add:
3674 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3675 break;
3676 case BinaryOperator::Sub:
3677 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3678 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003679 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003680 case BinaryOperator::Shr:
3681 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3682 break;
3683 case BinaryOperator::LE:
3684 case BinaryOperator::LT:
3685 case BinaryOperator::GE:
3686 case BinaryOperator::GT:
3687 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3688 break;
3689 case BinaryOperator::EQ:
3690 case BinaryOperator::NE:
3691 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3692 break;
3693 case BinaryOperator::And:
3694 case BinaryOperator::Xor:
3695 case BinaryOperator::Or:
3696 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3697 break;
3698 case BinaryOperator::LAnd:
3699 case BinaryOperator::LOr:
3700 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3701 break;
3702 case BinaryOperator::MulAssign:
3703 case BinaryOperator::DivAssign:
3704 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3705 if (!CompTy.isNull())
3706 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3707 break;
3708 case BinaryOperator::RemAssign:
3709 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3710 if (!CompTy.isNull())
3711 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3712 break;
3713 case BinaryOperator::AddAssign:
3714 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3715 if (!CompTy.isNull())
3716 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3717 break;
3718 case BinaryOperator::SubAssign:
3719 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3720 if (!CompTy.isNull())
3721 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3722 break;
3723 case BinaryOperator::ShlAssign:
3724 case BinaryOperator::ShrAssign:
3725 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3726 if (!CompTy.isNull())
3727 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3728 break;
3729 case BinaryOperator::AndAssign:
3730 case BinaryOperator::XorAssign:
3731 case BinaryOperator::OrAssign:
3732 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3733 if (!CompTy.isNull())
3734 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3735 break;
3736 case BinaryOperator::Comma:
3737 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3738 break;
3739 }
3740 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003741 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00003742 if (CompTy.isNull())
3743 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3744 else
3745 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Steve Naroff8b9a98d2009-01-20 21:06:31 +00003746 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003747}
3748
Chris Lattner4b009652007-07-25 00:24:17 +00003749// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003750Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3751 tok::TokenKind Kind,
3752 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003753 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003754 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003755
Steve Naroff87d58b42007-09-16 03:34:24 +00003756 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3757 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003758
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003759 // If either expression is type-dependent, just build the AST.
3760 // FIXME: We'll need to perform some caching of the result of name
3761 // lookup for operator+.
3762 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff774e4152009-01-21 00:14:39 +00003763 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3764 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003765 Context.DependentTy,
3766 Context.DependentTy, TokLoc));
Steve Naroff774e4152009-01-21 00:14:39 +00003767 else
Sebastian Redl95216a62009-02-07 00:15:38 +00003768 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc,
3769 Context.DependentTy, TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003770 }
3771
Sebastian Redl95216a62009-02-07 00:15:38 +00003772 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD &&
Douglas Gregord7f915e2008-11-06 23:29:22 +00003773 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3774 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003775 // If this is one of the assignment operators, we only perform
3776 // overload resolution if the left-hand side is a class or
3777 // enumeration type (C++ [expr.ass]p3).
3778 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3779 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3780 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3781 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003782
Douglas Gregord7f915e2008-11-06 23:29:22 +00003783 // Determine which overloaded operator we're dealing with.
3784 static const OverloadedOperatorKind OverOps[] = {
Sebastian Redl95216a62009-02-07 00:15:38 +00003785 // Overloading .* is not possible.
3786 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar,
Douglas Gregord7f915e2008-11-06 23:29:22 +00003787 OO_Star, OO_Slash, OO_Percent,
3788 OO_Plus, OO_Minus,
3789 OO_LessLess, OO_GreaterGreater,
3790 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3791 OO_EqualEqual, OO_ExclaimEqual,
3792 OO_Amp,
3793 OO_Caret,
3794 OO_Pipe,
3795 OO_AmpAmp,
3796 OO_PipePipe,
3797 OO_Equal, OO_StarEqual,
3798 OO_SlashEqual, OO_PercentEqual,
3799 OO_PlusEqual, OO_MinusEqual,
3800 OO_LessLessEqual, OO_GreaterGreaterEqual,
3801 OO_AmpEqual, OO_CaretEqual,
3802 OO_PipeEqual,
3803 OO_Comma
3804 };
3805 OverloadedOperatorKind OverOp = OverOps[Opc];
3806
Douglas Gregor5ed15042008-11-18 23:14:02 +00003807 // Add the appropriate overloaded operators (C++ [over.match.oper])
3808 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003809 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003810 Expr *Args[2] = { lhs, rhs };
Douglas Gregor48a87322009-02-04 16:44:47 +00003811 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3812 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003813
3814 // Perform overload resolution.
3815 OverloadCandidateSet::iterator Best;
3816 switch (BestViableFunction(CandidateSet, Best)) {
3817 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003818 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003819 FunctionDecl *FnDecl = Best->Function;
3820
Douglas Gregor70d26122008-11-12 17:17:38 +00003821 if (FnDecl) {
3822 // We matched an overloaded operator. Build a call to that
3823 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003824
Douglas Gregor70d26122008-11-12 17:17:38 +00003825 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003826 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3827 if (PerformObjectArgumentInitialization(lhs, Method) ||
3828 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3829 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003830 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003831 } else {
3832 // Convert the arguments.
3833 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3834 "passing") ||
3835 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3836 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003837 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003838 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003839
Douglas Gregor70d26122008-11-12 17:17:38 +00003840 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003841 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003842 = FnDecl->getType()->getAsFunctionType()->getResultType();
3843 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003844
Douglas Gregor70d26122008-11-12 17:17:38 +00003845 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003846 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3847 SourceLocation());
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003848 UsualUnaryConversions(FnExpr);
3849
Ted Kremenek362abcd2009-02-09 20:51:47 +00003850 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00003851 ResultTy, TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003852 } else {
3853 // We matched a built-in operator. Convert the arguments, then
3854 // break out so that we will build the appropriate built-in
3855 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003856 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3857 Best->Conversions[0], "passing") ||
3858 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3859 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003860 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003861
3862 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003863 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003864 }
3865
3866 case OR_No_Viable_Function:
3867 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003868 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003869 break;
3870
3871 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003872 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3873 << BinaryOperator::getOpcodeStr(Opc)
3874 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003875 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003876 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003877 }
3878
Douglas Gregor70d26122008-11-12 17:17:38 +00003879 // Either we found no viable overloaded operator or we matched a
3880 // built-in operator. In either case, fall through to trying to
3881 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003882 }
3883
Douglas Gregord7f915e2008-11-06 23:29:22 +00003884 // Build a built-in binary operation.
3885 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003886}
3887
3888// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00003889Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3890 tok::TokenKind Op, ExprArg input) {
3891 // FIXME: Input is modified later, but smart pointer not reassigned.
3892 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00003893 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003894
3895 if (getLangOptions().CPlusPlus &&
3896 (Input->getType()->isRecordType()
3897 || Input->getType()->isEnumeralType())) {
3898 // Determine which overloaded operator we're dealing with.
3899 static const OverloadedOperatorKind OverOps[] = {
3900 OO_None, OO_None,
3901 OO_PlusPlus, OO_MinusMinus,
3902 OO_Amp, OO_Star,
3903 OO_Plus, OO_Minus,
3904 OO_Tilde, OO_Exclaim,
3905 OO_None, OO_None,
3906 OO_None,
3907 OO_None
3908 };
3909 OverloadedOperatorKind OverOp = OverOps[Opc];
3910
3911 // Add the appropriate overloaded operators (C++ [over.match.oper])
3912 // to the candidate set.
3913 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00003914 if (OverOp != OO_None &&
3915 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
3916 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003917
3918 // Perform overload resolution.
3919 OverloadCandidateSet::iterator Best;
3920 switch (BestViableFunction(CandidateSet, Best)) {
3921 case OR_Success: {
3922 // We found a built-in operator or an overloaded operator.
3923 FunctionDecl *FnDecl = Best->Function;
3924
3925 if (FnDecl) {
3926 // We matched an overloaded operator. Build a call to that
3927 // operator.
3928
3929 // Convert the arguments.
3930 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3931 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00003932 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003933 } else {
3934 // Convert the arguments.
3935 if (PerformCopyInitialization(Input,
3936 FnDecl->getParamDecl(0)->getType(),
3937 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003938 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003939 }
3940
3941 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00003942 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003943 = FnDecl->getType()->getAsFunctionType()->getResultType();
3944 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00003945
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003946 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003947 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3948 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003949 UsualUnaryConversions(FnExpr);
3950
Sebastian Redl8b769972009-01-19 00:08:26 +00003951 input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00003952 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input, 1,
Steve Naroff774e4152009-01-21 00:14:39 +00003953 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003954 } else {
3955 // We matched a built-in operator. Convert the arguments, then
3956 // break out so that we will build the appropriate built-in
3957 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003958 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3959 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00003960 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003961
3962 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00003963 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003964 }
3965
3966 case OR_No_Viable_Function:
3967 // No viable function; fall through to handling this as a
3968 // built-in operator, which will produce an error message for us.
3969 break;
3970
3971 case OR_Ambiguous:
3972 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3973 << UnaryOperator::getOpcodeStr(Opc)
3974 << Input->getSourceRange();
3975 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00003976 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003977 }
3978
3979 // Either we found no viable overloaded operator or we matched a
3980 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00003981 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003982 }
3983
Chris Lattner4b009652007-07-25 00:24:17 +00003984 QualType resultType;
3985 switch (Opc) {
3986 default:
3987 assert(0 && "Unimplemented unary expr!");
3988 case UnaryOperator::PreInc:
3989 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003990 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3991 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00003992 break;
3993 case UnaryOperator::AddrOf:
3994 resultType = CheckAddressOfOperand(Input, OpLoc);
3995 break;
3996 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00003997 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00003998 resultType = CheckIndirectionOperand(Input, OpLoc);
3999 break;
4000 case UnaryOperator::Plus:
4001 case UnaryOperator::Minus:
4002 UsualUnaryConversions(Input);
4003 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004004 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4005 break;
4006 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4007 resultType->isEnumeralType())
4008 break;
4009 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4010 Opc == UnaryOperator::Plus &&
4011 resultType->isPointerType())
4012 break;
4013
Sebastian Redl8b769972009-01-19 00:08:26 +00004014 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4015 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004016 case UnaryOperator::Not: // bitwise complement
4017 UsualUnaryConversions(Input);
4018 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00004019 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4020 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4021 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00004022 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004023 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004024 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00004025 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4026 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004027 break;
4028 case UnaryOperator::LNot: // logical negation
4029 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4030 DefaultFunctionArrayConversion(Input);
4031 resultType = Input->getType();
4032 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004033 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4034 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004035 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004036 // In C++, it's bool. C++ 5.3.1p8
4037 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004038 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004039 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004040 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00004041 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00004042 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004043 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004044 resultType = Input->getType();
4045 break;
4046 }
4047 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004048 return ExprError();
4049 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004050 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004051}
4052
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004053/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4054Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00004055 SourceLocation LabLoc,
4056 IdentifierInfo *LabelII) {
4057 // Look up the record for this label identifier.
4058 LabelStmt *&LabelDecl = LabelMap[LabelII];
4059
Daniel Dunbar879788d2008-08-04 16:51:22 +00004060 // If we haven't seen this label yet, create a forward reference. It
4061 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00004062 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004063 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00004064
4065 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff774e4152009-01-21 00:14:39 +00004066 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4067 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00004068}
4069
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004070Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00004071 SourceLocation RPLoc) { // "({..})"
4072 Stmt *SubStmt = static_cast<Stmt*>(substmt);
4073 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4074 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4075
Eli Friedmanbc941e12009-01-24 23:09:00 +00004076 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4077 if (isFileScope) {
4078 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4079 }
4080
Chris Lattner4b009652007-07-25 00:24:17 +00004081 // FIXME: there are a variety of strange constraints to enforce here, for
4082 // example, it is not possible to goto into a stmt expression apparently.
4083 // More semantic analysis is needed.
4084
4085 // FIXME: the last statement in the compount stmt has its value used. We
4086 // should not warn about it being unused.
4087
4088 // If there are sub stmts in the compound stmt, take the type of the last one
4089 // as the type of the stmtexpr.
4090 QualType Ty = Context.VoidTy;
4091
Chris Lattner200964f2008-07-26 19:51:01 +00004092 if (!Compound->body_empty()) {
4093 Stmt *LastStmt = Compound->body_back();
4094 // If LastStmt is a label, skip down through into the body.
4095 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4096 LastStmt = Label->getSubStmt();
4097
4098 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004099 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004100 }
Chris Lattner4b009652007-07-25 00:24:17 +00004101
Steve Naroff774e4152009-01-21 00:14:39 +00004102 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00004103}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004104
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004105Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4106 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004107 SourceLocation TypeLoc,
4108 TypeTy *argty,
4109 OffsetOfComponent *CompPtr,
4110 unsigned NumComponents,
4111 SourceLocation RPLoc) {
4112 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4113 assert(!ArgTy.isNull() && "Missing type argument!");
4114
4115 // We must have at least one component that refers to the type, and the first
4116 // one is known to be a field designator. Verify that the ArgTy represents
4117 // a struct/union/class.
4118 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00004119 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004120
4121 // Otherwise, create a compound literal expression as the base, and
4122 // iteratively process the offsetof designators.
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004123 InitListExpr *IList =
Douglas Gregorf603b472009-01-28 21:54:33 +00004124 new (Context) InitListExpr(SourceLocation(), 0, 0, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004125 IList->setType(ArgTy);
4126 Expr *Res =
4127 new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, IList, false);
4128
Chris Lattnerb37522e2007-08-31 21:49:13 +00004129 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4130 // GCC extension, diagnose them.
4131 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004132 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4133 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00004134
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004135 for (unsigned i = 0; i != NumComponents; ++i) {
4136 const OffsetOfComponent &OC = CompPtr[i];
4137 if (OC.isBrackets) {
4138 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00004139 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004140 if (!AT) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004141 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004142 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004143 }
4144
Chris Lattner2af6a802007-08-30 17:59:59 +00004145 // FIXME: C++: Verify that operator[] isn't overloaded.
4146
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004147 // C99 6.5.2.1p1
4148 Expr *Idx = static_cast<Expr*>(OC.U.E);
4149 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00004150 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4151 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004152
Steve Naroff774e4152009-01-21 00:14:39 +00004153 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4154 OC.LocEnd);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004155 continue;
4156 }
4157
4158 const RecordType *RC = Res->getType()->getAsRecordType();
4159 if (!RC) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004160 Res->Destroy(Context);
Chris Lattner4bfd2232008-11-24 06:25:27 +00004161 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004162 }
4163
4164 // Get the decl corresponding to this.
4165 RecordDecl *RD = RC->getDecl();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004166 FieldDecl *MemberDecl
Douglas Gregor52ae30c2009-01-30 01:04:22 +00004167 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4168 LookupMemberName)
4169 .getAsDecl());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004170 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00004171 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4172 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00004173
4174 // FIXME: C++: Verify that MemberDecl isn't a static field.
4175 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00004176 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4177 // matter here.
Steve Naroff774e4152009-01-21 00:14:39 +00004178 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4179 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004180 }
4181
Steve Naroff774e4152009-01-21 00:14:39 +00004182 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4183 Context.getSizeType(), BuiltinLoc);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004184}
4185
4186
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004187Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00004188 TypeTy *arg1, TypeTy *arg2,
4189 SourceLocation RPLoc) {
4190 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4191 QualType argT2 = QualType::getFromOpaquePtr(arg2);
4192
4193 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4194
Steve Naroff774e4152009-01-21 00:14:39 +00004195 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
4196 argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00004197}
4198
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004199Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00004200 ExprTy *expr1, ExprTy *expr2,
4201 SourceLocation RPLoc) {
4202 Expr *CondExpr = static_cast<Expr*>(cond);
4203 Expr *LHSExpr = static_cast<Expr*>(expr1);
4204 Expr *RHSExpr = static_cast<Expr*>(expr2);
4205
4206 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4207
4208 // The conditional expression is required to be a constant expression.
4209 llvm::APSInt condEval(32);
4210 SourceLocation ExpLoc;
4211 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004212 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4213 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00004214
4215 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4216 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
4217 RHSExpr->getType();
Steve Naroff774e4152009-01-21 00:14:39 +00004218 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4219 resType, RPLoc);
Steve Naroff93c53012007-08-03 21:21:27 +00004220}
4221
Steve Naroff52a81c02008-09-03 18:15:37 +00004222//===----------------------------------------------------------------------===//
4223// Clang Extensions.
4224//===----------------------------------------------------------------------===//
4225
4226/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004227void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004228 // Analyze block parameters.
4229 BlockSemaInfo *BSI = new BlockSemaInfo();
4230
4231 // Add BSI to CurBlock.
4232 BSI->PrevBlockInfo = CurBlock;
4233 CurBlock = BSI;
4234
4235 BSI->ReturnType = 0;
4236 BSI->TheScope = BlockScope;
4237
Steve Naroff52059382008-10-10 01:28:17 +00004238 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004239 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004240}
4241
Mike Stumpc1fddff2009-02-04 22:31:32 +00004242void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4243 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4244
4245 if (ParamInfo.getNumTypeObjects() == 0
4246 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4247 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4248
4249 // The type is entirely optional as well, if none, use DependentTy.
4250 if (T.isNull())
4251 T = Context.DependentTy;
4252
4253 // The parameter list is optional, if there was none, assume ().
4254 if (!T->isFunctionType())
4255 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4256
4257 CurBlock->hasPrototype = true;
4258 CurBlock->isVariadic = false;
4259 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4260 .getTypePtr();
4261
4262 if (!RetTy->isDependentType())
4263 CurBlock->ReturnType = RetTy;
4264 return;
4265 }
4266
Steve Naroff52a81c02008-09-03 18:15:37 +00004267 // Analyze arguments to block.
4268 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4269 "Not a function declarator!");
4270 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004271
Steve Naroff52059382008-10-10 01:28:17 +00004272 CurBlock->hasPrototype = FTI.hasPrototype;
4273 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00004274
4275 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4276 // no arguments, not a function that takes a single void argument.
4277 if (FTI.hasPrototype &&
4278 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4279 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4280 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4281 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004282 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004283 } else if (FTI.hasPrototype) {
4284 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004285 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4286 CurBlock->isVariadic = FTI.isVariadic;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004287 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4288
4289 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4290 .getTypePtr();
4291
4292 if (!RetTy->isDependentType())
4293 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00004294 }
Steve Naroff52059382008-10-10 01:28:17 +00004295 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4296
4297 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4298 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4299 // If this has an identifier, add it to the scope stack.
4300 if ((*AI)->getIdentifier())
4301 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004302}
4303
4304/// ActOnBlockError - If there is an error parsing a block, this callback
4305/// is invoked to pop the information about the block from the action impl.
4306void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4307 // Ensure that CurBlock is deleted.
4308 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4309
4310 // Pop off CurBlock, handle nested blocks.
4311 CurBlock = CurBlock->PrevBlockInfo;
4312
4313 // FIXME: Delete the ParmVarDecl objects as well???
4314
4315}
4316
4317/// ActOnBlockStmtExpr - This is called when the body of a block statement
4318/// literal was successfully completed. ^(int x){...}
4319Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4320 Scope *CurScope) {
4321 // Ensure that CurBlock is deleted.
4322 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Ted Kremenek0c97e042009-02-07 01:47:29 +00004323 ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body));
Steve Naroff52a81c02008-09-03 18:15:37 +00004324
Steve Naroff52059382008-10-10 01:28:17 +00004325 PopDeclContext();
4326
Steve Naroff52a81c02008-09-03 18:15:37 +00004327 // Pop off CurBlock, handle nested blocks.
4328 CurBlock = CurBlock->PrevBlockInfo;
4329
4330 QualType RetTy = Context.VoidTy;
4331 if (BSI->ReturnType)
4332 RetTy = QualType(BSI->ReturnType, 0);
4333
4334 llvm::SmallVector<QualType, 8> ArgTypes;
4335 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4336 ArgTypes.push_back(BSI->Params[i]->getType());
4337
4338 QualType BlockTy;
4339 if (!BSI->hasPrototype)
4340 BlockTy = Context.getFunctionTypeNoProto(RetTy);
4341 else
4342 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004343 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00004344
4345 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00004346
Steve Naroff95029d92008-10-08 18:44:00 +00004347 BSI->TheDecl->setBody(Body.take());
Steve Naroff774e4152009-01-21 00:14:39 +00004348 return new (Context) BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004349}
4350
Nate Begemanbd881ef2008-01-30 20:50:20 +00004351/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004352/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00004353/// The number of arguments has already been validated to match the number of
4354/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004355static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4356 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004357 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00004358 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004359 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4360 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00004361
4362 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004363 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00004364 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004365 return true;
4366}
4367
4368Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4369 SourceLocation *CommaLocs,
4370 SourceLocation BuiltinLoc,
4371 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004372 // __builtin_overload requires at least 2 arguments
4373 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004374 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4375 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004376
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004377 // The first argument is required to be a constant expression. It tells us
4378 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00004379 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004380 Expr *NParamsExpr = Args[0];
4381 llvm::APSInt constEval(32);
4382 SourceLocation ExpLoc;
4383 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004384 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4385 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004386
4387 // Verify that the number of parameters is > 0
4388 unsigned NumParams = constEval.getZExtValue();
4389 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004390 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4391 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004392 // Verify that we have at least 1 + NumParams arguments to the builtin.
4393 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004394 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4395 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004396
4397 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00004398 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00004399 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004400 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4401 // UsualUnaryConversions will convert the function DeclRefExpr into a
4402 // pointer to function.
4403 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004404 const FunctionTypeProto *FnType = 0;
4405 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4406 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004407
4408 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4409 // parameters, and the number of parameters must match the value passed to
4410 // the builtin.
4411 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00004412 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4413 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004414
4415 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00004416 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004417 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00004418 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00004419 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004420 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4421 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00004422 // Remember our match, and continue processing the remaining arguments
4423 // to catch any errors.
Ted Kremenekf1a67122009-02-09 17:08:14 +00004424 OE = new (Context) OverloadExpr(Context, Args, NumArgs, i,
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00004425 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00004426 BuiltinLoc, RParenLoc);
4427 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004428 }
Nate Begemanc6078c92008-01-31 05:38:29 +00004429 // Return the newly created OverloadExpr node, if we succeded in matching
4430 // exactly one of the candidate functions.
4431 if (OE)
4432 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004433
4434 // If we didn't find a matching function Expr in the __builtin_overload list
4435 // the return an error.
4436 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00004437 for (unsigned i = 0; i != NumParams; ++i) {
4438 if (i != 0) typeNames += ", ";
4439 typeNames += Args[i+1]->getType().getAsString();
4440 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004441
Chris Lattner77d52da2008-11-20 06:06:08 +00004442 return Diag(BuiltinLoc, diag::err_overload_no_match)
4443 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00004444}
4445
Anders Carlsson36760332007-10-15 20:28:48 +00004446Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4447 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004448 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004449 Expr *E = static_cast<Expr*>(expr);
4450 QualType T = QualType::getFromOpaquePtr(type);
4451
4452 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004453
4454 // Get the va_list type
4455 QualType VaListType = Context.getBuiltinVaListType();
4456 // Deal with implicit array decay; for example, on x86-64,
4457 // va_list is an array, but it's supposed to decay to
4458 // a pointer for va_arg.
4459 if (VaListType->isArrayType())
4460 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004461 // Make sure the input expression also decays appropriately.
4462 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004463
4464 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004465 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004466 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004467 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00004468
4469 // FIXME: Warn if a non-POD type is passed in.
4470
Steve Naroff774e4152009-01-21 00:14:39 +00004471 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004472}
4473
Douglas Gregorad4b3792008-11-29 04:51:27 +00004474Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4475 // The type of __null will be int or long, depending on the size of
4476 // pointers on the target.
4477 QualType Ty;
4478 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4479 Ty = Context.IntTy;
4480 else
4481 Ty = Context.LongTy;
4482
Steve Naroff774e4152009-01-21 00:14:39 +00004483 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregorad4b3792008-11-29 04:51:27 +00004484}
4485
Chris Lattner005ed752008-01-04 18:04:52 +00004486bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4487 SourceLocation Loc,
4488 QualType DstType, QualType SrcType,
4489 Expr *SrcExpr, const char *Flavor) {
4490 // Decode the result (notice that AST's are still created for extensions).
4491 bool isInvalid = false;
4492 unsigned DiagKind;
4493 switch (ConvTy) {
4494 default: assert(0 && "Unknown conversion type");
4495 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004496 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004497 DiagKind = diag::ext_typecheck_convert_pointer_int;
4498 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004499 case IntToPointer:
4500 DiagKind = diag::ext_typecheck_convert_int_pointer;
4501 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004502 case IncompatiblePointer:
4503 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4504 break;
4505 case FunctionVoidPointer:
4506 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4507 break;
4508 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004509 // If the qualifiers lost were because we were applying the
4510 // (deprecated) C++ conversion from a string literal to a char*
4511 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4512 // Ideally, this check would be performed in
4513 // CheckPointerTypesForAssignment. However, that would require a
4514 // bit of refactoring (so that the second argument is an
4515 // expression, rather than a type), which should be done as part
4516 // of a larger effort to fix CheckPointerTypesForAssignment for
4517 // C++ semantics.
4518 if (getLangOptions().CPlusPlus &&
4519 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4520 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004521 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4522 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004523 case IntToBlockPointer:
4524 DiagKind = diag::err_int_to_block_pointer;
4525 break;
4526 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004527 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004528 break;
Steve Naroff19608432008-10-14 22:18:38 +00004529 case IncompatibleObjCQualifiedId:
4530 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4531 // it can give a more specific diagnostic.
4532 DiagKind = diag::warn_incompatible_qualified_id;
4533 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004534 case IncompatibleVectors:
4535 DiagKind = diag::warn_incompatible_vectors;
4536 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004537 case Incompatible:
4538 DiagKind = diag::err_typecheck_convert_incompatible;
4539 isInvalid = true;
4540 break;
4541 }
4542
Chris Lattner271d4c22008-11-24 05:29:24 +00004543 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4544 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004545 return isInvalid;
4546}
Anders Carlssond5201b92008-11-30 19:50:32 +00004547
4548bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4549{
4550 Expr::EvalResult EvalResult;
4551
4552 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4553 EvalResult.HasSideEffects) {
4554 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4555
4556 if (EvalResult.Diag) {
4557 // We only show the note if it's not the usual "invalid subexpression"
4558 // or if it's actually in a subexpression.
4559 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4560 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4561 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4562 }
4563
4564 return true;
4565 }
4566
4567 if (EvalResult.Diag) {
4568 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4569 E->getSourceRange();
4570
4571 // Print the reason it's not a constant.
4572 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4573 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4574 }
4575
4576 if (Result)
4577 *Result = EvalResult.Val.getInt();
4578 return false;
4579}