blob: e380f78ad056f2f8177e257d6c06e1663277a0db [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
Douglas Gregoraa57e862009-02-18 21:56:37 +000029/// \brief Determine whether the use of this declaration is valid, and
30/// emit any corresponding diagnostics.
31///
32/// This routine diagnoses various problems with referencing
33/// declarations that can occur when using a declaration. For example,
34/// it might warn if a deprecated or unavailable declaration is being
35/// used, or produce an error (and return true) if a C++0x deleted
36/// function is being used.
37///
38/// \returns true if there was an error (this declaration cannot be
39/// referenced), false otherwise.
40bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000041 // See if the decl is deprecated.
42 if (D->getAttr<DeprecatedAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000043 // Implementing deprecated stuff requires referencing deprecated
44 // stuff. Don't warn if we are implementing a deprecated
45 // construct.
Chris Lattnerfb1bb822009-02-16 19:35:30 +000046 bool isSilenced = false;
47
48 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
49 // If this reference happens *in* a deprecated function or method, don't
50 // warn.
51 isSilenced = ND->getAttr<DeprecatedAttr>();
52
53 // If this is an Objective-C method implementation, check to see if the
54 // method was deprecated on the declaration, not the definition.
55 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
56 // The semantic decl context of a ObjCMethodDecl is the
57 // ObjCImplementationDecl.
58 if (ObjCImplementationDecl *Impl
59 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
60
Douglas Gregorc55b0b02009-04-09 21:40:53 +000061 MD = Impl->getClassInterface()->getMethod(Context,
62 MD->getSelector(),
Chris Lattnerfb1bb822009-02-16 19:35:30 +000063 MD->isInstanceMethod());
64 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
65 }
66 }
67 }
68
69 if (!isSilenced)
Chris Lattner2cb744b2009-02-15 22:43:40 +000070 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
71 }
72
Douglas Gregoraa57e862009-02-18 21:56:37 +000073 // See if this is a deleted function.
Douglas Gregor6f8c3682009-02-24 04:26:15 +000074 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000075 if (FD->isDeleted()) {
76 Diag(Loc, diag::err_deleted_function_use);
77 Diag(D->getLocation(), diag::note_unavailable_here) << true;
78 return true;
79 }
Douglas Gregor6f8c3682009-02-24 04:26:15 +000080 }
Douglas Gregoraa57e862009-02-18 21:56:37 +000081
82 // See if the decl is unavailable
83 if (D->getAttr<UnavailableAttr>()) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000084 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
Douglas Gregoraa57e862009-02-18 21:56:37 +000085 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
86 }
87
Douglas Gregoraa57e862009-02-18 21:56:37 +000088 return false;
Chris Lattner2cb744b2009-02-15 22:43:40 +000089}
90
Douglas Gregor3bb30002009-02-26 21:00:50 +000091SourceRange Sema::getExprRange(ExprTy *E) const {
92 Expr *Ex = (Expr *)E;
93 return Ex? Ex->getSourceRange() : SourceRange();
94}
95
Chris Lattner299b8842008-07-25 21:10:04 +000096//===----------------------------------------------------------------------===//
97// Standard Promotions and Conversions
98//===----------------------------------------------------------------------===//
99
Chris Lattner299b8842008-07-25 21:10:04 +0000100/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
101void Sema::DefaultFunctionArrayConversion(Expr *&E) {
102 QualType Ty = E->getType();
103 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
104
Chris Lattner299b8842008-07-25 21:10:04 +0000105 if (Ty->isFunctionType())
106 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +0000107 else if (Ty->isArrayType()) {
108 // In C90 mode, arrays only promote to pointers if the array expression is
109 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
110 // type 'array of type' is converted to an expression that has type 'pointer
111 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
112 // that has type 'array of type' ...". The relevant change is "an lvalue"
113 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +0000114 //
115 // C++ 4.2p1:
116 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
117 // T" can be converted to an rvalue of type "pointer to T".
118 //
119 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
120 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +0000121 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
122 }
Chris Lattner299b8842008-07-25 21:10:04 +0000123}
124
125/// UsualUnaryConversions - Performs various conversions that are common to most
126/// operators (C99 6.3). The conversions of array and function types are
127/// sometimes surpressed. For example, the array->pointer conversion doesn't
128/// apply if the array is an argument to the sizeof or address (&) operators.
129/// In these instances, this routine should *not* be called.
130Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
131 QualType Ty = Expr->getType();
132 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
133
Chris Lattner299b8842008-07-25 21:10:04 +0000134 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
135 ImpCastExprToType(Expr, Context.IntTy);
136 else
137 DefaultFunctionArrayConversion(Expr);
138
139 return Expr;
140}
141
Chris Lattner9305c3d2008-07-25 22:25:12 +0000142/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
143/// do not have a prototype. Arguments that have type float are promoted to
144/// double. All other argument types are converted by UsualUnaryConversions().
145void Sema::DefaultArgumentPromotion(Expr *&Expr) {
146 QualType Ty = Expr->getType();
147 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
148
149 // If this is a 'float' (CVR qualified or typedef) promote to double.
150 if (const BuiltinType *BT = Ty->getAsBuiltinType())
151 if (BT->getKind() == BuiltinType::Float)
152 return ImpCastExprToType(Expr, Context.DoubleTy);
153
154 UsualUnaryConversions(Expr);
155}
156
Chris Lattner81f00ed2009-04-12 08:11:20 +0000157/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
158/// will warn if the resulting type is not a POD type, and rejects ObjC
159/// interfaces passed by value. This returns true if the argument type is
160/// completely illegal.
161bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000162 DefaultArgumentPromotion(Expr);
163
Chris Lattner81f00ed2009-04-12 08:11:20 +0000164 if (Expr->getType()->isObjCInterfaceType()) {
165 Diag(Expr->getLocStart(),
166 diag::err_cannot_pass_objc_interface_to_vararg)
167 << Expr->getType() << CT;
168 return true;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000169 }
Chris Lattner81f00ed2009-04-12 08:11:20 +0000170
171 if (!Expr->getType()->isPODType())
172 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
173 << Expr->getType() << CT;
174
175 return false;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000176}
177
178
Chris Lattner299b8842008-07-25 21:10:04 +0000179/// UsualArithmeticConversions - Performs various conversions that are common to
180/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
181/// routine returns the first non-arithmetic type found. The client is
182/// responsible for emitting appropriate error diagnostics.
183/// FIXME: verify the conversion rules for "complex int" are consistent with
184/// GCC.
185QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
186 bool isCompAssign) {
Eli Friedman3cd92882009-03-28 01:22:36 +0000187 if (!isCompAssign)
Chris Lattner299b8842008-07-25 21:10:04 +0000188 UsualUnaryConversions(lhsExpr);
Eli Friedman3cd92882009-03-28 01:22:36 +0000189
190 UsualUnaryConversions(rhsExpr);
Douglas Gregor70d26122008-11-12 17:17:38 +0000191
Chris Lattner299b8842008-07-25 21:10:04 +0000192 // For conversion purposes, we ignore any qualifiers.
193 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000194 QualType lhs =
195 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
196 QualType rhs =
197 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000198
199 // If both types are identical, no conversion is needed.
200 if (lhs == rhs)
201 return lhs;
202
203 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
204 // The caller can deal with this (e.g. pointer + int).
205 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
206 return lhs;
207
208 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman3cd92882009-03-28 01:22:36 +0000209 if (!isCompAssign)
Douglas Gregor70d26122008-11-12 17:17:38 +0000210 ImpCastExprToType(lhsExpr, destType);
Eli Friedman3cd92882009-03-28 01:22:36 +0000211 ImpCastExprToType(rhsExpr, destType);
Douglas Gregor70d26122008-11-12 17:17:38 +0000212 return destType;
213}
214
215QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
216 // Perform the usual unary conversions. We do this early so that
217 // integral promotions to "int" can allow us to exit early, in the
218 // lhs == rhs check. Also, for conversion purposes, we ignore any
219 // qualifiers. For example, "const float" and "float" are
220 // equivalent.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000221 if (lhs->isPromotableIntegerType())
222 lhs = Context.IntTy;
223 else
224 lhs = lhs.getUnqualifiedType();
225 if (rhs->isPromotableIntegerType())
226 rhs = Context.IntTy;
227 else
228 rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000229
Chris Lattner299b8842008-07-25 21:10:04 +0000230 // If both types are identical, no conversion is needed.
231 if (lhs == rhs)
232 return lhs;
233
234 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
235 // The caller can deal with this (e.g. pointer + int).
236 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
237 return lhs;
238
239 // At this point, we have two different arithmetic types.
240
241 // Handle complex types first (C99 6.3.1.8p1).
242 if (lhs->isComplexType() || rhs->isComplexType()) {
243 // if we have an integer operand, the result is the complex type.
244 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
245 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000246 return lhs;
247 }
248 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
249 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000250 return rhs;
251 }
252 // This handles complex/complex, complex/float, or float/complex.
253 // When both operands are complex, the shorter operand is converted to the
254 // type of the longer, and that is the type of the result. This corresponds
255 // to what is done when combining two real floating-point operands.
256 // The fun begins when size promotion occur across type domains.
257 // From H&S 6.3.4: When one operand is complex and the other is a real
258 // floating-point type, the less precise type is converted, within it's
259 // real or complex domain, to the precision of the other type. For example,
260 // when combining a "long double" with a "double _Complex", the
261 // "double _Complex" is promoted to "long double _Complex".
262 int result = Context.getFloatingTypeOrder(lhs, rhs);
263
264 if (result > 0) { // The left side is bigger, convert rhs.
265 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000266 } else if (result < 0) { // The right side is bigger, convert lhs.
267 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000268 }
269 // At this point, lhs and rhs have the same rank/size. Now, make sure the
270 // domains match. This is a requirement for our implementation, C99
271 // does not require this promotion.
272 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
273 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000274 return rhs;
275 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000276 return lhs;
277 }
278 }
279 return lhs; // The domain/size match exactly.
280 }
281 // Now handle "real" floating types (i.e. float, double, long double).
282 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
283 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000284 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000285 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000286 return lhs;
287 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000288 if (rhs->isComplexIntegerType()) {
289 // convert rhs to the complex floating point type.
290 return Context.getComplexType(lhs);
291 }
292 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000293 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000294 return rhs;
295 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000296 if (lhs->isComplexIntegerType()) {
297 // convert lhs to the complex floating point type.
298 return Context.getComplexType(rhs);
299 }
Chris Lattner299b8842008-07-25 21:10:04 +0000300 // We have two real floating types, float/complex combos were handled above.
301 // Convert the smaller operand to the bigger result.
302 int result = Context.getFloatingTypeOrder(lhs, rhs);
Chris Lattner2cb744b2009-02-15 22:43:40 +0000303 if (result > 0) // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000304 return lhs;
Chris Lattner2cb744b2009-02-15 22:43:40 +0000305 assert(result < 0 && "illegal float comparison");
306 return rhs; // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000307 }
308 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
309 // Handle GCC complex int extension.
310 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
311 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
312
313 if (lhsComplexInt && rhsComplexInt) {
314 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
Chris Lattner2cb744b2009-02-15 22:43:40 +0000315 rhsComplexInt->getElementType()) >= 0)
316 return lhs; // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000317 return rhs;
318 } else if (lhsComplexInt && rhs->isIntegerType()) {
319 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000320 return lhs;
321 } else if (rhsComplexInt && lhs->isIntegerType()) {
322 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000323 return rhs;
324 }
325 }
326 // Finally, we have two differing integer types.
327 // The rules for this case are in C99 6.3.1.8
328 int compare = Context.getIntegerTypeOrder(lhs, rhs);
329 bool lhsSigned = lhs->isSignedIntegerType(),
330 rhsSigned = rhs->isSignedIntegerType();
331 QualType destType;
332 if (lhsSigned == rhsSigned) {
333 // Same signedness; use the higher-ranked type
334 destType = compare >= 0 ? lhs : rhs;
335 } else if (compare != (lhsSigned ? 1 : -1)) {
336 // The unsigned type has greater than or equal rank to the
337 // signed type, so use the unsigned type
338 destType = lhsSigned ? rhs : lhs;
339 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
340 // The two types are different widths; if we are here, that
341 // means the signed type is larger than the unsigned type, so
342 // use the signed type.
343 destType = lhsSigned ? lhs : rhs;
344 } else {
345 // The signed type is higher-ranked than the unsigned type,
346 // but isn't actually any bigger (like unsigned int and long
347 // on most 32-bit systems). Use the unsigned type corresponding
348 // to the signed type.
349 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
350 }
Chris Lattner299b8842008-07-25 21:10:04 +0000351 return destType;
352}
353
354//===----------------------------------------------------------------------===//
355// Semantic Analysis for various Expression Types
356//===----------------------------------------------------------------------===//
357
358
Steve Naroff87d58b42007-09-16 03:34:24 +0000359/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000360/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
361/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
362/// multiple tokens. However, the common case is that StringToks points to one
363/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000364///
365Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000366Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000367 assert(NumStringToks && "Must have at least one string!");
368
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000369 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000370 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000371 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000372
373 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
374 for (unsigned i = 0; i != NumStringToks; ++i)
375 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000376
Chris Lattnera6dcce32008-02-11 00:02:17 +0000377 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000378 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000379 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000380
381 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
382 if (getLangOptions().CPlusPlus)
383 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000384
Chris Lattnera6dcce32008-02-11 00:02:17 +0000385 // Get an array type for the string, according to C99 6.4.5. This includes
386 // the nul terminator character as well as the string length for pascal
387 // strings.
388 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattner14032222009-02-26 23:01:51 +0000389 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000390 ArrayType::Normal, 0);
Chris Lattnerc3144742009-02-18 05:49:11 +0000391
Chris Lattner4b009652007-07-25 00:24:17 +0000392 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattneraa491192009-02-18 06:40:38 +0000393 return Owned(StringLiteral::Create(Context, Literal.GetString(),
394 Literal.GetStringLength(),
395 Literal.AnyWide, StrTy,
396 &StringTokLocs[0],
397 StringTokLocs.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000398}
399
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000400/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
401/// CurBlock to VD should cause it to be snapshotted (as we do for auto
402/// variables defined outside the block) or false if this is not needed (e.g.
403/// for values inside the block or for globals).
404///
405/// FIXME: This will create BlockDeclRefExprs for global variables,
406/// function references, etc which is suboptimal :) and breaks
407/// things like "integer constant expression" tests.
408static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
409 ValueDecl *VD) {
410 // If the value is defined inside the block, we couldn't snapshot it even if
411 // we wanted to.
412 if (CurBlock->TheDecl == VD->getDeclContext())
413 return false;
414
415 // If this is an enum constant or function, it is constant, don't snapshot.
416 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
417 return false;
418
419 // If this is a reference to an extern, static, or global variable, no need to
420 // snapshot it.
421 // FIXME: What about 'const' variables in C++?
422 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
423 return Var->hasLocalStorage();
424
425 return true;
426}
427
428
429
Steve Naroff0acc9c92007-09-15 18:49:24 +0000430/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000431/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000432/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000433/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000434/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000435Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
436 IdentifierInfo &II,
437 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000438 const CXXScopeSpec *SS,
439 bool isAddressOfOperand) {
440 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000441 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000442}
443
Douglas Gregor566782a2009-01-06 05:10:23 +0000444/// BuildDeclRefExpr - Build either a DeclRefExpr or a
445/// QualifiedDeclRefExpr based on whether or not SS is a
446/// nested-name-specifier.
Sebastian Redl0c9da212009-02-03 20:19:35 +0000447DeclRefExpr *
448Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
449 bool TypeDependent, bool ValueDependent,
450 const CXXScopeSpec *SS) {
Douglas Gregor7e508262009-03-19 03:51:16 +0000451 if (SS && !SS->isEmpty()) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000452 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
453 ValueDependent, SS->getRange(),
Douglas Gregor041e9292009-03-26 23:56:24 +0000454 static_cast<NestedNameSpecifier *>(SS->getScopeRep()));
Douglas Gregor7e508262009-03-19 03:51:16 +0000455 } else
Steve Naroff774e4152009-01-21 00:14:39 +0000456 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000457}
458
Douglas Gregor723d3332009-01-07 00:43:41 +0000459/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
460/// variable corresponding to the anonymous union or struct whose type
461/// is Record.
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000462static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
463 RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000464 assert(Record->isAnonymousStructOrUnion() &&
465 "Record must be an anonymous struct or union!");
466
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000467 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000468 // be an O(1) operation rather than a slow walk through DeclContext's
469 // vector (which itself will be eliminated). DeclGroups might make
470 // this even better.
471 DeclContext *Ctx = Record->getDeclContext();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000472 for (DeclContext::decl_iterator D = Ctx->decls_begin(Context),
473 DEnd = Ctx->decls_end(Context);
Douglas Gregor723d3332009-01-07 00:43:41 +0000474 D != DEnd; ++D) {
475 if (*D == Record) {
476 // The object for the anonymous struct/union directly
477 // follows its type in the list of declarations.
478 ++D;
479 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000480 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000481 return *D;
482 }
483 }
484
485 assert(false && "Missing object for anonymous record");
486 return 0;
487}
488
Sebastian Redlcd883f72009-01-18 18:53:16 +0000489Sema::OwningExprResult
Douglas Gregor723d3332009-01-07 00:43:41 +0000490Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
491 FieldDecl *Field,
492 Expr *BaseObjectExpr,
493 SourceLocation OpLoc) {
494 assert(Field->getDeclContext()->isRecord() &&
495 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
496 && "Field must be stored inside an anonymous struct or union");
497
498 // Construct the sequence of field member references
499 // we'll have to perform to get to the field in the anonymous
500 // union/struct. The list of members is built from the field
501 // outward, so traverse it backwards to go from an object in
502 // the current context to the field we found.
503 llvm::SmallVector<FieldDecl *, 4> AnonFields;
504 AnonFields.push_back(Field);
505 VarDecl *BaseObject = 0;
506 DeclContext *Ctx = Field->getDeclContext();
507 do {
508 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000509 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000510 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
511 AnonFields.push_back(AnonField);
512 else {
513 BaseObject = cast<VarDecl>(AnonObject);
514 break;
515 }
516 Ctx = Ctx->getParent();
517 } while (Ctx->isRecord() &&
518 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
519
520 // Build the expression that refers to the base object, from
521 // which we will build a sequence of member references to each
522 // of the anonymous union objects and, eventually, the field we
523 // found via name lookup.
524 bool BaseObjectIsPointer = false;
525 unsigned ExtraQuals = 0;
526 if (BaseObject) {
527 // BaseObject is an anonymous struct/union variable (and is,
528 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000529 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff774e4152009-01-21 00:14:39 +0000530 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump9afab102009-02-19 03:04:26 +0000531 SourceLocation());
Douglas Gregor723d3332009-01-07 00:43:41 +0000532 ExtraQuals
533 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
534 } else if (BaseObjectExpr) {
535 // The caller provided the base object expression. Determine
536 // whether its a pointer and whether it adds any qualifiers to the
537 // anonymous struct/union fields we're looking into.
538 QualType ObjectType = BaseObjectExpr->getType();
539 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
540 BaseObjectIsPointer = true;
541 ObjectType = ObjectPtr->getPointeeType();
542 }
543 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
544 } else {
545 // We've found a member of an anonymous struct/union that is
546 // inside a non-anonymous struct/union, so in a well-formed
547 // program our base object expression is "this".
548 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
549 if (!MD->isStatic()) {
550 QualType AnonFieldType
551 = Context.getTagDeclType(
552 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
553 QualType ThisType = Context.getTagDeclType(MD->getParent());
554 if ((Context.getCanonicalType(AnonFieldType)
555 == Context.getCanonicalType(ThisType)) ||
556 IsDerivedFrom(ThisType, AnonFieldType)) {
557 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000558 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000559 MD->getThisType(Context));
Douglas Gregor723d3332009-01-07 00:43:41 +0000560 BaseObjectIsPointer = true;
561 }
562 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000563 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
564 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000565 }
566 ExtraQuals = MD->getTypeQualifiers();
567 }
568
569 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000570 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
571 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000572 }
573
574 // Build the implicit member references to the field of the
575 // anonymous struct/union.
576 Expr *Result = BaseObjectExpr;
577 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
578 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
579 FI != FIEnd; ++FI) {
580 QualType MemberType = (*FI)->getType();
581 if (!(*FI)->isMutable()) {
582 unsigned combinedQualifiers
583 = MemberType.getCVRQualifiers() | ExtraQuals;
584 MemberType = MemberType.getQualifiedType(combinedQualifiers);
585 }
Steve Naroff774e4152009-01-21 00:14:39 +0000586 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
587 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000588 BaseObjectIsPointer = false;
589 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregor723d3332009-01-07 00:43:41 +0000590 }
591
Sebastian Redlcd883f72009-01-18 18:53:16 +0000592 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000593}
594
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000595/// ActOnDeclarationNameExpr - The parser has read some kind of name
596/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
597/// performs lookup on that name and returns an expression that refers
598/// to that name. This routine isn't directly called from the parser,
599/// because the parser doesn't know about DeclarationName. Rather,
600/// this routine is called by ActOnIdentifierExpr,
601/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
602/// which form the DeclarationName from the corresponding syntactic
603/// forms.
604///
605/// HasTrailingLParen indicates whether this identifier is used in a
606/// function call context. LookupCtx is only used for a C++
607/// qualified-id (foo::bar) to indicate the class or namespace that
608/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000609///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000610/// isAddressOfOperand means that this expression is the direct operand
611/// of an address-of operator. This matters because this is the only
612/// situation where a qualified name referencing a non-static member may
613/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000614Sema::OwningExprResult
615Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
616 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000617 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000618 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000619 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000620 if (SS && SS->isInvalid())
621 return ExprError();
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000622
623 // C++ [temp.dep.expr]p3:
624 // An id-expression is type-dependent if it contains:
625 // -- a nested-name-specifier that contains a class-name that
626 // names a dependent type.
627 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000628 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
629 Loc, SS->getRange(),
Douglas Gregor041e9292009-03-26 23:56:24 +0000630 static_cast<NestedNameSpecifier *>(SS->getScopeRep())));
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000631 }
632
Douglas Gregor411889e2009-02-13 23:20:09 +0000633 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
634 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000635
Douglas Gregor09be81b2009-02-04 17:27:36 +0000636 NamedDecl *D = 0;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000637 if (Lookup.isAmbiguous()) {
638 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
639 SS && SS->isSet() ? SS->getRange()
640 : SourceRange());
641 return ExprError();
642 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000643 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000644
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000645 // If this reference is in an Objective-C method, then ivar lookup happens as
646 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000647 IdentifierInfo *II = Name.getAsIdentifierInfo();
648 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000649 // There are two cases to handle here. 1) scoped lookup could have failed,
650 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000651 // found a decl, but that decl is outside the current instance method (i.e.
652 // a global variable). In these two cases, we do a lookup for an ivar with
653 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000654 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000655 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000656 ObjCInterfaceDecl *ClassDeclared;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000657 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(Context, II,
658 ClassDeclared)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000659 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000660 if (DiagnoseUseOfDecl(IV, Loc))
661 return ExprError();
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000662 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
663 // If a class method attemps to use a free standing ivar, this is
664 // an error.
665 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
666 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
667 << IV->getDeclName());
668 // If a class method uses a global variable, even if an ivar with
669 // same name exists, use the global.
670 if (!IsClsMethod) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000671 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
672 ClassDeclared != IFace)
673 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000674 // FIXME: This should use a new expr for a direct reference, don't turn
675 // this into Self->ivar, just return a BareIVarExpr or something.
676 IdentifierInfo &II = Context.Idents.get("self");
677 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
678 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
679 Loc, static_cast<Expr*>(SelfExpr.release()),
680 true, true);
681 Context.setFieldDecl(IFace, IV, MRef);
682 return Owned(MRef);
683 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000684 }
685 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000686 else if (getCurMethodDecl()->isInstanceMethod()) {
687 // We should warn if a local variable hides an ivar.
688 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000689 ObjCInterfaceDecl *ClassDeclared;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000690 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(Context, II,
691 ClassDeclared)) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000692 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
693 IFace == ClassDeclared)
694 Diag(Loc, diag::warn_ivar_use_hidden)<<IV->getDeclName();
695 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000696 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000697 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000698 if (D == 0 && II->isStr("super")) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000699 QualType T;
700
701 if (getCurMethodDecl()->isInstanceMethod())
702 T = Context.getPointerType(Context.getObjCInterfaceType(
703 getCurMethodDecl()->getClassInterface()));
704 else
705 T = Context.getObjCClassType();
Steve Naroff774e4152009-01-21 00:14:39 +0000706 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000707 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000708 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000709
Douglas Gregoraa57e862009-02-18 21:56:37 +0000710 // Determine whether this name might be a candidate for
711 // argument-dependent lookup.
712 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
713 HasTrailingLParen;
714
715 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000716 // We've seen something of the form
717 //
718 // identifier(
719 //
720 // and we did not find any entity by the name
721 // "identifier". However, this identifier is still subject to
722 // argument-dependent lookup, so keep track of the name.
723 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
724 Context.OverloadTy,
725 Loc));
726 }
727
Chris Lattner4b009652007-07-25 00:24:17 +0000728 if (D == 0) {
729 // Otherwise, this could be an implicitly declared function reference (legal
730 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000731 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000732 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000733 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000734 else {
735 // If this name wasn't predeclared and if this is not a function call,
736 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000737 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000738 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
739 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000740 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
741 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000742 return ExprError(Diag(Loc, diag::err_undeclared_use)
743 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000744 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000745 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000746 }
747 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000748
Sebastian Redl0c9da212009-02-03 20:19:35 +0000749 // If this is an expression of the form &Class::member, don't build an
750 // implicit member ref, because we want a pointer to the member in general,
751 // not any specific instance's member.
752 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000753 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor09be81b2009-02-04 17:27:36 +0000754 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000755 QualType DType;
756 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
757 DType = FD->getType().getNonReferenceType();
758 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
759 DType = Method->getType();
760 } else if (isa<OverloadedFunctionDecl>(D)) {
761 DType = Context.OverloadTy;
762 }
763 // Could be an inner type. That's diagnosed below, so ignore it here.
764 if (!DType.isNull()) {
765 // The pointer is type- and value-dependent if it points into something
766 // dependent.
767 bool Dependent = false;
768 for (; DC; DC = DC->getParent()) {
769 // FIXME: could stop early at namespace scope.
770 if (DC->isRecord()) {
771 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
772 if (Context.getTypeDeclType(Record)->isDependentType()) {
773 Dependent = true;
774 break;
775 }
776 }
777 }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000778 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000779 }
780 }
781 }
782
Douglas Gregor723d3332009-01-07 00:43:41 +0000783 // We may have found a field within an anonymous union or struct
784 // (C++ [class.union]).
785 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
786 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
787 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000788
Douglas Gregor3257fb52008-12-22 05:46:06 +0000789 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
790 if (!MD->isStatic()) {
791 // C++ [class.mfct.nonstatic]p2:
792 // [...] if name lookup (3.4.1) resolves the name in the
793 // id-expression to a nonstatic nontype member of class X or of
794 // a base class of X, the id-expression is transformed into a
795 // class member access expression (5.2.5) using (*this) (9.3.2)
796 // as the postfix-expression to the left of the '.' operator.
797 DeclContext *Ctx = 0;
798 QualType MemberType;
799 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
800 Ctx = FD->getDeclContext();
801 MemberType = FD->getType();
802
803 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
804 MemberType = RefType->getPointeeType();
805 else if (!FD->isMutable()) {
806 unsigned combinedQualifiers
807 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
808 MemberType = MemberType.getQualifiedType(combinedQualifiers);
809 }
810 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
811 if (!Method->isStatic()) {
812 Ctx = Method->getParent();
813 MemberType = Method->getType();
814 }
815 } else if (OverloadedFunctionDecl *Ovl
816 = dyn_cast<OverloadedFunctionDecl>(D)) {
817 for (OverloadedFunctionDecl::function_iterator
818 Func = Ovl->function_begin(),
819 FuncEnd = Ovl->function_end();
820 Func != FuncEnd; ++Func) {
821 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
822 if (!DMethod->isStatic()) {
823 Ctx = Ovl->getDeclContext();
824 MemberType = Context.OverloadTy;
825 break;
826 }
827 }
828 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000829
830 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000831 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
832 QualType ThisType = Context.getTagDeclType(MD->getParent());
833 if ((Context.getCanonicalType(CtxType)
834 == Context.getCanonicalType(ThisType)) ||
835 IsDerivedFrom(ThisType, CtxType)) {
836 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000837 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000838 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +0000839 return Owned(new (Context) MemberExpr(This, true, D,
Mike Stump9afab102009-02-19 03:04:26 +0000840 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000841 }
842 }
843 }
844 }
845
Douglas Gregor8acb7272008-12-11 16:49:14 +0000846 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000847 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
848 if (MD->isStatic())
849 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000850 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
851 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000852 }
853
Douglas Gregor3257fb52008-12-22 05:46:06 +0000854 // Any other ways we could have found the field in a well-formed
855 // program would have been turned into implicit member expressions
856 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000857 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
858 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000859 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000860
Chris Lattner4b009652007-07-25 00:24:17 +0000861 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000862 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000863 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000864 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000865 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000866 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000867
Steve Naroffd6163f32008-09-05 22:11:13 +0000868 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000869 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000870 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
871 false, false, SS));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000872 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
873 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
874 false, false, SS));
Steve Naroffd6163f32008-09-05 22:11:13 +0000875 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000876
Douglas Gregoraa57e862009-02-18 21:56:37 +0000877 // Check whether this declaration can be used. Note that we suppress
878 // this check when we're going to perform argument-dependent lookup
879 // on this function name, because this might not be the function
880 // that overload resolution actually selects.
881 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
882 return ExprError();
883
Douglas Gregor48840c72008-12-10 23:01:14 +0000884 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000885 // Warn about constructs like:
886 // if (void *X = foo()) { ... } else { X }.
887 // In the else block, the pointer is always false.
Douglas Gregor48840c72008-12-10 23:01:14 +0000888 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
889 Scope *CheckS = S;
890 while (CheckS) {
891 if (CheckS->isWithinElse() &&
Chris Lattner5261d0c2009-03-28 19:18:32 +0000892 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
Douglas Gregor48840c72008-12-10 23:01:14 +0000893 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000894 ExprError(Diag(Loc, diag::warn_value_always_false)
895 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000896 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000897 ExprError(Diag(Loc, diag::warn_value_always_zero)
898 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000899 break;
900 }
901
902 // Move up one more control parent to check again.
903 CheckS = CheckS->getControlParent();
904 if (CheckS)
905 CheckS = CheckS->getParent();
906 }
907 }
Douglas Gregor1f88aa72009-02-25 16:33:18 +0000908 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(VD)) {
909 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
910 // C99 DR 316 says that, if a function type comes from a
911 // function definition (without a prototype), that type is only
912 // used for checking compatibility. Therefore, when referencing
913 // the function, we pretend that we don't have the full function
914 // type.
915 QualType T = Func->getType();
916 QualType NoProtoType = T;
Douglas Gregor4fa58902009-02-26 23:50:07 +0000917 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
918 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
Douglas Gregor1f88aa72009-02-25 16:33:18 +0000919 return Owned(BuildDeclRefExpr(VD, NoProtoType, Loc, false, false, SS));
920 }
Douglas Gregor48840c72008-12-10 23:01:14 +0000921 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000922
923 // Only create DeclRefExpr's for valid Decl's.
924 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000925 return ExprError();
926
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000927 // If the identifier reference is inside a block, and it refers to a value
928 // that is outside the block, create a BlockDeclRefExpr instead of a
929 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
930 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000931 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000932 // We do not do this for things like enum constants, global variables, etc,
933 // as they do not get snapshotted.
934 //
935 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Mike Stumpae93d652009-02-19 22:01:56 +0000936 // Blocks that have these can't be constant.
937 CurBlock->hasBlockDeclRefExprs = true;
938
Eli Friedman9c2b33f2009-03-22 23:00:19 +0000939 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff52059382008-10-10 01:28:17 +0000940 // The BlocksAttr indicates the variable is bound by-reference.
941 if (VD->getAttr<BlocksAttr>())
Eli Friedman9c2b33f2009-03-22 23:00:19 +0000942 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000943
Steve Naroff52059382008-10-10 01:28:17 +0000944 // Variable will be bound by-copy, make it const within the closure.
Eli Friedman9c2b33f2009-03-22 23:00:19 +0000945 ExprTy.addConst();
946 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000947 }
948 // If this reference is not in a block or if the referenced variable is
949 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000950
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000951 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000952 bool ValueDependent = false;
953 if (getLangOptions().CPlusPlus) {
954 // C++ [temp.dep.expr]p3:
955 // An id-expression is type-dependent if it contains:
956 // - an identifier that was declared with a dependent type,
957 if (VD->getType()->isDependentType())
958 TypeDependent = true;
959 // - FIXME: a template-id that is dependent,
960 // - a conversion-function-id that specifies a dependent type,
961 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
962 Name.getCXXNameType()->isDependentType())
963 TypeDependent = true;
964 // - a nested-name-specifier that contains a class-name that
965 // names a dependent type.
966 else if (SS && !SS->isEmpty()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000967 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregora5d84612008-12-10 20:57:37 +0000968 DC; DC = DC->getParent()) {
969 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000970 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000971 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
972 if (Context.getTypeDeclType(Record)->isDependentType()) {
973 TypeDependent = true;
974 break;
975 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000976 }
977 }
978 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000979
Douglas Gregora5d84612008-12-10 20:57:37 +0000980 // C++ [temp.dep.constexpr]p2:
981 //
982 // An identifier is value-dependent if it is:
983 // - a name declared with a dependent type,
984 if (TypeDependent)
985 ValueDependent = true;
986 // - the name of a non-type template parameter,
987 else if (isa<NonTypeTemplateParmDecl>(VD))
988 ValueDependent = true;
989 // - a constant with integral or enumeration type and is
990 // initialized with an expression that is value-dependent
991 // (FIXME!).
992 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000993
Sebastian Redlcd883f72009-01-18 18:53:16 +0000994 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
995 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000996}
997
Sebastian Redlcd883f72009-01-18 18:53:16 +0000998Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
999 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +00001000 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001001
Chris Lattner4b009652007-07-25 00:24:17 +00001002 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001003 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +00001004 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1005 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1006 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001007 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001008
Chris Lattner7e637512008-01-12 08:14:25 +00001009 // Pre-defined identifiers are of type char[x], where x is the length of the
1010 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001011 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +00001012 if (FunctionDecl *FD = getCurFunctionDecl())
1013 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +00001014 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1015 Length = MD->getSynthesizedMethodSize();
1016 else {
1017 Diag(Loc, diag::ext_predef_outside_function);
1018 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1019 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1020 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001021
1022
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001023 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001024 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001025 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +00001026 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +00001027}
1028
Sebastian Redlcd883f72009-01-18 18:53:16 +00001029Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +00001030 llvm::SmallString<16> CharBuffer;
1031 CharBuffer.resize(Tok.getLength());
1032 const char *ThisTokBegin = &CharBuffer[0];
1033 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001034
Chris Lattner4b009652007-07-25 00:24:17 +00001035 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1036 Tok.getLocation(), PP);
1037 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001038 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001039
1040 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1041
Sebastian Redl75324932009-01-20 22:23:13 +00001042 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1043 Literal.isWide(),
1044 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001045}
1046
Sebastian Redlcd883f72009-01-18 18:53:16 +00001047Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1048 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001049 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1050 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001051 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001052 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001053 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001054 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001055 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001056
Chris Lattner4b009652007-07-25 00:24:17 +00001057 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001058 // Add padding so that NumericLiteralParser can overread by one character.
1059 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001060 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001061
Chris Lattner4b009652007-07-25 00:24:17 +00001062 // Get the spelling of the token, which eliminates trigraphs, etc.
1063 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001064
Chris Lattner4b009652007-07-25 00:24:17 +00001065 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1066 Tok.getLocation(), PP);
1067 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001068 return ExprError();
1069
Chris Lattner1de66eb2007-08-26 03:42:43 +00001070 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001071
Chris Lattner1de66eb2007-08-26 03:42:43 +00001072 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001073 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001074 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001075 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001076 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001077 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001078 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001079 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001080
1081 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1082
Ted Kremenekddedbe22007-11-29 00:56:49 +00001083 // isExact will be set by GetFloatValue().
1084 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +00001085 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
1086 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001087
Chris Lattner1de66eb2007-08-26 03:42:43 +00001088 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001089 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001090 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001091 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001092
Neil Booth7421e9c2007-08-29 22:00:19 +00001093 // long long is a C99 feature.
1094 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001095 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001096 Diag(Tok.getLocation(), diag::ext_longlong);
1097
Chris Lattner4b009652007-07-25 00:24:17 +00001098 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001099 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001100
Chris Lattner4b009652007-07-25 00:24:17 +00001101 if (Literal.GetIntegerValue(ResultVal)) {
1102 // If this value didn't fit into uintmax_t, warn and force to ull.
1103 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001104 Ty = Context.UnsignedLongLongTy;
1105 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001106 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001107 } else {
1108 // If this value fits into a ULL, try to figure out what else it fits into
1109 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001110
Chris Lattner4b009652007-07-25 00:24:17 +00001111 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1112 // be an unsigned int.
1113 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1114
1115 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001116 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001117 if (!Literal.isLong && !Literal.isLongLong) {
1118 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001119 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001120
Chris Lattner4b009652007-07-25 00:24:17 +00001121 // Does it fit in a unsigned int?
1122 if (ResultVal.isIntN(IntSize)) {
1123 // Does it fit in a signed int?
1124 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001125 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001126 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001127 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001128 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001129 }
Chris Lattner4b009652007-07-25 00:24:17 +00001130 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001131
Chris Lattner4b009652007-07-25 00:24:17 +00001132 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001133 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001134 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001135
Chris Lattner4b009652007-07-25 00:24:17 +00001136 // Does it fit in a unsigned long?
1137 if (ResultVal.isIntN(LongSize)) {
1138 // Does it fit in a signed long?
1139 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001140 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001141 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001142 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001143 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001144 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001145 }
1146
Chris Lattner4b009652007-07-25 00:24:17 +00001147 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001148 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001149 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001150
Chris Lattner4b009652007-07-25 00:24:17 +00001151 // Does it fit in a unsigned long long?
1152 if (ResultVal.isIntN(LongLongSize)) {
1153 // Does it fit in a signed long long?
1154 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001155 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001156 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001157 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001158 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001159 }
1160 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001161
Chris Lattner4b009652007-07-25 00:24:17 +00001162 // If we still couldn't decide a type, we probably have something that
1163 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001164 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001165 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001166 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001167 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001168 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001169
Chris Lattnere4068872008-05-09 05:59:00 +00001170 if (ResultVal.getBitWidth() != Width)
1171 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001172 }
Sebastian Redl75324932009-01-20 22:23:13 +00001173 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001174 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001175
Chris Lattner1de66eb2007-08-26 03:42:43 +00001176 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1177 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001178 Res = new (Context) ImaginaryLiteral(Res,
1179 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001180
1181 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001182}
1183
Sebastian Redlcd883f72009-01-18 18:53:16 +00001184Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1185 SourceLocation R, ExprArg Val) {
1186 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001187 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001188 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001189}
1190
1191/// The UsualUnaryConversions() function is *not* called by this routine.
1192/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001193bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001194 SourceLocation OpLoc,
1195 const SourceRange &ExprRange,
1196 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001197 if (exprType->isDependentType())
1198 return false;
1199
Chris Lattner4b009652007-07-25 00:24:17 +00001200 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001201 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001202 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001203 if (isSizeof)
1204 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1205 return false;
1206 }
1207
1208 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001209 Diag(OpLoc, diag::ext_sizeof_void_type)
1210 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001211 return false;
1212 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001213
Douglas Gregorc84d8932009-03-09 16:13:40 +00001214 return RequireCompleteType(OpLoc, exprType,
Chris Lattner159fe082009-01-24 19:46:37 +00001215 isSizeof ? diag::err_sizeof_incomplete_type :
1216 diag::err_alignof_incomplete_type,
1217 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001218}
1219
Chris Lattner8d9f7962009-01-24 20:17:12 +00001220bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1221 const SourceRange &ExprRange) {
1222 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001223
Chris Lattner8d9f7962009-01-24 20:17:12 +00001224 // alignof decl is always ok.
1225 if (isa<DeclRefExpr>(E))
1226 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001227
1228 // Cannot know anything else if the expression is dependent.
1229 if (E->isTypeDependent())
1230 return false;
1231
Chris Lattner8d9f7962009-01-24 20:17:12 +00001232 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1233 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1234 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001235 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001236 return true;
1237 }
1238 // Other fields are ok.
1239 return false;
1240 }
1241 }
1242 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1243}
1244
Douglas Gregor396f1142009-03-13 21:01:28 +00001245/// \brief Build a sizeof or alignof expression given a type operand.
1246Action::OwningExprResult
1247Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1248 bool isSizeOf, SourceRange R) {
1249 if (T.isNull())
1250 return ExprError();
1251
1252 if (!T->isDependentType() &&
1253 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1254 return ExprError();
1255
1256 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1257 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1258 Context.getSizeType(), OpLoc,
1259 R.getEnd()));
1260}
1261
1262/// \brief Build a sizeof or alignof expression given an expression
1263/// operand.
1264Action::OwningExprResult
1265Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1266 bool isSizeOf, SourceRange R) {
1267 // Verify that the operand is valid.
1268 bool isInvalid = false;
1269 if (E->isTypeDependent()) {
1270 // Delay type-checking for type-dependent expressions.
1271 } else if (!isSizeOf) {
1272 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
1273 } else if (E->isBitField()) { // C99 6.5.3.4p1.
1274 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1275 isInvalid = true;
1276 } else {
1277 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1278 }
1279
1280 if (isInvalid)
1281 return ExprError();
1282
1283 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1284 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1285 Context.getSizeType(), OpLoc,
1286 R.getEnd()));
1287}
1288
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001289/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1290/// the same for @c alignof and @c __alignof
1291/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001292Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001293Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1294 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001295 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001296 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001297
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001298 if (isType) {
Douglas Gregor396f1142009-03-13 21:01:28 +00001299 QualType ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1300 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1301 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001302
Douglas Gregor396f1142009-03-13 21:01:28 +00001303 // Get the end location.
1304 Expr *ArgEx = (Expr *)TyOrEx;
1305 Action::OwningExprResult Result
1306 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1307
1308 if (Result.isInvalid())
1309 DeleteExpr(ArgEx);
1310
1311 return move(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001312}
1313
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001314QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001315 if (V->isTypeDependent())
1316 return Context.DependentTy;
1317
Chris Lattner03931a72007-08-24 21:16:53 +00001318 DefaultFunctionArrayConversion(V);
1319
Chris Lattnera16e42d2007-08-26 05:39:26 +00001320 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001321 if (const ComplexType *CT = V->getType()->getAsComplexType())
1322 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001323
1324 // Otherwise they pass through real integer and floating point types here.
1325 if (V->getType()->isArithmeticType())
1326 return V->getType();
1327
1328 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001329 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1330 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001331 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001332}
1333
1334
Chris Lattner4b009652007-07-25 00:24:17 +00001335
Sebastian Redl8b769972009-01-19 00:08:26 +00001336Action::OwningExprResult
1337Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1338 tok::TokenKind Kind, ExprArg Input) {
1339 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001340
Chris Lattner4b009652007-07-25 00:24:17 +00001341 UnaryOperator::Opcode Opc;
1342 switch (Kind) {
1343 default: assert(0 && "Unknown unary op!");
1344 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1345 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1346 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001347
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001348 if (getLangOptions().CPlusPlus &&
1349 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1350 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001351 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001352 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1353
1354 // C++ [over.inc]p1:
1355 //
1356 // [...] If the function is a member function with one
1357 // parameter (which shall be of type int) or a non-member
1358 // function with two parameters (the second of which shall be
1359 // of type int), it defines the postfix increment operator ++
1360 // for objects of that type. When the postfix increment is
1361 // called as a result of using the ++ operator, the int
1362 // argument will have value zero.
1363 Expr *Args[2] = {
1364 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001365 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1366 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001367 };
1368
1369 // Build the candidate set for overloading
1370 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001371 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001372
1373 // Perform overload resolution.
1374 OverloadCandidateSet::iterator Best;
1375 switch (BestViableFunction(CandidateSet, Best)) {
1376 case OR_Success: {
1377 // We found a built-in operator or an overloaded operator.
1378 FunctionDecl *FnDecl = Best->Function;
1379
1380 if (FnDecl) {
1381 // We matched an overloaded operator. Build a call to that
1382 // operator.
1383
1384 // Convert the arguments.
1385 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1386 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001387 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001388 } else {
1389 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001390 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001391 FnDecl->getParamDecl(0)->getType(),
1392 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001393 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001394 }
1395
1396 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001397 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001398 = FnDecl->getType()->getAsFunctionType()->getResultType();
1399 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001400
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001401 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001402 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001403 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001404 UsualUnaryConversions(FnExpr);
1405
Sebastian Redl8b769972009-01-19 00:08:26 +00001406 Input.release();
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001407 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1408 Args, 2, ResultTy,
1409 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001410 } else {
1411 // We matched a built-in operator. Convert the arguments, then
1412 // break out so that we will build the appropriate built-in
1413 // operator node.
1414 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1415 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001416 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001417
1418 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001419 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001420 }
1421
1422 case OR_No_Viable_Function:
1423 // No viable function; fall through to handling this as a
1424 // built-in operator, which will produce an error message for us.
1425 break;
1426
1427 case OR_Ambiguous:
1428 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1429 << UnaryOperator::getOpcodeStr(Opc)
1430 << Arg->getSourceRange();
1431 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001432 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001433
1434 case OR_Deleted:
1435 Diag(OpLoc, diag::err_ovl_deleted_oper)
1436 << Best->Function->isDeleted()
1437 << UnaryOperator::getOpcodeStr(Opc)
1438 << Arg->getSourceRange();
1439 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1440 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001441 }
1442
1443 // Either we found no viable overloaded operator or we matched a
1444 // built-in operator. In either case, fall through to trying to
1445 // build a built-in operation.
1446 }
1447
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001448 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1449 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001450 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001451 return ExprError();
1452 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001453 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001454}
1455
Sebastian Redl8b769972009-01-19 00:08:26 +00001456Action::OwningExprResult
1457Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1458 ExprArg Idx, SourceLocation RLoc) {
1459 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1460 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001461
Douglas Gregor80723c52008-11-19 17:17:41 +00001462 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001463 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001464 LHSExp->getType()->isEnumeralType() ||
1465 RHSExp->getType()->isRecordType() ||
1466 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001467 // Add the appropriate overloaded operators (C++ [over.match.oper])
1468 // to the candidate set.
1469 OverloadCandidateSet CandidateSet;
1470 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001471 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1472 SourceRange(LLoc, RLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001473
Douglas Gregor80723c52008-11-19 17:17:41 +00001474 // Perform overload resolution.
1475 OverloadCandidateSet::iterator Best;
1476 switch (BestViableFunction(CandidateSet, Best)) {
1477 case OR_Success: {
1478 // We found a built-in operator or an overloaded operator.
1479 FunctionDecl *FnDecl = Best->Function;
1480
1481 if (FnDecl) {
1482 // We matched an overloaded operator. Build a call to that
1483 // operator.
1484
1485 // Convert the arguments.
1486 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1487 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1488 PerformCopyInitialization(RHSExp,
1489 FnDecl->getParamDecl(0)->getType(),
1490 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001491 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001492 } else {
1493 // Convert the arguments.
1494 if (PerformCopyInitialization(LHSExp,
1495 FnDecl->getParamDecl(0)->getType(),
1496 "passing") ||
1497 PerformCopyInitialization(RHSExp,
1498 FnDecl->getParamDecl(1)->getType(),
1499 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001500 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001501 }
1502
1503 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001504 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001505 = FnDecl->getType()->getAsFunctionType()->getResultType();
1506 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001507
Douglas Gregor80723c52008-11-19 17:17:41 +00001508 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001509 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1510 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001511 UsualUnaryConversions(FnExpr);
1512
Sebastian Redl8b769972009-01-19 00:08:26 +00001513 Base.release();
1514 Idx.release();
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001515 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1516 FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001517 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001518 } else {
1519 // We matched a built-in operator. Convert the arguments, then
1520 // break out so that we will build the appropriate built-in
1521 // operator node.
1522 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1523 "passing") ||
1524 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1525 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001526 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001527
1528 break;
1529 }
1530 }
1531
1532 case OR_No_Viable_Function:
1533 // No viable function; fall through to handling this as a
1534 // built-in operator, which will produce an error message for us.
1535 break;
1536
1537 case OR_Ambiguous:
1538 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1539 << "[]"
1540 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1541 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001542 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001543
1544 case OR_Deleted:
1545 Diag(LLoc, diag::err_ovl_deleted_oper)
1546 << Best->Function->isDeleted()
1547 << "[]"
1548 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1549 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1550 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001551 }
1552
1553 // Either we found no viable overloaded operator or we matched a
1554 // built-in operator. In either case, fall through to trying to
1555 // build a built-in operation.
1556 }
1557
Chris Lattner4b009652007-07-25 00:24:17 +00001558 // Perform default conversions.
1559 DefaultFunctionArrayConversion(LHSExp);
1560 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001561
Chris Lattner4b009652007-07-25 00:24:17 +00001562 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1563
1564 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001565 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001566 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001567 // and index from the expression types.
1568 Expr *BaseExpr, *IndexExpr;
1569 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001570 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1571 BaseExpr = LHSExp;
1572 IndexExpr = RHSExp;
1573 ResultType = Context.DependentTy;
1574 } else if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001575 BaseExpr = LHSExp;
1576 IndexExpr = RHSExp;
1577 // FIXME: need to deal with const...
1578 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001579 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001580 // Handle the uncommon case of "123[Ptr]".
1581 BaseExpr = RHSExp;
1582 IndexExpr = LHSExp;
1583 // FIXME: need to deal with const...
1584 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001585 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1586 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001587 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001588
Chris Lattner4b009652007-07-25 00:24:17 +00001589 // FIXME: need to deal with const...
1590 ResultType = VTy->getElementType();
1591 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001592 return ExprError(Diag(LHSExp->getLocStart(),
1593 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1594 }
Chris Lattner4b009652007-07-25 00:24:17 +00001595 // C99 6.5.2.1p1
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001596 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Sebastian Redl8b769972009-01-19 00:08:26 +00001597 return ExprError(Diag(IndexExpr->getLocStart(),
1598 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001599
Douglas Gregor05e28f62009-03-24 19:52:54 +00001600 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1601 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1602 // type. Note that Functions are not objects, and that (in C99 parlance)
1603 // incomplete types are not object types.
1604 if (ResultType->isFunctionType()) {
1605 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1606 << ResultType << BaseExpr->getSourceRange();
1607 return ExprError();
1608 }
1609 if (!ResultType->isDependentType() &&
1610 RequireCompleteType(BaseExpr->getLocStart(), ResultType,
1611 diag::err_subscript_incomplete_type,
1612 BaseExpr->getSourceRange()))
1613 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001614
Sebastian Redl8b769972009-01-19 00:08:26 +00001615 Base.release();
1616 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001617 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001618 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001619}
1620
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001621QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001622CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001623 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001624 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001625
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001626 // The vector accessor can't exceed the number of elements.
1627 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001628
Mike Stump9afab102009-02-19 03:04:26 +00001629 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001630 // special names that indicate a subset of exactly half the elements are
1631 // to be selected.
1632 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001633
Nate Begeman1486b502009-01-18 01:47:54 +00001634 // This flag determines whether or not CompName has an 's' char prefix,
1635 // indicating that it is a string of hex values to be used as vector indices.
1636 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001637
1638 // Check that we've found one of the special components, or that the component
1639 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001640 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001641 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1642 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001643 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001644 do
1645 compStr++;
1646 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001647 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001648 do
1649 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001650 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001651 }
Nate Begeman1486b502009-01-18 01:47:54 +00001652
Mike Stump9afab102009-02-19 03:04:26 +00001653 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001654 // We didn't get to the end of the string. This means the component names
1655 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001656 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1657 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001658 return QualType();
1659 }
Mike Stump9afab102009-02-19 03:04:26 +00001660
Nate Begeman1486b502009-01-18 01:47:54 +00001661 // Ensure no component accessor exceeds the width of the vector type it
1662 // operates on.
1663 if (!HalvingSwizzle) {
1664 compStr = CompName.getName();
1665
1666 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001667 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001668
1669 while (*compStr) {
1670 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1671 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1672 << baseType << SourceRange(CompLoc);
1673 return QualType();
1674 }
1675 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001676 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001677
Nate Begeman1486b502009-01-18 01:47:54 +00001678 // If this is a halving swizzle, verify that the base type has an even
1679 // number of elements.
1680 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001681 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001682 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001683 return QualType();
1684 }
Mike Stump9afab102009-02-19 03:04:26 +00001685
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001686 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001687 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001688 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001689 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001690 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001691 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1692 : CompName.getLength();
1693 if (HexSwizzle)
1694 CompSize--;
1695
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001696 if (CompSize == 1)
1697 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001698
Nate Begemanaf6ed502008-04-18 23:10:10 +00001699 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001700 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001701 // diagostics look bad. We want extended vector types to appear built-in.
1702 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1703 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1704 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001705 }
1706 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001707}
1708
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001709static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
1710 IdentifierInfo &Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001711 const Selector &Sel,
1712 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001713
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001714 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Context, &Member))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001715 return PD;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001716 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Context, Sel))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001717 return OMD;
1718
1719 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1720 E = PDecl->protocol_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001721 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
1722 Context))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001723 return D;
1724 }
1725 return 0;
1726}
1727
1728static Decl *FindGetterNameDecl(const ObjCQualifiedIdType *QIdTy,
1729 IdentifierInfo &Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001730 const Selector &Sel,
1731 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001732 // Check protocols on qualified interfaces.
1733 Decl *GDecl = 0;
1734 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1735 E = QIdTy->qual_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001736 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Context, &Member)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001737 GDecl = PD;
1738 break;
1739 }
1740 // Also must look for a getter name which uses property syntax.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001741 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Context, Sel)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001742 GDecl = OMD;
1743 break;
1744 }
1745 }
1746 if (!GDecl) {
1747 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1748 E = QIdTy->qual_end(); I != E; ++I) {
1749 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001750 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001751 if (GDecl)
1752 return GDecl;
1753 }
1754 }
1755 return GDecl;
1756}
Chris Lattner2cb744b2009-02-15 22:43:40 +00001757
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001758/// FindMethodInNestedImplementations - Look up a method in current and
1759/// all base class implementations.
1760///
1761ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
1762 const ObjCInterfaceDecl *IFace,
1763 const Selector &Sel) {
1764 ObjCMethodDecl *Method = 0;
1765 if (ObjCImplementationDecl *ImpDecl =
1766 Sema::ObjCImplementations[IFace->getIdentifier()])
1767 Method = ImpDecl->getInstanceMethod(Sel);
1768
1769 if (!Method && IFace->getSuperClass())
1770 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
1771 return Method;
1772}
1773
Sebastian Redl8b769972009-01-19 00:08:26 +00001774Action::OwningExprResult
1775Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1776 tok::TokenKind OpKind, SourceLocation MemberLoc,
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00001777 IdentifierInfo &Member,
Chris Lattner5261d0c2009-03-28 19:18:32 +00001778 DeclPtrTy ObjCImpDecl) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001779 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001780 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001781
1782 // Perform default conversions.
1783 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001784
Steve Naroff2cb66382007-07-26 03:11:44 +00001785 QualType BaseType = BaseExpr->getType();
1786 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001787
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001788 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1789 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001790 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001791 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001792 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001793 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001794 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1795 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001796 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001797 return ExprError(Diag(MemberLoc,
1798 diag::err_typecheck_member_reference_arrow)
1799 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001800 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001801
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001802 // Handle field access to simple records. This also handles access to fields
1803 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001804 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001805 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorc84d8932009-03-09 16:13:40 +00001806 if (RequireCompleteType(OpLoc, BaseType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001807 diag::err_typecheck_incomplete_tag,
1808 BaseExpr->getSourceRange()))
1809 return ExprError();
1810
Steve Naroff2cb66382007-07-26 03:11:44 +00001811 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001812 // FIXME: Qualified name lookup for C++ is a bit more complicated
1813 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001814 LookupResult Result
Mike Stump9afab102009-02-19 03:04:26 +00001815 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001816 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001817
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001818 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001819 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1820 << &Member << BaseExpr->getSourceRange());
Chris Lattner84ad8332009-03-31 08:18:48 +00001821 if (Result.isAmbiguous()) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001822 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1823 MemberLoc, BaseExpr->getSourceRange());
1824 return ExprError();
Chris Lattner84ad8332009-03-31 08:18:48 +00001825 }
1826
1827 NamedDecl *MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001828
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001829 // If the decl being referenced had an error, return an error for this
1830 // sub-expr without emitting another error, in order to avoid cascading
1831 // error cases.
1832 if (MemberDecl->isInvalidDecl())
1833 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001834
Douglas Gregoraa57e862009-02-18 21:56:37 +00001835 // Check the use of this field
1836 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1837 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001838
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001839 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001840 // We may have found a field within an anonymous union or struct
1841 // (C++ [class.union]).
1842 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001843 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001844 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001845
Douglas Gregor82d44772008-12-20 23:49:58 +00001846 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1847 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001848 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001849 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1850 MemberType = Ref->getPointeeType();
1851 else {
1852 unsigned combinedQualifiers =
1853 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001854 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001855 combinedQualifiers &= ~QualType::Const;
1856 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1857 }
Eli Friedman76b49832008-02-06 22:48:16 +00001858
Steve Naroff774e4152009-01-21 00:14:39 +00001859 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1860 MemberLoc, MemberType));
Chris Lattner84ad8332009-03-31 08:18:48 +00001861 }
1862
1863 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001864 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Chris Lattner84ad8332009-03-31 08:18:48 +00001865 Var, MemberLoc,
1866 Var->getType().getNonReferenceType()));
1867 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00001868 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Chris Lattner84ad8332009-03-31 08:18:48 +00001869 MemberFn, MemberLoc,
1870 MemberFn->getType()));
1871 if (OverloadedFunctionDecl *Ovl
1872 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001873 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Chris Lattner84ad8332009-03-31 08:18:48 +00001874 MemberLoc, Context.OverloadTy));
1875 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00001876 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1877 Enum, MemberLoc, Enum->getType()));
Chris Lattner84ad8332009-03-31 08:18:48 +00001878 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001879 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1880 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001881
Douglas Gregor82d44772008-12-20 23:49:58 +00001882 // We found a declaration kind that we didn't expect. This is a
1883 // generic error message that tells the user that she can't refer
1884 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001885 return ExprError(Diag(MemberLoc,
1886 diag::err_typecheck_member_reference_unknown)
1887 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001888 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001889
Chris Lattnere9d71612008-07-21 04:59:05 +00001890 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1891 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001892 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00001893 ObjCInterfaceDecl *ClassDeclared;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001894 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(Context,
1895 &Member,
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00001896 ClassDeclared)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001897 // If the decl being referenced had an error, return an error for this
1898 // sub-expr without emitting another error, in order to avoid cascading
1899 // error cases.
1900 if (IV->isInvalidDecl())
1901 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001902
1903 // Check whether we can reference this field.
1904 if (DiagnoseUseOfDecl(IV, MemberLoc))
1905 return ExprError();
Steve Naroff8c56ee02009-03-26 16:01:08 +00001906 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1907 IV->getAccessControl() != ObjCIvarDecl::Package) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00001908 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1909 if (ObjCMethodDecl *MD = getCurMethodDecl())
1910 ClassOfMethodDecl = MD->getClassInterface();
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00001911 else if (ObjCImpDecl && getCurFunctionDecl()) {
1912 // Case of a c-function declared inside an objc implementation.
1913 // FIXME: For a c-style function nested inside an objc implementation
1914 // class, there is no implementation context available, so we pass down
1915 // the context as argument to this routine. Ideally, this context need
1916 // be passed down in the AST node and somehow calculated from the AST
1917 // for a function decl.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001918 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00001919 if (ObjCImplementationDecl *IMPD =
1920 dyn_cast<ObjCImplementationDecl>(ImplDecl))
1921 ClassOfMethodDecl = IMPD->getClassInterface();
1922 else if (ObjCCategoryImplDecl* CatImplClass =
1923 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
1924 ClassOfMethodDecl = CatImplClass->getClassInterface();
Steve Narofff9606572009-03-04 18:34:24 +00001925 }
Chris Lattner84ad8332009-03-31 08:18:48 +00001926
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00001927 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00001928 if (ClassDeclared != IFTy->getDecl() ||
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00001929 ClassOfMethodDecl != ClassDeclared)
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00001930 Diag(MemberLoc, diag::error_private_ivar_access) << IV->getDeclName();
1931 }
1932 // @protected
1933 else if (!IFTy->getDecl()->isSuperClassOf(ClassOfMethodDecl))
1934 Diag(MemberLoc, diag::error_protected_ivar_access) << IV->getDeclName();
1935 }
Mike Stump9afab102009-02-19 03:04:26 +00001936
1937 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +00001938 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001939 OpKind == tok::arrow);
1940 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001941 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001942 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001943 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1944 << IFTy->getDecl()->getDeclName() << &Member
1945 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001946 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001947
Chris Lattnere9d71612008-07-21 04:59:05 +00001948 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1949 // pointer to a (potentially qualified) interface type.
1950 const PointerType *PTy;
1951 const ObjCInterfaceType *IFTy;
1952 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1953 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1954 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001955
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001956 // Search for a declared property first.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001957 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Context,
1958 &Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001959 // Check whether we can reference this property.
1960 if (DiagnoseUseOfDecl(PD, MemberLoc))
1961 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001962
Steve Naroff774e4152009-01-21 00:14:39 +00001963 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001964 MemberLoc, BaseExpr));
1965 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001966
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001967 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001968 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1969 E = IFTy->qual_end(); I != E; ++I)
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001970 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Context,
1971 &Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001972 // Check whether we can reference this property.
1973 if (DiagnoseUseOfDecl(PD, MemberLoc))
1974 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001975
Steve Naroff774e4152009-01-21 00:14:39 +00001976 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001977 MemberLoc, BaseExpr));
1978 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001979
1980 // If that failed, look for an "implicit" property by seeing if the nullary
1981 // selector is implemented.
1982
1983 // FIXME: The logic for looking up nullary and unary selectors should be
1984 // shared with the code in ActOnInstanceMessage.
1985
1986 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001987 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Context, Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001988
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001989 // If this reference is in an @implementation, check for 'private' methods.
1990 if (!Getter)
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001991 Getter = FindMethodInNestedImplementations(IFace, Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001992
Steve Naroff04151f32008-10-22 19:16:27 +00001993 // Look through local category implementations associated with the class.
1994 if (!Getter) {
1995 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1996 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1997 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1998 }
1999 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002000 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002001 // Check if we can reference this property.
2002 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2003 return ExprError();
Steve Naroffdede0c92009-03-11 13:48:17 +00002004 }
2005 // If we found a getter then this may be a valid dot-reference, we
2006 // will look for the matching setter, in case it is needed.
2007 Selector SetterSel =
2008 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2009 PP.getSelectorTable(), &Member);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002010 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(Context, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002011 if (!Setter) {
2012 // If this reference is in an @implementation, also check for 'private'
2013 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002014 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002015 }
2016 // Look through local category implementations associated with the class.
2017 if (!Setter) {
2018 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
2019 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
2020 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
Fariborz Jahanianc05da422008-11-22 20:25:50 +00002021 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002022 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002023
Steve Naroffdede0c92009-03-11 13:48:17 +00002024 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2025 return ExprError();
2026
2027 if (Getter || Setter) {
2028 QualType PType;
2029
2030 if (Getter)
2031 PType = Getter->getResultType();
2032 else {
2033 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2034 E = Setter->param_end(); PI != E; ++PI)
2035 PType = (*PI)->getType();
2036 }
2037 // FIXME: we must check that the setter has property type.
2038 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2039 Setter, MemberLoc, BaseExpr));
2040 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002041 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2042 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00002043 }
Steve Naroffd1d44402008-10-20 22:53:06 +00002044 // Handle properties on qualified "id" protocols.
2045 const ObjCQualifiedIdType *QIdTy;
2046 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
2047 // Check protocols on qualified interfaces.
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002048 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002049 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002050 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002051 // Check the use of this declaration
2052 if (DiagnoseUseOfDecl(PD, MemberLoc))
2053 return ExprError();
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002054
Steve Naroff774e4152009-01-21 00:14:39 +00002055 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002056 MemberLoc, BaseExpr));
2057 }
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002058 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002059 // Check the use of this method.
2060 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2061 return ExprError();
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002062
Mike Stump9afab102009-02-19 03:04:26 +00002063 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002064 OMD->getResultType(),
2065 OMD, OpLoc, MemberLoc,
2066 NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00002067 }
2068 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002069
2070 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2071 << &Member << BaseType);
Mike Stump9afab102009-02-19 03:04:26 +00002072 }
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002073 // Handle properties on ObjC 'Class' types.
2074 if (OpKind == tok::period && (BaseType == Context.getObjCClassType())) {
2075 // Also must look for a getter name which uses property syntax.
2076 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2077 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002078 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2079 ObjCMethodDecl *Getter;
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002080 // FIXME: need to also look locally in the implementation.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002081 if ((Getter = IFace->lookupClassMethod(Context, Sel))) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002082 // Check the use of this method.
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002083 if (DiagnoseUseOfDecl(Getter, MemberLoc))
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002084 return ExprError();
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002085 }
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002086 // If we found a getter then this may be a valid dot-reference, we
2087 // will look for the matching setter, in case it is needed.
2088 Selector SetterSel =
2089 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2090 PP.getSelectorTable(), &Member);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002091 ObjCMethodDecl *Setter = IFace->lookupClassMethod(Context, SetterSel);
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002092 if (!Setter) {
2093 // If this reference is in an @implementation, also check for 'private'
2094 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002095 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002096 }
2097 // Look through local category implementations associated with the class.
2098 if (!Setter) {
2099 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
2100 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
2101 Setter = ObjCCategoryImpls[i]->getClassMethod(SetterSel);
2102 }
2103 }
2104
2105 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2106 return ExprError();
2107
2108 if (Getter || Setter) {
2109 QualType PType;
2110
2111 if (Getter)
2112 PType = Getter->getResultType();
2113 else {
2114 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2115 E = Setter->param_end(); PI != E; ++PI)
2116 PType = (*PI)->getType();
2117 }
2118 // FIXME: we must check that the setter has property type.
2119 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2120 Setter, MemberLoc, BaseExpr));
2121 }
2122 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2123 << &Member << BaseType);
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002124 }
2125 }
2126
Chris Lattnera57cf472008-07-21 04:28:12 +00002127 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00002128 if (BaseType->isExtVectorType()) {
Chris Lattnera57cf472008-07-21 04:28:12 +00002129 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2130 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00002131 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002132 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
Steve Naroff774e4152009-01-21 00:14:39 +00002133 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00002134 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002135
Douglas Gregor762da552009-03-27 06:00:30 +00002136 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2137 << BaseType << BaseExpr->getSourceRange();
2138
2139 // If the user is trying to apply -> or . to a function or function
2140 // pointer, it's probably because they forgot parentheses to call
2141 // the function. Suggest the addition of those parentheses.
2142 if (BaseType == Context.OverloadTy ||
2143 BaseType->isFunctionType() ||
2144 (BaseType->isPointerType() &&
2145 BaseType->getAsPointerType()->isFunctionType())) {
2146 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2147 Diag(Loc, diag::note_member_reference_needs_call)
2148 << CodeModificationHint::CreateInsertion(Loc, "()");
2149 }
2150
2151 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00002152}
2153
Douglas Gregor3257fb52008-12-22 05:46:06 +00002154/// ConvertArgumentsForCall - Converts the arguments specified in
2155/// Args/NumArgs to the parameter types of the function FDecl with
2156/// function prototype Proto. Call is the call expression itself, and
2157/// Fn is the function expression. For a C++ member function, this
2158/// routine does not attempt to convert the object argument. Returns
2159/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00002160bool
2161Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002162 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002163 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002164 Expr **Args, unsigned NumArgs,
2165 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00002166 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00002167 // assignment, to the types of the corresponding parameter, ...
2168 unsigned NumArgsInProto = Proto->getNumArgs();
2169 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002170 bool Invalid = false;
2171
Douglas Gregor3257fb52008-12-22 05:46:06 +00002172 // If too few arguments are available (and we don't have default
2173 // arguments for the remaining parameters), don't make the call.
2174 if (NumArgs < NumArgsInProto) {
2175 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2176 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2177 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2178 // Use default arguments for missing arguments
2179 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00002180 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002181 }
2182
2183 // If too many are passed and not variadic, error on the extras and drop
2184 // them.
2185 if (NumArgs > NumArgsInProto) {
2186 if (!Proto->isVariadic()) {
2187 Diag(Args[NumArgsInProto]->getLocStart(),
2188 diag::err_typecheck_call_too_many_args)
2189 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2190 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2191 Args[NumArgs-1]->getLocEnd());
2192 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002193 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002194 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002195 }
2196 NumArgsToCheck = NumArgsInProto;
2197 }
Mike Stump9afab102009-02-19 03:04:26 +00002198
Douglas Gregor3257fb52008-12-22 05:46:06 +00002199 // Continue to check argument types (even if we have too few/many args).
2200 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2201 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00002202
Douglas Gregor3257fb52008-12-22 05:46:06 +00002203 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002204 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002205 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002206
Eli Friedman83dec9e2009-03-22 22:00:50 +00002207 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2208 ProtoArgType,
2209 diag::err_call_incomplete_argument,
2210 Arg->getSourceRange()))
2211 return true;
2212
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002213 // Pass the argument.
2214 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2215 return true;
Mike Stump9afab102009-02-19 03:04:26 +00002216 } else
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002217 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00002218 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002219 QualType ArgType = Arg->getType();
Mike Stump9afab102009-02-19 03:04:26 +00002220
Douglas Gregor3257fb52008-12-22 05:46:06 +00002221 Call->setArg(i, Arg);
2222 }
Mike Stump9afab102009-02-19 03:04:26 +00002223
Douglas Gregor3257fb52008-12-22 05:46:06 +00002224 // If this is a variadic call, handle args passed through "...".
2225 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002226 VariadicCallType CallType = VariadicFunction;
2227 if (Fn->getType()->isBlockPointerType())
2228 CallType = VariadicBlock; // Block
2229 else if (isa<MemberExpr>(Fn))
2230 CallType = VariadicMethod;
2231
Douglas Gregor3257fb52008-12-22 05:46:06 +00002232 // Promote the arguments (C99 6.5.2.2p7).
2233 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2234 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00002235 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002236 Call->setArg(i, Arg);
2237 }
2238 }
2239
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002240 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002241}
2242
Steve Naroff87d58b42007-09-16 03:34:24 +00002243/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002244/// This provides the location of the left/right parens and a list of comma
2245/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002246Action::OwningExprResult
2247Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2248 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002249 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002250 unsigned NumArgs = args.size();
2251 Expr *Fn = static_cast<Expr *>(fn.release());
2252 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002253 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002254 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002255 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002256
Douglas Gregor3257fb52008-12-22 05:46:06 +00002257 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002258 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002259 // in which case we won't do any semantic analysis now.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002260 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
2261 bool Dependent = false;
2262 if (Fn->isTypeDependent())
2263 Dependent = true;
2264 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2265 Dependent = true;
2266
2267 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002268 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002269 Context.DependentTy, RParenLoc));
2270
2271 // Determine whether this is a call to an object (C++ [over.call.object]).
2272 if (Fn->getType()->isRecordType())
2273 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2274 CommaLocs, RParenLoc));
2275
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002276 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002277 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
2278 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
2279 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00002280 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2281 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002282 }
2283
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002284 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00002285 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002286 Expr *FnExpr = Fn;
2287 bool ADL = true;
2288 while (true) {
2289 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2290 FnExpr = IcExpr->getSubExpr();
2291 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002292 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002293 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002294 ADL = false;
2295 FnExpr = PExpr->getSubExpr();
2296 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002297 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002298 == UnaryOperator::AddrOf) {
2299 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002300 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
2301 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2302 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2303 break;
Mike Stump9afab102009-02-19 03:04:26 +00002304 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002305 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2306 UnqualifiedName = DepName->getName();
2307 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002308 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002309 // Any kind of name that does not refer to a declaration (or
2310 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2311 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002312 break;
2313 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002314 }
Mike Stump9afab102009-02-19 03:04:26 +00002315
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002316 OverloadedFunctionDecl *Ovl = 0;
2317 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002318 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002319 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
2320 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002321
Douglas Gregorfcb19192009-02-11 23:02:49 +00002322 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002323 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002324 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002325 ADL = false;
2326
Douglas Gregorfcb19192009-02-11 23:02:49 +00002327 // We don't perform ADL in C.
2328 if (!getLangOptions().CPlusPlus)
2329 ADL = false;
2330
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002331 if (Ovl || ADL) {
Mike Stump9afab102009-02-19 03:04:26 +00002332 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2333 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002334 NumArgs, CommaLocs, RParenLoc, ADL);
2335 if (!FDecl)
2336 return ExprError();
2337
2338 // Update Fn to refer to the actual function selected.
2339 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002340 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002341 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Douglas Gregor1e589cc2009-03-26 23:50:42 +00002342 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2343 QDRExpr->getLocation(),
2344 false, false,
2345 QDRExpr->getQualifierRange(),
2346 QDRExpr->getQualifier());
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002347 else
Mike Stump9afab102009-02-19 03:04:26 +00002348 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002349 Fn->getSourceRange().getBegin());
2350 Fn->Destroy(Context);
2351 Fn = NewFn;
2352 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002353 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002354
2355 // Promote the function operand.
2356 UsualUnaryConversions(Fn);
2357
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002358 // Make the call expr early, before semantic checks. This guarantees cleanup
2359 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002360 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2361 Args, NumArgs,
2362 Context.BoolTy,
2363 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002364
Steve Naroffd6163f32008-09-05 22:11:13 +00002365 const FunctionType *FuncT;
2366 if (!Fn->getType()->isBlockPointerType()) {
2367 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2368 // have type pointer to function".
2369 const PointerType *PT = Fn->getType()->getAsPointerType();
2370 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002371 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2372 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002373 FuncT = PT->getPointeeType()->getAsFunctionType();
2374 } else { // This is a block call.
2375 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2376 getAsFunctionType();
2377 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002378 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002379 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2380 << Fn->getType() << Fn->getSourceRange());
2381
Eli Friedman83dec9e2009-03-22 22:00:50 +00002382 // Check for a valid return type
2383 if (!FuncT->getResultType()->isVoidType() &&
2384 RequireCompleteType(Fn->getSourceRange().getBegin(),
2385 FuncT->getResultType(),
2386 diag::err_call_incomplete_return,
2387 TheCall->getSourceRange()))
2388 return ExprError();
2389
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002390 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002391 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002392
Douglas Gregor4fa58902009-02-26 23:50:07 +00002393 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002394 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002395 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002396 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002397 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002398 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002399
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002400 if (FDecl) {
2401 // Check if we have too few/too many template arguments, based
2402 // on our knowledge of the function definition.
2403 const FunctionDecl *Def = 0;
2404 if (FDecl->getBody(Def) && NumArgs != Def->param_size())
2405 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2406 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2407 }
2408
Steve Naroffdb65e052007-08-28 23:30:39 +00002409 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002410 for (unsigned i = 0; i != NumArgs; i++) {
2411 Expr *Arg = Args[i];
2412 DefaultArgumentPromotion(Arg);
Eli Friedman83dec9e2009-03-22 22:00:50 +00002413 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2414 Arg->getType(),
2415 diag::err_call_incomplete_argument,
2416 Arg->getSourceRange()))
2417 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002418 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002419 }
Chris Lattner4b009652007-07-25 00:24:17 +00002420 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002421
Douglas Gregor3257fb52008-12-22 05:46:06 +00002422 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2423 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002424 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2425 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002426
Chris Lattner2e64c072007-08-10 20:18:51 +00002427 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00002428 if (FDecl)
2429 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002430
Sebastian Redl8b769972009-01-19 00:08:26 +00002431 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002432}
2433
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002434Action::OwningExprResult
2435Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2436 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002437 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002438 QualType literalType = QualType::getFromOpaquePtr(Ty);
2439 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002440 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002441 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002442
Eli Friedman8c2173d2008-05-20 05:22:08 +00002443 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002444 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002445 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2446 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregorc84d8932009-03-09 16:13:40 +00002447 } else if (RequireCompleteType(LParenLoc, literalType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002448 diag::err_typecheck_decl_incomplete_type,
2449 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002450 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002451
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002452 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002453 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002454 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002455
Chris Lattnere5cb5862008-12-04 23:50:19 +00002456 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002457 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002458 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002459 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002460 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002461 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002462 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002463 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002464}
2465
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002466Action::OwningExprResult
2467Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002468 SourceLocation RBraceLoc) {
2469 unsigned NumInit = initlist.size();
2470 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002471
Steve Naroff0acc9c92007-09-15 18:49:24 +00002472 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002473 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002474
Mike Stump9afab102009-02-19 03:04:26 +00002475 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002476 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002477 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002478 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002479}
2480
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002481/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002482bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002483 UsualUnaryConversions(castExpr);
2484
2485 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2486 // type needs to be scalar.
2487 if (castType->isVoidType()) {
2488 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002489 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2490 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002491 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002492 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2493 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2494 (castType->isStructureType() || castType->isUnionType())) {
2495 // GCC struct/union extension: allow cast to self.
Eli Friedman2b128322009-03-23 00:24:07 +00002496 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002497 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2498 << castType << castExpr->getSourceRange();
2499 } else if (castType->isUnionType()) {
2500 // GCC cast to union extension
2501 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2502 RecordDecl::field_iterator Field, FieldEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002503 for (Field = RD->field_begin(Context), FieldEnd = RD->field_end(Context);
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002504 Field != FieldEnd; ++Field) {
2505 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2506 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2507 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2508 << castExpr->getSourceRange();
2509 break;
2510 }
2511 }
2512 if (Field == FieldEnd)
2513 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2514 << castExpr->getType() << castExpr->getSourceRange();
2515 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002516 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002517 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002518 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002519 }
Mike Stump9afab102009-02-19 03:04:26 +00002520 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002521 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002522 return Diag(castExpr->getLocStart(),
2523 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002524 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002525 } else if (castExpr->getType()->isVectorType()) {
2526 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2527 return true;
2528 } else if (castType->isVectorType()) {
2529 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2530 return true;
Steve Naroffff6c8022009-03-04 15:11:40 +00002531 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroff49fd7ad2009-04-08 23:52:26 +00002532 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002533 }
2534 return false;
2535}
2536
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002537bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002538 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00002539
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002540 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002541 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002542 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00002543 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002544 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002545 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002546 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002547 } else
2548 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002549 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002550 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00002551
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002552 return false;
2553}
2554
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002555Action::OwningExprResult
2556Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2557 SourceLocation RParenLoc, ExprArg Op) {
2558 assert((Ty != 0) && (Op.get() != 0) &&
2559 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002560
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002561 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002562 QualType castType = QualType::getFromOpaquePtr(Ty);
2563
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002564 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002565 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002566 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Mike Stump9afab102009-02-19 03:04:26 +00002567 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002568}
2569
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00002570/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
2571/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00002572/// C99 6.5.15
2573QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2574 SourceLocation QuestionLoc) {
Chris Lattnere2897262009-02-18 04:28:32 +00002575 UsualUnaryConversions(Cond);
2576 UsualUnaryConversions(LHS);
2577 UsualUnaryConversions(RHS);
2578 QualType CondTy = Cond->getType();
2579 QualType LHSTy = LHS->getType();
2580 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002581
2582 // first, check the condition.
Chris Lattnere2897262009-02-18 04:28:32 +00002583 if (!Cond->isTypeDependent()) {
2584 if (!CondTy->isScalarType()) { // C99 6.5.15p2
2585 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2586 << CondTy;
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002587 return QualType();
2588 }
Chris Lattner4b009652007-07-25 00:24:17 +00002589 }
Mike Stump9afab102009-02-19 03:04:26 +00002590
Chris Lattner992ae932008-01-06 22:42:25 +00002591 // Now check the two expressions.
Chris Lattnere2897262009-02-18 04:28:32 +00002592 if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent()))
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002593 return Context.DependentTy;
2594
Chris Lattner992ae932008-01-06 22:42:25 +00002595 // If both operands have arithmetic type, do the usual arithmetic conversions
2596 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00002597 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2598 UsualArithmeticConversions(LHS, RHS);
2599 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002600 }
Mike Stump9afab102009-02-19 03:04:26 +00002601
Chris Lattner992ae932008-01-06 22:42:25 +00002602 // If both operands are the same structure or union type, the result is that
2603 // type.
Chris Lattnere2897262009-02-18 04:28:32 +00002604 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
2605 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002606 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00002607 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00002608 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00002609 return LHSTy.getUnqualifiedType();
Eli Friedman2b128322009-03-23 00:24:07 +00002610 // FIXME: Type of conditional expression must be complete in C mode.
Chris Lattner4b009652007-07-25 00:24:17 +00002611 }
Mike Stump9afab102009-02-19 03:04:26 +00002612
Chris Lattner992ae932008-01-06 22:42:25 +00002613 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002614 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00002615 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2616 if (!LHSTy->isVoidType())
2617 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2618 << RHS->getSourceRange();
2619 if (!RHSTy->isVoidType())
2620 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2621 << LHS->getSourceRange();
2622 ImpCastExprToType(LHS, Context.VoidTy);
2623 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00002624 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002625 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002626 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2627 // the type of the other operand."
Chris Lattnere2897262009-02-18 04:28:32 +00002628 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2629 Context.isObjCObjectPointerType(LHSTy)) &&
2630 RHS->isNullPointerConstant(Context)) {
2631 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2632 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002633 }
Chris Lattnere2897262009-02-18 04:28:32 +00002634 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2635 Context.isObjCObjectPointerType(RHSTy)) &&
2636 LHS->isNullPointerConstant(Context)) {
2637 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2638 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002639 }
Mike Stump9afab102009-02-19 03:04:26 +00002640
Chris Lattner0ac51632008-01-06 22:50:31 +00002641 // Handle the case where both operands are pointers before we handle null
2642 // pointer constants in case both operands are null pointer constants.
Chris Lattnere2897262009-02-18 04:28:32 +00002643 if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6
2644 if (const PointerType *RHSPT = RHSTy->getAsPointerType()) {
Chris Lattner71225142007-07-31 21:27:01 +00002645 // get the "pointed to" types
2646 QualType lhptee = LHSPT->getPointeeType();
2647 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002648
Chris Lattner71225142007-07-31 21:27:01 +00002649 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2650 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002651 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002652 // Figure out necessary qualifiers (C99 6.5.15p6)
2653 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002654 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002655 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2656 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002657 return destType;
2658 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002659 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002660 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002661 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002662 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2663 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002664 return destType;
2665 }
Chris Lattner4b009652007-07-25 00:24:17 +00002666
Chris Lattner9c039b52009-02-18 04:38:20 +00002667 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
Chris Lattner676c86a2009-02-19 04:44:58 +00002668 // Two identical pointer types are always compatible.
Chris Lattner9c039b52009-02-18 04:38:20 +00002669 return LHSTy;
2670 }
Mike Stump9afab102009-02-19 03:04:26 +00002671
Chris Lattnere2897262009-02-18 04:28:32 +00002672 QualType compositeType = LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002673
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002674 // If either type is an Objective-C object type then check
2675 // compatibility according to Objective-C.
Mike Stump9afab102009-02-19 03:04:26 +00002676 if (Context.isObjCObjectPointerType(LHSTy) ||
Chris Lattnere2897262009-02-18 04:28:32 +00002677 Context.isObjCObjectPointerType(RHSTy)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002678 // If both operands are interfaces and either operand can be
2679 // assigned to the other, use that type as the composite
2680 // type. This allows
2681 // xxx ? (A*) a : (B*) b
2682 // where B is a subclass of A.
2683 //
2684 // Additionally, as for assignment, if either type is 'id'
2685 // allow silent coercion. Finally, if the types are
2686 // incompatible then make sure to use 'id' as the composite
2687 // type so the result is acceptable for sending messages to.
2688
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002689 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
Mike Stump9afab102009-02-19 03:04:26 +00002690 // It could return the composite type.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002691 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2692 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2693 if (LHSIface && RHSIface &&
2694 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002695 compositeType = LHSTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002696 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002697 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002698 compositeType = RHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002699 } else if (Context.isObjCIdStructType(lhptee) ||
2700 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002701 compositeType = Context.getObjCIdType();
2702 } else {
Chris Lattnere2897262009-02-18 04:28:32 +00002703 Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
Mike Stump9afab102009-02-19 03:04:26 +00002704 << LHSTy << RHSTy
Chris Lattnere2897262009-02-18 04:28:32 +00002705 << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002706 QualType incompatTy = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002707 ImpCastExprToType(LHS, incompatTy);
2708 ImpCastExprToType(RHS, incompatTy);
Mike Stump9afab102009-02-19 03:04:26 +00002709 return incompatTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002710 }
Mike Stump9afab102009-02-19 03:04:26 +00002711 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002712 rhptee.getUnqualifiedType())) {
Chris Lattnere2897262009-02-18 04:28:32 +00002713 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2714 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002715 // In this situation, we assume void* type. No especially good
2716 // reason, but this is what gcc does, and we do have to pick
2717 // to get a consistent AST.
2718 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Chris Lattnere2897262009-02-18 04:28:32 +00002719 ImpCastExprToType(LHS, incompatTy);
2720 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002721 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002722 }
2723 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002724 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2725 // differently qualified versions of compatible types, the result type is
2726 // a pointer to an appropriately qualified version of the *composite*
2727 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002728 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002729 // FIXME: Need to add qualifiers
Chris Lattnere2897262009-02-18 04:28:32 +00002730 ImpCastExprToType(LHS, compositeType);
2731 ImpCastExprToType(RHS, compositeType);
Eli Friedmane38150e2008-05-16 20:37:07 +00002732 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002733 }
Chris Lattner4b009652007-07-25 00:24:17 +00002734 }
Mike Stump9afab102009-02-19 03:04:26 +00002735
Steve Naroff6ba22682009-04-08 17:05:15 +00002736 // GCC compatibility: soften pointer/integer mismatch.
2737 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
2738 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
2739 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
2740 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
2741 return RHSTy;
2742 }
2743 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
2744 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
2745 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
2746 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
2747 return LHSTy;
2748 }
2749
Chris Lattner9c039b52009-02-18 04:38:20 +00002750 // Selection between block pointer types is ok as long as they are the same.
2751 if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() &&
2752 Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))
2753 return LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002754
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002755 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2756 // evaluates to "struct objc_object *" (and is handled above when comparing
Mike Stump9afab102009-02-19 03:04:26 +00002757 // id with statically typed objects).
2758 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002759 // GCC allows qualified id and any Objective-C type to devolve to
2760 // id. Currently localizing to here until clear this should be
2761 // part of ObjCQualifiedIdTypesAreCompatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002762 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
Mike Stump9afab102009-02-19 03:04:26 +00002763 (LHSTy->isObjCQualifiedIdType() &&
Chris Lattnere2897262009-02-18 04:28:32 +00002764 Context.isObjCObjectPointerType(RHSTy)) ||
2765 (RHSTy->isObjCQualifiedIdType() &&
2766 Context.isObjCObjectPointerType(LHSTy))) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002767 // FIXME: This is not the correct composite type. This only
2768 // happens to work because id can more or less be used anywhere,
2769 // however this may change the type of method sends.
2770 // FIXME: gcc adds some type-checking of the arguments and emits
2771 // (confusing) incompatible comparison warnings in some
2772 // cases. Investigate.
2773 QualType compositeType = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002774 ImpCastExprToType(LHS, compositeType);
2775 ImpCastExprToType(RHS, compositeType);
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002776 return compositeType;
2777 }
2778 }
2779
Chris Lattner992ae932008-01-06 22:42:25 +00002780 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002781 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2782 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002783 return QualType();
2784}
2785
Steve Naroff87d58b42007-09-16 03:34:24 +00002786/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002787/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002788Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2789 SourceLocation ColonLoc,
2790 ExprArg Cond, ExprArg LHS,
2791 ExprArg RHS) {
2792 Expr *CondExpr = (Expr *) Cond.get();
2793 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002794
2795 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2796 // was the condition.
2797 bool isLHSNull = LHSExpr == 0;
2798 if (isLHSNull)
2799 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002800
2801 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002802 RHSExpr, QuestionLoc);
2803 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002804 return ExprError();
2805
2806 Cond.release();
2807 LHS.release();
2808 RHS.release();
Mike Stump9afab102009-02-19 03:04:26 +00002809 return Owned(new (Context) ConditionalOperator(CondExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00002810 isLHSNull ? 0 : LHSExpr,
2811 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002812}
2813
Chris Lattner4b009652007-07-25 00:24:17 +00002814
2815// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00002816// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00002817// routine is it effectively iqnores the qualifiers on the top level pointee.
2818// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2819// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00002820Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002821Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2822 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00002823
Chris Lattner4b009652007-07-25 00:24:17 +00002824 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002825 lhptee = lhsType->getAsPointerType()->getPointeeType();
2826 rhptee = rhsType->getAsPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002827
Chris Lattner4b009652007-07-25 00:24:17 +00002828 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002829 lhptee = Context.getCanonicalType(lhptee);
2830 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002831
Chris Lattner005ed752008-01-04 18:04:52 +00002832 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00002833
2834 // C99 6.5.16.1p1: This following citation is common to constraints
2835 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2836 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00002837 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002838 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002839 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002840
Mike Stump9afab102009-02-19 03:04:26 +00002841 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2842 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00002843 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002844 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002845 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002846 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00002847
Chris Lattner4ca3d772008-01-03 22:56:36 +00002848 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002849 assert(rhptee->isFunctionType());
2850 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002851 }
Mike Stump9afab102009-02-19 03:04:26 +00002852
Chris Lattner4ca3d772008-01-03 22:56:36 +00002853 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002854 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002855 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002856
2857 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002858 assert(lhptee->isFunctionType());
2859 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002860 }
Mike Stump9afab102009-02-19 03:04:26 +00002861 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00002862 // unqualified versions of compatible types, ...
Eli Friedman6ca28cb2009-03-22 23:59:44 +00002863 lhptee = lhptee.getUnqualifiedType();
2864 rhptee = rhptee.getUnqualifiedType();
2865 if (!Context.typesAreCompatible(lhptee, rhptee)) {
2866 // Check if the pointee types are compatible ignoring the sign.
2867 // We explicitly check for char so that we catch "char" vs
2868 // "unsigned char" on systems where "char" is unsigned.
2869 if (lhptee->isCharType()) {
2870 lhptee = Context.UnsignedCharTy;
2871 } else if (lhptee->isSignedIntegerType()) {
2872 lhptee = Context.getCorrespondingUnsignedType(lhptee);
2873 }
2874 if (rhptee->isCharType()) {
2875 rhptee = Context.UnsignedCharTy;
2876 } else if (rhptee->isSignedIntegerType()) {
2877 rhptee = Context.getCorrespondingUnsignedType(rhptee);
2878 }
2879 if (lhptee == rhptee) {
2880 // Types are compatible ignoring the sign. Qualifier incompatibility
2881 // takes priority over sign incompatibility because the sign
2882 // warning can be disabled.
2883 if (ConvTy != Compatible)
2884 return ConvTy;
2885 return IncompatiblePointerSign;
2886 }
2887 // General pointer incompatibility takes priority over qualifiers.
2888 return IncompatiblePointer;
2889 }
Chris Lattner005ed752008-01-04 18:04:52 +00002890 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002891}
2892
Steve Naroff3454b6c2008-09-04 15:10:53 +00002893/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2894/// block pointer types are compatible or whether a block and normal pointer
2895/// are compatible. It is more restrict than comparing two function pointer
2896// types.
Mike Stump9afab102009-02-19 03:04:26 +00002897Sema::AssignConvertType
2898Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00002899 QualType rhsType) {
2900 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00002901
Steve Naroff3454b6c2008-09-04 15:10:53 +00002902 // get the "pointed to" type (ignoring qualifiers at the top level)
2903 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002904 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2905
Steve Naroff3454b6c2008-09-04 15:10:53 +00002906 // make sure we operate on the canonical type
2907 lhptee = Context.getCanonicalType(lhptee);
2908 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00002909
Steve Naroff3454b6c2008-09-04 15:10:53 +00002910 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00002911
Steve Naroff3454b6c2008-09-04 15:10:53 +00002912 // For blocks we enforce that qualifiers are identical.
2913 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2914 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00002915
Steve Naroff3454b6c2008-09-04 15:10:53 +00002916 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00002917 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002918 return ConvTy;
2919}
2920
Mike Stump9afab102009-02-19 03:04:26 +00002921/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2922/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00002923/// pointers. Here are some objectionable examples that GCC considers warnings:
2924///
2925/// int a, *pint;
2926/// short *pshort;
2927/// struct foo *pfoo;
2928///
2929/// pint = pshort; // warning: assignment from incompatible pointer type
2930/// a = pint; // warning: assignment makes integer from pointer without a cast
2931/// pint = a; // warning: assignment makes pointer from integer without a cast
2932/// pint = pfoo; // warning: assignment from incompatible pointer type
2933///
2934/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00002935/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002936///
Chris Lattner005ed752008-01-04 18:04:52 +00002937Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002938Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002939 // Get canonical types. We're not formatting these types, just comparing
2940 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002941 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2942 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002943
2944 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002945 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002946
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002947 // If the left-hand side is a reference type, then we are in a
2948 // (rare!) case where we've allowed the use of references in C,
2949 // e.g., as a parameter type in a built-in function. In this case,
2950 // just make sure that the type referenced is compatible with the
2951 // right-hand side type. The caller is responsible for adjusting
2952 // lhsType so that the resulting expression does not have reference
2953 // type.
2954 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2955 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002956 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002957 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002958 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002959
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002960 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2961 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002962 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002963 // Relax integer conversions like we do for pointers below.
2964 if (rhsType->isIntegerType())
2965 return IntToPointer;
2966 if (lhsType->isIntegerType())
2967 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002968 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002969 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002970
Nate Begemanc5f0f652008-07-14 18:02:46 +00002971 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002972 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002973 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2974 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002975 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002976
Nate Begemanc5f0f652008-07-14 18:02:46 +00002977 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00002978 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00002979 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002980 if (getLangOptions().LaxVectorConversions &&
2981 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002982 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002983 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002984 }
2985 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00002986 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002987
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002988 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002989 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002990
Chris Lattner390564e2008-04-07 06:49:41 +00002991 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002992 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002993 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002994
Chris Lattner390564e2008-04-07 06:49:41 +00002995 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002996 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002997
Steve Naroffa982c712008-09-29 18:10:17 +00002998 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002999 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003000 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00003001
3002 // Treat block pointers as objects.
3003 if (getLangOptions().ObjC1 &&
3004 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
3005 return Compatible;
3006 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003007 return Incompatible;
3008 }
3009
3010 if (isa<BlockPointerType>(lhsType)) {
3011 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00003012 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00003013
Steve Naroffa982c712008-09-29 18:10:17 +00003014 // Treat block pointers as objects.
3015 if (getLangOptions().ObjC1 &&
3016 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
3017 return Compatible;
3018
Steve Naroff3454b6c2008-09-04 15:10:53 +00003019 if (rhsType->isBlockPointerType())
3020 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003021
Steve Naroff3454b6c2008-09-04 15:10:53 +00003022 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
3023 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003024 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003025 }
Chris Lattner1853da22008-01-04 23:18:45 +00003026 return Incompatible;
3027 }
3028
Chris Lattner390564e2008-04-07 06:49:41 +00003029 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003030 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00003031 if (lhsType == Context.BoolTy)
3032 return Compatible;
3033
3034 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003035 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00003036
Mike Stump9afab102009-02-19 03:04:26 +00003037 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003038 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003039
3040 if (isa<BlockPointerType>(lhsType) &&
Steve Naroff3454b6c2008-09-04 15:10:53 +00003041 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003042 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003043 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003044 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003045
Chris Lattner1853da22008-01-04 23:18:45 +00003046 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00003047 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003048 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00003049 }
3050 return Incompatible;
3051}
3052
Chris Lattner005ed752008-01-04 18:04:52 +00003053Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003054Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003055 if (getLangOptions().CPlusPlus) {
3056 if (!lhsType->isRecordType()) {
3057 // C++ 5.17p3: If the left operand is not of class type, the
3058 // expression is implicitly converted (C++ 4) to the
3059 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00003060 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3061 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003062 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00003063 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003064 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003065 }
3066
3067 // FIXME: Currently, we fall through and treat C++ classes like C
3068 // structures.
3069 }
3070
Steve Naroffcdee22d2007-11-27 17:58:44 +00003071 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3072 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00003073 if ((lhsType->isPointerType() ||
3074 lhsType->isObjCQualifiedIdType() ||
Mike Stump9afab102009-02-19 03:04:26 +00003075 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00003076 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003077 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00003078 return Compatible;
3079 }
Mike Stump9afab102009-02-19 03:04:26 +00003080
Chris Lattner5f505bf2007-10-16 02:55:40 +00003081 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00003082 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00003083 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00003084 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00003085 //
Mike Stump9afab102009-02-19 03:04:26 +00003086 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00003087 if (!lhsType->isReferenceType())
3088 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00003089
Chris Lattner005ed752008-01-04 18:04:52 +00003090 Sema::AssignConvertType result =
3091 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00003092
Steve Naroff0f32f432007-08-24 22:33:52 +00003093 // C99 6.5.16.1p2: The value of the right operand is converted to the
3094 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003095 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3096 // so that we can use references in built-in functions even in C.
3097 // The getNonReferenceType() call makes sure that the resulting expression
3098 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00003099 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003100 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00003101 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00003102}
3103
Chris Lattner005ed752008-01-04 18:04:52 +00003104Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003105Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
3106 return CheckAssignmentConstraints(lhsType, rhsType);
3107}
3108
Chris Lattner1eafdea2008-11-18 01:30:42 +00003109QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003110 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003111 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003112 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00003113 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003114}
3115
Mike Stump9afab102009-02-19 03:04:26 +00003116inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00003117 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00003118 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00003119 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003120 QualType lhsType =
3121 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3122 QualType rhsType =
3123 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00003124
Nate Begemanc5f0f652008-07-14 18:02:46 +00003125 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00003126 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00003127 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00003128
Nate Begemanc5f0f652008-07-14 18:02:46 +00003129 // Handle the case of a vector & extvector type of the same size and element
3130 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00003131 if (getLangOptions().LaxVectorConversions) {
3132 // FIXME: Should we warn here?
3133 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003134 if (const VectorType *RV = rhsType->getAsVectorType())
3135 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00003136 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003137 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00003138 }
3139 }
3140 }
Mike Stump9afab102009-02-19 03:04:26 +00003141
Nate Begemanc5f0f652008-07-14 18:02:46 +00003142 // If the lhs is an extended vector and the rhs is a scalar of the same type
3143 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00003144 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003145 QualType eltType = V->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00003146
3147 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00003148 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
3149 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003150 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00003151 return lhsType;
3152 }
3153 }
3154
Nate Begemanc5f0f652008-07-14 18:02:46 +00003155 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00003156 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00003157 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003158 QualType eltType = V->getElementType();
3159
Mike Stump9afab102009-02-19 03:04:26 +00003160 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00003161 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
3162 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003163 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00003164 return rhsType;
3165 }
3166 }
3167
Chris Lattner4b009652007-07-25 00:24:17 +00003168 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00003169 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003170 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003171 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003172 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00003173}
3174
Chris Lattner4b009652007-07-25 00:24:17 +00003175inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003176 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003177{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00003178 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003179 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003180
Steve Naroff8f708362007-08-24 19:07:16 +00003181 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003182
Chris Lattner4b009652007-07-25 00:24:17 +00003183 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00003184 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003185 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003186}
3187
3188inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003189 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003190{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00003191 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3192 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3193 return CheckVectorOperands(Loc, lex, rex);
3194 return InvalidOperands(Loc, lex, rex);
3195 }
Chris Lattner4b009652007-07-25 00:24:17 +00003196
Steve Naroff8f708362007-08-24 19:07:16 +00003197 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003198
Chris Lattner4b009652007-07-25 00:24:17 +00003199 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003200 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003201 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003202}
3203
3204inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Eli Friedman3cd92882009-03-28 01:22:36 +00003205 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
Chris Lattner4b009652007-07-25 00:24:17 +00003206{
Eli Friedman3cd92882009-03-28 01:22:36 +00003207 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3208 QualType compType = CheckVectorOperands(Loc, lex, rex);
3209 if (CompLHSTy) *CompLHSTy = compType;
3210 return compType;
3211 }
Chris Lattner4b009652007-07-25 00:24:17 +00003212
Eli Friedman3cd92882009-03-28 01:22:36 +00003213 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003214
Chris Lattner4b009652007-07-25 00:24:17 +00003215 // handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00003216 if (lex->getType()->isArithmeticType() &&
3217 rex->getType()->isArithmeticType()) {
3218 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00003219 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00003220 }
Chris Lattner4b009652007-07-25 00:24:17 +00003221
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003222 // Put any potential pointer into PExp
3223 Expr* PExp = lex, *IExp = rex;
3224 if (IExp->getType()->isPointerType())
3225 std::swap(PExp, IExp);
3226
3227 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
3228 if (IExp->getType()->isIntegerType()) {
3229 // Check for arithmetic on pointers to incomplete types
Douglas Gregor05e28f62009-03-24 19:52:54 +00003230 if (PTy->getPointeeType()->isVoidType()) {
3231 if (getLangOptions().CPlusPlus) {
3232 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner8ba580c2008-11-19 05:08:23 +00003233 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003234 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003235 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003236
3237 // GNU extension: arithmetic on pointer to void
3238 Diag(Loc, diag::ext_gnu_void_ptr)
3239 << lex->getSourceRange() << rex->getSourceRange();
3240 } else if (PTy->getPointeeType()->isFunctionType()) {
3241 if (getLangOptions().CPlusPlus) {
3242 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3243 << lex->getType() << lex->getSourceRange();
3244 return QualType();
3245 }
3246
3247 // GNU extension: arithmetic on pointer to function
3248 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3249 << lex->getType() << lex->getSourceRange();
3250 } else if (!PTy->isDependentType() &&
3251 RequireCompleteType(Loc, PTy->getPointeeType(),
3252 diag::err_typecheck_arithmetic_incomplete_type,
3253 lex->getSourceRange(), SourceRange(),
3254 lex->getType()))
3255 return QualType();
3256
Eli Friedman3cd92882009-03-28 01:22:36 +00003257 if (CompLHSTy) {
3258 QualType LHSTy = lex->getType();
3259 if (LHSTy->isPromotableIntegerType())
3260 LHSTy = Context.IntTy;
3261 *CompLHSTy = LHSTy;
3262 }
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003263 return PExp->getType();
3264 }
3265 }
3266
Chris Lattner1eafdea2008-11-18 01:30:42 +00003267 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003268}
3269
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003270// C99 6.5.6
3271QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman3cd92882009-03-28 01:22:36 +00003272 SourceLocation Loc, QualType* CompLHSTy) {
3273 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3274 QualType compType = CheckVectorOperands(Loc, lex, rex);
3275 if (CompLHSTy) *CompLHSTy = compType;
3276 return compType;
3277 }
Mike Stump9afab102009-02-19 03:04:26 +00003278
Eli Friedman3cd92882009-03-28 01:22:36 +00003279 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump9afab102009-02-19 03:04:26 +00003280
Chris Lattnerf6da2912007-12-09 21:53:25 +00003281 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00003282
Chris Lattnerf6da2912007-12-09 21:53:25 +00003283 // Handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00003284 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) {
3285 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00003286 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00003287 }
Mike Stump9afab102009-02-19 03:04:26 +00003288
Chris Lattnerf6da2912007-12-09 21:53:25 +00003289 // Either ptr - int or ptr - ptr.
3290 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00003291 QualType lpointee = LHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003292
Douglas Gregor05e28f62009-03-24 19:52:54 +00003293 // The LHS must be an completely-defined object type.
Douglas Gregorb3193242009-01-23 00:36:41 +00003294
Douglas Gregor05e28f62009-03-24 19:52:54 +00003295 bool ComplainAboutVoid = false;
3296 Expr *ComplainAboutFunc = 0;
3297 if (lpointee->isVoidType()) {
3298 if (getLangOptions().CPlusPlus) {
3299 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3300 << lex->getSourceRange() << rex->getSourceRange();
3301 return QualType();
3302 }
3303
3304 // GNU C extension: arithmetic on pointer to void
3305 ComplainAboutVoid = true;
3306 } else if (lpointee->isFunctionType()) {
3307 if (getLangOptions().CPlusPlus) {
3308 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003309 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003310 return QualType();
3311 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003312
3313 // GNU C extension: arithmetic on pointer to function
3314 ComplainAboutFunc = lex;
3315 } else if (!lpointee->isDependentType() &&
3316 RequireCompleteType(Loc, lpointee,
3317 diag::err_typecheck_sub_ptr_object,
3318 lex->getSourceRange(),
3319 SourceRange(),
3320 lex->getType()))
3321 return QualType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003322
3323 // The result type of a pointer-int computation is the pointer type.
Douglas Gregor05e28f62009-03-24 19:52:54 +00003324 if (rex->getType()->isIntegerType()) {
3325 if (ComplainAboutVoid)
3326 Diag(Loc, diag::ext_gnu_void_ptr)
3327 << lex->getSourceRange() << rex->getSourceRange();
3328 if (ComplainAboutFunc)
3329 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3330 << ComplainAboutFunc->getType()
3331 << ComplainAboutFunc->getSourceRange();
3332
Eli Friedman3cd92882009-03-28 01:22:36 +00003333 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003334 return lex->getType();
Douglas Gregor05e28f62009-03-24 19:52:54 +00003335 }
Mike Stump9afab102009-02-19 03:04:26 +00003336
Chris Lattnerf6da2912007-12-09 21:53:25 +00003337 // Handle pointer-pointer subtractions.
3338 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00003339 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003340
Douglas Gregor05e28f62009-03-24 19:52:54 +00003341 // RHS must be a completely-type object type.
3342 // Handle the GNU void* extension.
3343 if (rpointee->isVoidType()) {
3344 if (getLangOptions().CPlusPlus) {
3345 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3346 << lex->getSourceRange() << rex->getSourceRange();
3347 return QualType();
3348 }
Mike Stump9afab102009-02-19 03:04:26 +00003349
Douglas Gregor05e28f62009-03-24 19:52:54 +00003350 ComplainAboutVoid = true;
3351 } else if (rpointee->isFunctionType()) {
3352 if (getLangOptions().CPlusPlus) {
3353 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003354 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003355 return QualType();
3356 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003357
3358 // GNU extension: arithmetic on pointer to function
3359 if (!ComplainAboutFunc)
3360 ComplainAboutFunc = rex;
3361 } else if (!rpointee->isDependentType() &&
3362 RequireCompleteType(Loc, rpointee,
3363 diag::err_typecheck_sub_ptr_object,
3364 rex->getSourceRange(),
3365 SourceRange(),
3366 rex->getType()))
3367 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00003368
Chris Lattnerf6da2912007-12-09 21:53:25 +00003369 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00003370 if (!Context.typesAreCompatible(
Mike Stump9afab102009-02-19 03:04:26 +00003371 Context.getCanonicalType(lpointee).getUnqualifiedType(),
Eli Friedman583c31e2008-09-02 05:09:35 +00003372 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003373 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003374 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003375 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003376 return QualType();
3377 }
Mike Stump9afab102009-02-19 03:04:26 +00003378
Douglas Gregor05e28f62009-03-24 19:52:54 +00003379 if (ComplainAboutVoid)
3380 Diag(Loc, diag::ext_gnu_void_ptr)
3381 << lex->getSourceRange() << rex->getSourceRange();
3382 if (ComplainAboutFunc)
3383 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3384 << ComplainAboutFunc->getType()
3385 << ComplainAboutFunc->getSourceRange();
Eli Friedman3cd92882009-03-28 01:22:36 +00003386
3387 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003388 return Context.getPointerDiffType();
3389 }
3390 }
Mike Stump9afab102009-02-19 03:04:26 +00003391
Chris Lattner1eafdea2008-11-18 01:30:42 +00003392 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003393}
3394
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003395// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00003396QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003397 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00003398 // C99 6.5.7p2: Each of the operands shall have integer type.
3399 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003400 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003401
Chris Lattner2c8bff72007-12-12 05:47:28 +00003402 // Shifts don't perform usual arithmetic conversions, they just do integer
3403 // promotions on each operand. C99 6.5.7p3
Eli Friedman3cd92882009-03-28 01:22:36 +00003404 QualType LHSTy;
3405 if (lex->getType()->isPromotableIntegerType())
3406 LHSTy = Context.IntTy;
3407 else
3408 LHSTy = lex->getType();
Chris Lattnerbb19bc42007-12-13 07:28:16 +00003409 if (!isCompAssign)
Eli Friedman3cd92882009-03-28 01:22:36 +00003410 ImpCastExprToType(lex, LHSTy);
3411
Chris Lattner2c8bff72007-12-12 05:47:28 +00003412 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003413
Chris Lattner2c8bff72007-12-12 05:47:28 +00003414 // "The type of the result is that of the promoted left operand."
Eli Friedman3cd92882009-03-28 01:22:36 +00003415 return LHSTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003416}
3417
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003418// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00003419QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor1f12c352009-04-06 18:45:53 +00003420 unsigned OpaqueOpc, bool isRelational) {
3421 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
3422
Nate Begemanc5f0f652008-07-14 18:02:46 +00003423 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003424 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00003425
Chris Lattner254f3bc2007-08-26 01:18:55 +00003426 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00003427 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3428 UsualArithmeticConversions(lex, rex);
3429 else {
3430 UsualUnaryConversions(lex);
3431 UsualUnaryConversions(rex);
3432 }
Chris Lattner4b009652007-07-25 00:24:17 +00003433 QualType lType = lex->getType();
3434 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003435
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003436 if (!lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00003437 // For non-floating point types, check for self-comparisons of the form
3438 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3439 // often indicate logic errors in the program.
Ted Kremenek264b5cb2009-03-20 19:57:37 +00003440 // NOTE: Don't warn about comparisons of enum constants. These can arise
3441 // from macro expansions, and are usually quite deliberate.
Chris Lattner4e479f92009-03-08 19:39:53 +00003442 Expr *LHSStripped = lex->IgnoreParens();
3443 Expr *RHSStripped = rex->IgnoreParens();
3444 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
3445 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekf042dc62009-03-20 18:35:45 +00003446 if (DRL->getDecl() == DRR->getDecl() &&
3447 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump9afab102009-02-19 03:04:26 +00003448 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner4e479f92009-03-08 19:39:53 +00003449
3450 if (isa<CastExpr>(LHSStripped))
3451 LHSStripped = LHSStripped->IgnoreParenCasts();
3452 if (isa<CastExpr>(RHSStripped))
3453 RHSStripped = RHSStripped->IgnoreParenCasts();
3454
3455 // Warn about comparisons against a string constant (unless the other
3456 // operand is null), the user probably wants strcmp.
Douglas Gregor1f12c352009-04-06 18:45:53 +00003457 Expr *literalString = 0;
3458 Expr *literalStringStripped = 0;
Chris Lattner4e479f92009-03-08 19:39:53 +00003459 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00003460 !RHSStripped->isNullPointerConstant(Context)) {
3461 literalString = lex;
3462 literalStringStripped = LHSStripped;
3463 }
Chris Lattner4e479f92009-03-08 19:39:53 +00003464 else if ((isa<StringLiteral>(RHSStripped) ||
3465 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00003466 !LHSStripped->isNullPointerConstant(Context)) {
3467 literalString = rex;
3468 literalStringStripped = RHSStripped;
3469 }
3470
3471 if (literalString) {
3472 std::string resultComparison;
3473 switch (Opc) {
3474 case BinaryOperator::LT: resultComparison = ") < 0"; break;
3475 case BinaryOperator::GT: resultComparison = ") > 0"; break;
3476 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
3477 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
3478 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
3479 case BinaryOperator::NE: resultComparison = ") != 0"; break;
3480 default: assert(false && "Invalid comparison operator");
3481 }
3482 Diag(Loc, diag::warn_stringcompare)
3483 << isa<ObjCEncodeExpr>(literalStringStripped)
3484 << literalString->getSourceRange()
Douglas Gregor3faaa812009-04-01 23:51:29 +00003485 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
3486 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
3487 "strcmp(")
3488 << CodeModificationHint::CreateInsertion(
3489 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor1f12c352009-04-06 18:45:53 +00003490 resultComparison);
3491 }
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003492 }
Mike Stump9afab102009-02-19 03:04:26 +00003493
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003494 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner4e479f92009-03-08 19:39:53 +00003495 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003496
Chris Lattner254f3bc2007-08-26 01:18:55 +00003497 if (isRelational) {
3498 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003499 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003500 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00003501 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00003502 if (lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00003503 assert(rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003504 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00003505 }
Mike Stump9afab102009-02-19 03:04:26 +00003506
Chris Lattner254f3bc2007-08-26 01:18:55 +00003507 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003508 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003509 }
Mike Stump9afab102009-02-19 03:04:26 +00003510
Chris Lattner22be8422007-08-26 01:10:14 +00003511 bool LHSIsNull = lex->isNullPointerConstant(Context);
3512 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00003513
Chris Lattner254f3bc2007-08-26 01:18:55 +00003514 // All of the following pointer related warnings are GCC extensions, except
3515 // when handling null pointer constants. One day, we can consider making them
3516 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00003517 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003518 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003519 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00003520 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003521 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00003522
Steve Naroff3b435622007-11-13 14:57:38 +00003523 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003524 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3525 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00003526 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00003527 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003528 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003529 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003530 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003531 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003532 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003533 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003534 // Handle block pointer types.
3535 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3536 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3537 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003538
Steve Naroff3454b6c2008-09-04 15:10:53 +00003539 if (!LHSIsNull && !RHSIsNull &&
3540 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003541 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003542 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003543 }
3544 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003545 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003546 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003547 // Allow block pointers to be compared with null pointer constants.
3548 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3549 (lType->isPointerType() && rType->isBlockPointerType())) {
3550 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003551 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003552 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003553 }
3554 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003555 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003556 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003557
Steve Naroff936c4362008-06-03 14:04:54 +00003558 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003559 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003560 const PointerType *LPT = lType->getAsPointerType();
3561 const PointerType *RPT = rType->getAsPointerType();
Mike Stump9afab102009-02-19 03:04:26 +00003562 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003563 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003564 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003565 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003566
Steve Naroff030fcda2008-11-17 19:49:16 +00003567 if (!LPtrToVoid && !RPtrToVoid &&
3568 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003569 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003570 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003571 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003572 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003573 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003574 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003575 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003576 }
Steve Naroff936c4362008-06-03 14:04:54 +00003577 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3578 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003579 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003580 } else {
3581 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003582 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003583 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003584 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003585 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003586 }
Steve Naroff936c4362008-06-03 14:04:54 +00003587 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003588 }
Mike Stump9afab102009-02-19 03:04:26 +00003589 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
Steve Naroff936c4362008-06-03 14:04:54 +00003590 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003591 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003592 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003593 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003594 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003595 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003596 }
Mike Stump9afab102009-02-19 03:04:26 +00003597 if (lType->isIntegerType() &&
Steve Naroff936c4362008-06-03 14:04:54 +00003598 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003599 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003600 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003601 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003602 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003603 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003604 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003605 // Handle block pointers.
3606 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3607 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003608 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003609 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003610 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003611 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003612 }
3613 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3614 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003615 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003616 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003617 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003618 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003619 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003620 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003621}
3622
Nate Begemanc5f0f652008-07-14 18:02:46 +00003623/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00003624/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003625/// like a scalar comparison, a vector comparison produces a vector of integer
3626/// types.
3627QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003628 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003629 bool isRelational) {
3630 // Check to make sure we're operating on vectors of the same type and width,
3631 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003632 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003633 if (vType.isNull())
3634 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00003635
Nate Begemanc5f0f652008-07-14 18:02:46 +00003636 QualType lType = lex->getType();
3637 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003638
Nate Begemanc5f0f652008-07-14 18:02:46 +00003639 // For non-floating point types, check for self-comparisons of the form
3640 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3641 // often indicate logic errors in the program.
3642 if (!lType->isFloatingType()) {
3643 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3644 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3645 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003646 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003647 }
Mike Stump9afab102009-02-19 03:04:26 +00003648
Nate Begemanc5f0f652008-07-14 18:02:46 +00003649 // Check for comparisons of floating point operands using != and ==.
3650 if (!isRelational && lType->isFloatingType()) {
3651 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003652 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003653 }
Mike Stump9afab102009-02-19 03:04:26 +00003654
Chris Lattner10687e32009-03-31 07:46:52 +00003655 // FIXME: Vector compare support in the LLVM backend is not fully reliable,
3656 // just reject all vector comparisons for now.
3657 if (1) {
3658 Diag(Loc, diag::err_typecheck_vector_comparison)
3659 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3660 return QualType();
3661 }
3662
Nate Begemanc5f0f652008-07-14 18:02:46 +00003663 // Return the type for the comparison, which is the same as vector type for
3664 // integer vectors, or an integer type of identical size and number of
3665 // elements for floating point vectors.
3666 if (lType->isIntegerType())
3667 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00003668
Nate Begemanc5f0f652008-07-14 18:02:46 +00003669 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003670 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003671 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003672 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner10687e32009-03-31 07:46:52 +00003673 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begemand6d2f772009-01-18 03:20:47 +00003674 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3675
Mike Stump9afab102009-02-19 03:04:26 +00003676 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00003677 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003678 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3679}
3680
Chris Lattner4b009652007-07-25 00:24:17 +00003681inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003682 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003683{
3684 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003685 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003686
Steve Naroff8f708362007-08-24 19:07:16 +00003687 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003688
Chris Lattner4b009652007-07-25 00:24:17 +00003689 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003690 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003691 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003692}
3693
3694inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00003695 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003696{
3697 UsualUnaryConversions(lex);
3698 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003699
Eli Friedmanbea3f842008-05-13 20:16:47 +00003700 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003701 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003702 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003703}
3704
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003705/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3706/// is a read-only property; return true if so. A readonly property expression
3707/// depends on various declarations and thus must be treated specially.
3708///
Mike Stump9afab102009-02-19 03:04:26 +00003709static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003710{
3711 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3712 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3713 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3714 QualType BaseType = PropExpr->getBase()->getType();
3715 if (const PointerType *PTy = BaseType->getAsPointerType())
Mike Stump9afab102009-02-19 03:04:26 +00003716 if (const ObjCInterfaceType *IFTy =
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003717 PTy->getPointeeType()->getAsObjCInterfaceType())
3718 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3719 if (S.isPropertyReadonly(PDecl, IFace))
3720 return true;
3721 }
3722 }
3723 return false;
3724}
3725
Chris Lattner4c2642c2008-11-18 01:22:49 +00003726/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3727/// emit an error and return true. If so, return false.
3728static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003729 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3730 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3731 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003732 if (IsLV == Expr::MLV_Valid)
3733 return false;
Mike Stump9afab102009-02-19 03:04:26 +00003734
Chris Lattner4c2642c2008-11-18 01:22:49 +00003735 unsigned Diag = 0;
3736 bool NeedType = false;
3737 switch (IsLV) { // C99 6.5.16p2
3738 default: assert(0 && "Unknown result from isModifiableLvalue!");
3739 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00003740 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003741 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3742 NeedType = true;
3743 break;
Mike Stump9afab102009-02-19 03:04:26 +00003744 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003745 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3746 NeedType = true;
3747 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003748 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003749 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3750 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003751 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003752 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3753 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003754 case Expr::MLV_IncompleteType:
3755 case Expr::MLV_IncompleteVoidType:
Douglas Gregorc84d8932009-03-09 16:13:40 +00003756 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003757 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3758 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003759 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003760 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3761 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003762 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003763 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3764 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003765 case Expr::MLV_ReadonlyProperty:
3766 Diag = diag::error_readonly_property_assignment;
3767 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003768 case Expr::MLV_NoSetterProperty:
3769 Diag = diag::error_nosetter_property_assignment;
3770 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003771 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003772
Chris Lattner4c2642c2008-11-18 01:22:49 +00003773 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003774 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003775 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003776 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003777 return true;
3778}
3779
3780
3781
3782// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003783QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3784 SourceLocation Loc,
3785 QualType CompoundType) {
3786 // Verify that LHS is a modifiable lvalue, and emit error if not.
3787 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003788 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003789
3790 QualType LHSType = LHS->getType();
3791 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00003792
Chris Lattner005ed752008-01-04 18:04:52 +00003793 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003794 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003795 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003796 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003797 // Special case of NSObject attributes on c-style pointer types.
3798 if (ConvTy == IncompatiblePointer &&
3799 ((Context.isObjCNSObjectType(LHSType) &&
3800 Context.isObjCObjectPointerType(RHSType)) ||
3801 (Context.isObjCNSObjectType(RHSType) &&
3802 Context.isObjCObjectPointerType(LHSType))))
3803 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003804
Chris Lattner34c85082008-08-21 18:04:13 +00003805 // If the RHS is a unary plus or minus, check to see if they = and + are
3806 // right next to each other. If so, the user may have typo'd "x =+ 4"
3807 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003808 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003809 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3810 RHSCheck = ICE->getSubExpr();
3811 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3812 if ((UO->getOpcode() == UnaryOperator::Plus ||
3813 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003814 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003815 // Only if the two operators are exactly adjacent.
Chris Lattner55a17242009-03-08 06:51:10 +00003816 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
3817 // And there is a space or other character before the subexpr of the
3818 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnerf1e5d4a2009-03-09 07:11:10 +00003819 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
3820 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003821 Diag(Loc, diag::warn_not_compound_assign)
3822 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3823 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner55a17242009-03-08 06:51:10 +00003824 }
Chris Lattner34c85082008-08-21 18:04:13 +00003825 }
3826 } else {
3827 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003828 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003829 }
Chris Lattner005ed752008-01-04 18:04:52 +00003830
Chris Lattner1eafdea2008-11-18 01:30:42 +00003831 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3832 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003833 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00003834
Chris Lattner4b009652007-07-25 00:24:17 +00003835 // C99 6.5.16p3: The type of an assignment expression is the type of the
3836 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00003837 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00003838 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3839 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003840 // C++ 5.17p1: the type of the assignment expression is that of its left
3841 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003842 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003843}
3844
Chris Lattner1eafdea2008-11-18 01:30:42 +00003845// C99 6.5.17
3846QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00003847 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003848 DefaultFunctionArrayConversion(RHS);
Eli Friedman2b128322009-03-23 00:24:07 +00003849
3850 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
3851 // incomplete in C++).
3852
Chris Lattner1eafdea2008-11-18 01:30:42 +00003853 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003854}
3855
3856/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3857/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003858QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3859 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003860 if (Op->isTypeDependent())
3861 return Context.DependentTy;
3862
Chris Lattnere65182c2008-11-21 07:05:48 +00003863 QualType ResType = Op->getType();
3864 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003865
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003866 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3867 // Decrement of bool is not allowed.
3868 if (!isInc) {
3869 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3870 return QualType();
3871 }
3872 // Increment of bool sets it to true, but is deprecated.
3873 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3874 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003875 // OK!
3876 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3877 // C99 6.5.2.4p2, 6.5.6p2
Douglas Gregorcde3a2d2009-03-24 20:13:58 +00003878 if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003879 if (getLangOptions().CPlusPlus) {
3880 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3881 << Op->getSourceRange();
3882 return QualType();
3883 }
3884
3885 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003886 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003887 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003888 if (getLangOptions().CPlusPlus) {
3889 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3890 << Op->getType() << Op->getSourceRange();
3891 return QualType();
3892 }
3893
3894 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003895 << ResType << Op->getSourceRange();
Douglas Gregorcde3a2d2009-03-24 20:13:58 +00003896 } else if (RequireCompleteType(OpLoc, PT->getPointeeType(),
3897 diag::err_typecheck_arithmetic_incomplete_type,
3898 Op->getSourceRange(), SourceRange(),
3899 ResType))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003900 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003901 } else if (ResType->isComplexType()) {
3902 // C99 does not support ++/-- on complex types, we allow as an extension.
3903 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003904 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003905 } else {
3906 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003907 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003908 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003909 }
Mike Stump9afab102009-02-19 03:04:26 +00003910 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00003911 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003912 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003913 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003914 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003915}
3916
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003917/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003918/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003919/// where the declaration is needed for type checking. We only need to
3920/// handle cases when the expression references a function designator
3921/// or is an lvalue. Here are some examples:
3922/// - &(x) => x
3923/// - &*****f => f for f a function designator.
3924/// - &s.xx => s
3925/// - &s.zz[1].yy -> s, if zz is an array
3926/// - *(x + 1) -> x, if x is an array
3927/// - &"123"[2] -> 0
3928/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003929static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003930 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003931 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003932 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003933 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003934 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003935 // Fields cannot be declared with a 'register' storage class.
3936 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003937 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003938 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003939 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003940 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003941 // &X[4] and &4[X] refers to X if X is not a pointer.
Mike Stump9afab102009-02-19 03:04:26 +00003942
Douglas Gregord2baafd2008-10-21 16:13:35 +00003943 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003944 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003945 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003946 return 0;
3947 else
3948 return VD;
3949 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003950 case Stmt::UnaryOperatorClass: {
3951 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00003952
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003953 switch(UO->getOpcode()) {
3954 case UnaryOperator::Deref: {
3955 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003956 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3957 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3958 if (!VD || VD->getType()->isPointerType())
3959 return 0;
3960 return VD;
3961 }
3962 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003963 }
3964 case UnaryOperator::Real:
3965 case UnaryOperator::Imag:
3966 case UnaryOperator::Extension:
3967 return getPrimaryDecl(UO->getSubExpr());
3968 default:
3969 return 0;
3970 }
3971 }
3972 case Stmt::BinaryOperatorClass: {
3973 BinaryOperator *BO = cast<BinaryOperator>(E);
3974
3975 // Handle cases involving pointer arithmetic. The result of an
3976 // Assign or AddAssign is not an lvalue so they can be ignored.
3977
3978 // (x + n) or (n + x) => x
3979 if (BO->getOpcode() == BinaryOperator::Add) {
3980 if (BO->getLHS()->getType()->isPointerType()) {
3981 return getPrimaryDecl(BO->getLHS());
3982 } else if (BO->getRHS()->getType()->isPointerType()) {
3983 return getPrimaryDecl(BO->getRHS());
3984 }
3985 }
3986
3987 return 0;
3988 }
Chris Lattner4b009652007-07-25 00:24:17 +00003989 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003990 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003991 case Stmt::ImplicitCastExprClass:
3992 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003993 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003994 default:
3995 return 0;
3996 }
3997}
3998
3999/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00004000/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00004001/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00004002/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00004003/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00004004/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00004005/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00004006QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00004007 if (op->isTypeDependent())
4008 return Context.DependentTy;
4009
Steve Naroff9c6c3592008-01-13 17:10:08 +00004010 if (getLangOptions().C99) {
4011 // Implement C99-only parts of addressof rules.
4012 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
4013 if (uOp->getOpcode() == UnaryOperator::Deref)
4014 // Per C99 6.5.3.2, the address of a deref always returns a valid result
4015 // (assuming the deref expression is valid).
4016 return uOp->getSubExpr()->getType();
4017 }
4018 // Technically, there should be a check for array subscript
4019 // expressions here, but the result of one is always an lvalue anyway.
4020 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00004021 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00004022 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00004023
Chris Lattner4b009652007-07-25 00:24:17 +00004024 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00004025 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
4026 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00004027 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
4028 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004029 return QualType();
4030 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00004031 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00004032 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
4033 if (Field->isBitField()) {
4034 Diag(OpLoc, diag::err_typecheck_address_of)
4035 << "bit-field" << op->getSourceRange();
4036 return QualType();
4037 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00004038 }
4039 // Check for Apple extension for accessing vector components.
Nate Begemana9187ab2009-02-15 22:45:20 +00004040 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
4041 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Chris Lattner77d52da2008-11-20 06:06:08 +00004042 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00004043 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004044 return QualType();
4045 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00004046 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00004047 // with the register storage-class specifier.
4048 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
4049 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004050 Diag(OpLoc, diag::err_typecheck_address_of)
4051 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004052 return QualType();
4053 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00004054 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00004055 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00004056 } else if (isa<FieldDecl>(dcl)) {
4057 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00004058 // Could be a pointer to member, though, if there is an explicit
4059 // scope qualifier for the class.
4060 if (isa<QualifiedDeclRefExpr>(op)) {
4061 DeclContext *Ctx = dcl->getDeclContext();
4062 if (Ctx && Ctx->isRecord())
4063 return Context.getMemberPointerType(op->getType(),
4064 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
4065 }
Nuno Lopesdf239522008-12-16 22:58:26 +00004066 } else if (isa<FunctionDecl>(dcl)) {
4067 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00004068 // As above.
4069 if (isa<QualifiedDeclRefExpr>(op)) {
4070 DeclContext *Ctx = dcl->getDeclContext();
4071 if (Ctx && Ctx->isRecord())
4072 return Context.getMemberPointerType(op->getType(),
4073 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
4074 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00004075 }
Nuno Lopesdf239522008-12-16 22:58:26 +00004076 else
Chris Lattner4b009652007-07-25 00:24:17 +00004077 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00004078 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00004079
Chris Lattner4b009652007-07-25 00:24:17 +00004080 // If the operand has type "type", the result has type "pointer to type".
4081 return Context.getPointerType(op->getType());
4082}
4083
Chris Lattnerda5c0872008-11-23 09:13:29 +00004084QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004085 if (Op->isTypeDependent())
4086 return Context.DependentTy;
4087
Chris Lattnerda5c0872008-11-23 09:13:29 +00004088 UsualUnaryConversions(Op);
4089 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004090
Chris Lattnerda5c0872008-11-23 09:13:29 +00004091 // Note that per both C89 and C99, this is always legal, even if ptype is an
4092 // incomplete type or void. It would be possible to warn about dereferencing
4093 // a void pointer, but it's completely well-defined, and such a warning is
4094 // unlikely to catch any mistakes.
4095 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00004096 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004097
Chris Lattner77d52da2008-11-20 06:06:08 +00004098 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00004099 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004100 return QualType();
4101}
4102
4103static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
4104 tok::TokenKind Kind) {
4105 BinaryOperator::Opcode Opc;
4106 switch (Kind) {
4107 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00004108 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
4109 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00004110 case tok::star: Opc = BinaryOperator::Mul; break;
4111 case tok::slash: Opc = BinaryOperator::Div; break;
4112 case tok::percent: Opc = BinaryOperator::Rem; break;
4113 case tok::plus: Opc = BinaryOperator::Add; break;
4114 case tok::minus: Opc = BinaryOperator::Sub; break;
4115 case tok::lessless: Opc = BinaryOperator::Shl; break;
4116 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
4117 case tok::lessequal: Opc = BinaryOperator::LE; break;
4118 case tok::less: Opc = BinaryOperator::LT; break;
4119 case tok::greaterequal: Opc = BinaryOperator::GE; break;
4120 case tok::greater: Opc = BinaryOperator::GT; break;
4121 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
4122 case tok::equalequal: Opc = BinaryOperator::EQ; break;
4123 case tok::amp: Opc = BinaryOperator::And; break;
4124 case tok::caret: Opc = BinaryOperator::Xor; break;
4125 case tok::pipe: Opc = BinaryOperator::Or; break;
4126 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
4127 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
4128 case tok::equal: Opc = BinaryOperator::Assign; break;
4129 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
4130 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
4131 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
4132 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
4133 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
4134 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
4135 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
4136 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
4137 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
4138 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
4139 case tok::comma: Opc = BinaryOperator::Comma; break;
4140 }
4141 return Opc;
4142}
4143
4144static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
4145 tok::TokenKind Kind) {
4146 UnaryOperator::Opcode Opc;
4147 switch (Kind) {
4148 default: assert(0 && "Unknown unary op!");
4149 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
4150 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
4151 case tok::amp: Opc = UnaryOperator::AddrOf; break;
4152 case tok::star: Opc = UnaryOperator::Deref; break;
4153 case tok::plus: Opc = UnaryOperator::Plus; break;
4154 case tok::minus: Opc = UnaryOperator::Minus; break;
4155 case tok::tilde: Opc = UnaryOperator::Not; break;
4156 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00004157 case tok::kw___real: Opc = UnaryOperator::Real; break;
4158 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
4159 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
4160 }
4161 return Opc;
4162}
4163
Douglas Gregord7f915e2008-11-06 23:29:22 +00004164/// CreateBuiltinBinOp - Creates a new built-in binary operation with
4165/// operator @p Opc at location @c TokLoc. This routine only supports
4166/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004167Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
4168 unsigned Op,
4169 Expr *lhs, Expr *rhs) {
Eli Friedman3cd92882009-03-28 01:22:36 +00004170 QualType ResultTy; // Result type of the binary operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00004171 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman3cd92882009-03-28 01:22:36 +00004172 // The following two variables are used for compound assignment operators
4173 QualType CompLHSTy; // Type of LHS after promotions for computation
4174 QualType CompResultTy; // Type of computation result
Douglas Gregord7f915e2008-11-06 23:29:22 +00004175
4176 switch (Opc) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00004177 case BinaryOperator::Assign:
4178 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
4179 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00004180 case BinaryOperator::PtrMemD:
4181 case BinaryOperator::PtrMemI:
4182 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
4183 Opc == BinaryOperator::PtrMemI);
4184 break;
4185 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00004186 case BinaryOperator::Div:
4187 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
4188 break;
4189 case BinaryOperator::Rem:
4190 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
4191 break;
4192 case BinaryOperator::Add:
4193 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
4194 break;
4195 case BinaryOperator::Sub:
4196 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
4197 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00004198 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00004199 case BinaryOperator::Shr:
4200 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
4201 break;
4202 case BinaryOperator::LE:
4203 case BinaryOperator::LT:
4204 case BinaryOperator::GE:
4205 case BinaryOperator::GT:
Douglas Gregor1f12c352009-04-06 18:45:53 +00004206 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004207 break;
4208 case BinaryOperator::EQ:
4209 case BinaryOperator::NE:
Douglas Gregor1f12c352009-04-06 18:45:53 +00004210 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004211 break;
4212 case BinaryOperator::And:
4213 case BinaryOperator::Xor:
4214 case BinaryOperator::Or:
4215 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
4216 break;
4217 case BinaryOperator::LAnd:
4218 case BinaryOperator::LOr:
4219 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
4220 break;
4221 case BinaryOperator::MulAssign:
4222 case BinaryOperator::DivAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004223 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
4224 CompLHSTy = CompResultTy;
4225 if (!CompResultTy.isNull())
4226 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004227 break;
4228 case BinaryOperator::RemAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004229 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
4230 CompLHSTy = CompResultTy;
4231 if (!CompResultTy.isNull())
4232 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004233 break;
4234 case BinaryOperator::AddAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004235 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
4236 if (!CompResultTy.isNull())
4237 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004238 break;
4239 case BinaryOperator::SubAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004240 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
4241 if (!CompResultTy.isNull())
4242 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004243 break;
4244 case BinaryOperator::ShlAssign:
4245 case BinaryOperator::ShrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004246 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
4247 CompLHSTy = CompResultTy;
4248 if (!CompResultTy.isNull())
4249 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004250 break;
4251 case BinaryOperator::AndAssign:
4252 case BinaryOperator::XorAssign:
4253 case BinaryOperator::OrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004254 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
4255 CompLHSTy = CompResultTy;
4256 if (!CompResultTy.isNull())
4257 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004258 break;
4259 case BinaryOperator::Comma:
4260 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
4261 break;
4262 }
4263 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004264 return ExprError();
Eli Friedman3cd92882009-03-28 01:22:36 +00004265 if (CompResultTy.isNull())
Steve Naroff774e4152009-01-21 00:14:39 +00004266 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
4267 else
4268 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman3cd92882009-03-28 01:22:36 +00004269 CompLHSTy, CompResultTy,
4270 OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00004271}
4272
Chris Lattner4b009652007-07-25 00:24:17 +00004273// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004274Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
4275 tok::TokenKind Kind,
4276 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00004277 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004278 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00004279
Steve Naroff87d58b42007-09-16 03:34:24 +00004280 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
4281 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004282
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004283 if (getLangOptions().CPlusPlus &&
4284 (lhs->getType()->isOverloadableType() ||
4285 rhs->getType()->isOverloadableType())) {
4286 // Find all of the overloaded operators visible from this
4287 // point. We perform both an operator-name lookup from the local
4288 // scope and an argument-dependent lookup based on the types of
4289 // the arguments.
Douglas Gregor3fc092f2009-03-13 00:33:25 +00004290 FunctionSet Functions;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004291 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
4292 if (OverOp != OO_None) {
4293 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
4294 Functions);
4295 Expr *Args[2] = { lhs, rhs };
4296 DeclarationName OpName
4297 = Context.DeclarationNames.getCXXOperatorName(OverOp);
4298 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregor70d26122008-11-12 17:17:38 +00004299 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004300
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004301 // Build the (potentially-overloaded, potentially-dependent)
4302 // binary operation.
4303 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004304 }
4305
Douglas Gregord7f915e2008-11-06 23:29:22 +00004306 // Build a built-in binary operation.
4307 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00004308}
4309
Douglas Gregorc78182d2009-03-13 23:49:33 +00004310Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
4311 unsigned OpcIn,
4312 ExprArg InputArg) {
4313 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004314
Douglas Gregorc78182d2009-03-13 23:49:33 +00004315 // FIXME: Input is modified below, but InputArg is not updated
4316 // appropriately.
4317 Expr *Input = (Expr *)InputArg.get();
Chris Lattner4b009652007-07-25 00:24:17 +00004318 QualType resultType;
4319 switch (Opc) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00004320 case UnaryOperator::PostInc:
4321 case UnaryOperator::PostDec:
4322 case UnaryOperator::OffsetOf:
4323 assert(false && "Invalid unary operator");
4324 break;
4325
Chris Lattner4b009652007-07-25 00:24:17 +00004326 case UnaryOperator::PreInc:
4327 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004328 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4329 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00004330 break;
Mike Stump9afab102009-02-19 03:04:26 +00004331 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00004332 resultType = CheckAddressOfOperand(Input, OpLoc);
4333 break;
Mike Stump9afab102009-02-19 03:04:26 +00004334 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00004335 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00004336 resultType = CheckIndirectionOperand(Input, OpLoc);
4337 break;
4338 case UnaryOperator::Plus:
4339 case UnaryOperator::Minus:
4340 UsualUnaryConversions(Input);
4341 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004342 if (resultType->isDependentType())
4343 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004344 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4345 break;
4346 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4347 resultType->isEnumeralType())
4348 break;
4349 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4350 Opc == UnaryOperator::Plus &&
4351 resultType->isPointerType())
4352 break;
4353
Sebastian Redl8b769972009-01-19 00:08:26 +00004354 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4355 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004356 case UnaryOperator::Not: // bitwise complement
4357 UsualUnaryConversions(Input);
4358 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004359 if (resultType->isDependentType())
4360 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00004361 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4362 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4363 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00004364 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004365 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004366 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00004367 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4368 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004369 break;
4370 case UnaryOperator::LNot: // logical negation
4371 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4372 DefaultFunctionArrayConversion(Input);
4373 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004374 if (resultType->isDependentType())
4375 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004376 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004377 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4378 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004379 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004380 // In C++, it's bool. C++ 5.3.1p8
4381 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004382 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004383 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004384 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00004385 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00004386 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004387 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004388 resultType = Input->getType();
4389 break;
4390 }
4391 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004392 return ExprError();
Douglas Gregorc78182d2009-03-13 23:49:33 +00004393
4394 InputArg.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004395 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004396}
4397
Douglas Gregorc78182d2009-03-13 23:49:33 +00004398// Unary Operators. 'Tok' is the token for the operator.
4399Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4400 tok::TokenKind Op, ExprArg input) {
4401 Expr *Input = (Expr*)input.get();
4402 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
4403
4404 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
4405 // Find all of the overloaded operators visible from this
4406 // point. We perform both an operator-name lookup from the local
4407 // scope and an argument-dependent lookup based on the types of
4408 // the arguments.
4409 FunctionSet Functions;
4410 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
4411 if (OverOp != OO_None) {
4412 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
4413 Functions);
4414 DeclarationName OpName
4415 = Context.DeclarationNames.getCXXOperatorName(OverOp);
4416 ArgumentDependentLookup(OpName, &Input, 1, Functions);
4417 }
4418
4419 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
4420 }
4421
4422 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
4423}
4424
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004425/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004426Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
4427 SourceLocation LabLoc,
4428 IdentifierInfo *LabelII) {
Chris Lattner4b009652007-07-25 00:24:17 +00004429 // Look up the record for this label identifier.
Steve Naroffff9ecaf2009-03-13 16:03:38 +00004430 LabelStmt *&LabelDecl = CurBlock ? CurBlock->LabelMap[LabelII] :
4431 LabelMap[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00004432
Daniel Dunbar879788d2008-08-04 16:51:22 +00004433 // If we haven't seen this label yet, create a forward reference. It
4434 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffb88d81c2009-03-13 15:38:40 +00004435 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004436 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004437
Chris Lattner4b009652007-07-25 00:24:17 +00004438 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004439 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4440 Context.getPointerType(Context.VoidTy)));
Chris Lattner4b009652007-07-25 00:24:17 +00004441}
4442
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004443Sema::OwningExprResult
4444Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
4445 SourceLocation RPLoc) { // "({..})"
4446 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner4b009652007-07-25 00:24:17 +00004447 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4448 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4449
Eli Friedmanbc941e12009-01-24 23:09:00 +00004450 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4451 if (isFileScope) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004452 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmanbc941e12009-01-24 23:09:00 +00004453 }
4454
Chris Lattner4b009652007-07-25 00:24:17 +00004455 // FIXME: there are a variety of strange constraints to enforce here, for
4456 // example, it is not possible to goto into a stmt expression apparently.
4457 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00004458
Chris Lattner4b009652007-07-25 00:24:17 +00004459 // FIXME: the last statement in the compount stmt has its value used. We
4460 // should not warn about it being unused.
4461
4462 // If there are sub stmts in the compound stmt, take the type of the last one
4463 // as the type of the stmtexpr.
4464 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00004465
Chris Lattner200964f2008-07-26 19:51:01 +00004466 if (!Compound->body_empty()) {
4467 Stmt *LastStmt = Compound->body_back();
4468 // If LastStmt is a label, skip down through into the body.
4469 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4470 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00004471
Chris Lattner200964f2008-07-26 19:51:01 +00004472 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004473 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004474 }
Mike Stump9afab102009-02-19 03:04:26 +00004475
Eli Friedman2b128322009-03-23 00:24:07 +00004476 // FIXME: Check that expression type is complete/non-abstract; statement
4477 // expressions are not lvalues.
4478
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004479 substmt.release();
4480 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004481}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004482
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004483Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4484 SourceLocation BuiltinLoc,
4485 SourceLocation TypeLoc,
4486 TypeTy *argty,
4487 OffsetOfComponent *CompPtr,
4488 unsigned NumComponents,
4489 SourceLocation RPLoc) {
4490 // FIXME: This function leaks all expressions in the offset components on
4491 // error.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004492 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4493 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00004494
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004495 bool Dependent = ArgTy->isDependentType();
4496
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004497 // We must have at least one component that refers to the type, and the first
4498 // one is known to be a field designator. Verify that the ArgTy represents
4499 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004500 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004501 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump9afab102009-02-19 03:04:26 +00004502
Eli Friedman2b128322009-03-23 00:24:07 +00004503 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
4504 // with an incomplete type would be illegal.
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00004505
Eli Friedman342d9432009-02-27 06:44:11 +00004506 // Otherwise, create a null pointer as the base, and iteratively process
4507 // the offsetof designators.
4508 QualType ArgTyPtr = Context.getPointerType(ArgTy);
4509 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004510 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman342d9432009-02-27 06:44:11 +00004511 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004512
Chris Lattnerb37522e2007-08-31 21:49:13 +00004513 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4514 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00004515 // FIXME: This diagnostic isn't actually visible because the location is in
4516 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00004517 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004518 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4519 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00004520
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004521 if (!Dependent) {
4522 // FIXME: Dependent case loses a lot of information here. And probably
4523 // leaks like a sieve.
4524 for (unsigned i = 0; i != NumComponents; ++i) {
4525 const OffsetOfComponent &OC = CompPtr[i];
4526 if (OC.isBrackets) {
4527 // Offset of an array sub-field. TODO: Should we allow vector elements?
4528 const ArrayType *AT = Context.getAsArrayType(Res->getType());
4529 if (!AT) {
4530 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004531 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
4532 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004533 }
4534
4535 // FIXME: C++: Verify that operator[] isn't overloaded.
4536
Eli Friedman342d9432009-02-27 06:44:11 +00004537 // Promote the array so it looks more like a normal array subscript
4538 // expression.
4539 DefaultFunctionArrayConversion(Res);
4540
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004541 // C99 6.5.2.1p1
4542 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004543 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004544 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004545 return ExprError(Diag(Idx->getLocStart(),
4546 diag::err_typecheck_subscript)
4547 << Idx->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004548
4549 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4550 OC.LocEnd);
4551 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004552 }
Mike Stump9afab102009-02-19 03:04:26 +00004553
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004554 const RecordType *RC = Res->getType()->getAsRecordType();
4555 if (!RC) {
4556 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004557 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
4558 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004559 }
Chris Lattner2af6a802007-08-30 17:59:59 +00004560
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004561 // Get the decl corresponding to this.
4562 RecordDecl *RD = RC->getDecl();
4563 FieldDecl *MemberDecl
4564 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4565 LookupMemberName)
4566 .getAsDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004567 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004568 if (!MemberDecl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004569 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
4570 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump9afab102009-02-19 03:04:26 +00004571
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004572 // FIXME: C++: Verify that MemberDecl isn't a static field.
4573 // FIXME: Verify that MemberDecl isn't a bitfield.
4574 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4575 // matter here.
4576 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
Steve Naroff774e4152009-01-21 00:14:39 +00004577 MemberDecl->getType().getNonReferenceType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004578 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004579 }
Mike Stump9afab102009-02-19 03:04:26 +00004580
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004581 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4582 Context.getSizeType(), BuiltinLoc));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004583}
4584
4585
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004586Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
4587 TypeTy *arg1,TypeTy *arg2,
4588 SourceLocation RPLoc) {
Steve Naroff63bad2d2007-08-01 22:05:33 +00004589 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4590 QualType argT2 = QualType::getFromOpaquePtr(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00004591
Steve Naroff63bad2d2007-08-01 22:05:33 +00004592 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00004593
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004594 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
4595 argT1, argT2, RPLoc));
Steve Naroff63bad2d2007-08-01 22:05:33 +00004596}
4597
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004598Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
4599 ExprArg cond,
4600 ExprArg expr1, ExprArg expr2,
4601 SourceLocation RPLoc) {
4602 Expr *CondExpr = static_cast<Expr*>(cond.get());
4603 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
4604 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump9afab102009-02-19 03:04:26 +00004605
Steve Naroff93c53012007-08-03 21:21:27 +00004606 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4607
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004608 QualType resType;
4609 if (CondExpr->isValueDependent()) {
4610 resType = Context.DependentTy;
4611 } else {
4612 // The conditional expression is required to be a constant expression.
4613 llvm::APSInt condEval(32);
4614 SourceLocation ExpLoc;
4615 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004616 return ExprError(Diag(ExpLoc,
4617 diag::err_typecheck_choose_expr_requires_constant)
4618 << CondExpr->getSourceRange());
Steve Naroff93c53012007-08-03 21:21:27 +00004619
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004620 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4621 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
4622 }
4623
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004624 cond.release(); expr1.release(); expr2.release();
4625 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4626 resType, RPLoc));
Steve Naroff93c53012007-08-03 21:21:27 +00004627}
4628
Steve Naroff52a81c02008-09-03 18:15:37 +00004629//===----------------------------------------------------------------------===//
4630// Clang Extensions.
4631//===----------------------------------------------------------------------===//
4632
4633/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004634void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004635 // Analyze block parameters.
4636 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00004637
Steve Naroff52a81c02008-09-03 18:15:37 +00004638 // Add BSI to CurBlock.
4639 BSI->PrevBlockInfo = CurBlock;
4640 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00004641
Steve Naroff52a81c02008-09-03 18:15:37 +00004642 BSI->ReturnType = 0;
4643 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00004644 BSI->hasBlockDeclRefExprs = false;
Mike Stump9afab102009-02-19 03:04:26 +00004645
Steve Naroff52059382008-10-10 01:28:17 +00004646 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004647 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004648}
4649
Mike Stumpc1fddff2009-02-04 22:31:32 +00004650void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4651 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4652
4653 if (ParamInfo.getNumTypeObjects() == 0
4654 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4655 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4656
4657 // The type is entirely optional as well, if none, use DependentTy.
4658 if (T.isNull())
4659 T = Context.DependentTy;
4660
4661 // The parameter list is optional, if there was none, assume ().
4662 if (!T->isFunctionType())
4663 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4664
4665 CurBlock->hasPrototype = true;
4666 CurBlock->isVariadic = false;
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00004667
4668 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
4669
4670 // Do not allow returning a objc interface by-value.
4671 if (RetTy->isObjCInterfaceType()) {
4672 Diag(ParamInfo.getSourceRange().getBegin(),
4673 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
4674 return;
4675 }
Mike Stumpc1fddff2009-02-04 22:31:32 +00004676
4677 if (!RetTy->isDependentType())
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00004678 CurBlock->ReturnType = RetTy.getTypePtr();
Mike Stumpc1fddff2009-02-04 22:31:32 +00004679 return;
4680 }
4681
Steve Naroff52a81c02008-09-03 18:15:37 +00004682 // Analyze arguments to block.
4683 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4684 "Not a function declarator!");
4685 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00004686
Steve Naroff52059382008-10-10 01:28:17 +00004687 CurBlock->hasPrototype = FTI.hasPrototype;
4688 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00004689
Steve Naroff52a81c02008-09-03 18:15:37 +00004690 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4691 // no arguments, not a function that takes a single void argument.
4692 if (FTI.hasPrototype &&
4693 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner5261d0c2009-03-28 19:18:32 +00004694 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
4695 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004696 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004697 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004698 } else if (FTI.hasPrototype) {
4699 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner5261d0c2009-03-28 19:18:32 +00004700 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff52059382008-10-10 01:28:17 +00004701 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00004702 }
Steve Naroff494cb0f2009-03-13 16:56:44 +00004703 CurBlock->TheDecl->setParams(Context, &CurBlock->Params[0],
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00004704 CurBlock->Params.size());
Mike Stump9afab102009-02-19 03:04:26 +00004705
Steve Naroff52059382008-10-10 01:28:17 +00004706 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4707 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4708 // If this has an identifier, add it to the scope stack.
4709 if ((*AI)->getIdentifier())
4710 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00004711
4712 // Analyze the return type.
4713 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4714 QualType RetTy = T->getAsFunctionType()->getResultType();
4715
4716 // Do not allow returning a objc interface by-value.
4717 if (RetTy->isObjCInterfaceType()) {
4718 Diag(ParamInfo.getSourceRange().getBegin(),
4719 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
4720 } else if (!RetTy->isDependentType())
4721 CurBlock->ReturnType = RetTy.getTypePtr();
Steve Naroff52a81c02008-09-03 18:15:37 +00004722}
4723
4724/// ActOnBlockError - If there is an error parsing a block, this callback
4725/// is invoked to pop the information about the block from the action impl.
4726void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4727 // Ensure that CurBlock is deleted.
4728 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00004729
Steve Naroff52a81c02008-09-03 18:15:37 +00004730 // Pop off CurBlock, handle nested blocks.
4731 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004732
Steve Naroff52a81c02008-09-03 18:15:37 +00004733 // FIXME: Delete the ParmVarDecl objects as well???
Douglas Gregorc1408ea2009-03-11 23:54:15 +00004734
Steve Naroff52a81c02008-09-03 18:15:37 +00004735}
4736
4737/// ActOnBlockStmtExpr - This is called when the body of a block statement
4738/// literal was successfully completed. ^(int x){...}
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004739Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
4740 StmtArg body, Scope *CurScope) {
Chris Lattnerc14c7f02009-03-27 04:18:06 +00004741 // If blocks are disabled, emit an error.
4742 if (!LangOpts.Blocks)
4743 Diag(CaretLoc, diag::err_blocks_disable);
4744
Steve Naroff52a81c02008-09-03 18:15:37 +00004745 // Ensure that CurBlock is deleted.
4746 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff52a81c02008-09-03 18:15:37 +00004747
Steve Naroff52059382008-10-10 01:28:17 +00004748 PopDeclContext();
4749
Steve Naroff52a81c02008-09-03 18:15:37 +00004750 // Pop off CurBlock, handle nested blocks.
4751 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004752
Steve Naroff52a81c02008-09-03 18:15:37 +00004753 QualType RetTy = Context.VoidTy;
4754 if (BSI->ReturnType)
4755 RetTy = QualType(BSI->ReturnType, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004756
Steve Naroff52a81c02008-09-03 18:15:37 +00004757 llvm::SmallVector<QualType, 8> ArgTypes;
4758 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4759 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00004760
Steve Naroff52a81c02008-09-03 18:15:37 +00004761 QualType BlockTy;
4762 if (!BSI->hasPrototype)
Douglas Gregor4fa58902009-02-26 23:50:07 +00004763 BlockTy = Context.getFunctionNoProtoType(RetTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004764 else
4765 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004766 BSI->isVariadic, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004767
Eli Friedman2b128322009-03-23 00:24:07 +00004768 // FIXME: Check that return/parameter types are complete/non-abstract
4769
Steve Naroff52a81c02008-09-03 18:15:37 +00004770 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00004771
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004772 BSI->TheDecl->setBody(static_cast<CompoundStmt*>(body.release()));
4773 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
4774 BSI->hasBlockDeclRefExprs));
Steve Naroff52a81c02008-09-03 18:15:37 +00004775}
4776
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004777Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4778 ExprArg expr, TypeTy *type,
4779 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004780 QualType T = QualType::getFromOpaquePtr(type);
Chris Lattnerda139482009-04-05 15:49:53 +00004781 Expr *E = static_cast<Expr*>(expr.get());
4782 Expr *OrigExpr = E;
4783
Anders Carlsson36760332007-10-15 20:28:48 +00004784 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004785
4786 // Get the va_list type
4787 QualType VaListType = Context.getBuiltinVaListType();
4788 // Deal with implicit array decay; for example, on x86-64,
4789 // va_list is an array, but it's supposed to decay to
4790 // a pointer for va_arg.
4791 if (VaListType->isArrayType())
4792 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004793 // Make sure the input expression also decays appropriately.
4794 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004795
Chris Lattnercb9469d2009-04-06 17:07:34 +00004796 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004797 return ExprError(Diag(E->getLocStart(),
4798 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerda139482009-04-05 15:49:53 +00004799 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner89a72c52009-04-05 00:59:53 +00004800 }
Mike Stump9afab102009-02-19 03:04:26 +00004801
Eli Friedman2b128322009-03-23 00:24:07 +00004802 // FIXME: Check that type is complete/non-abstract
Anders Carlsson36760332007-10-15 20:28:48 +00004803 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00004804
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004805 expr.release();
4806 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
4807 RPLoc));
Anders Carlsson36760332007-10-15 20:28:48 +00004808}
4809
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004810Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregorad4b3792008-11-29 04:51:27 +00004811 // The type of __null will be int or long, depending on the size of
4812 // pointers on the target.
4813 QualType Ty;
4814 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4815 Ty = Context.IntTy;
4816 else
4817 Ty = Context.LongTy;
4818
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004819 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregorad4b3792008-11-29 04:51:27 +00004820}
4821
Chris Lattner005ed752008-01-04 18:04:52 +00004822bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4823 SourceLocation Loc,
4824 QualType DstType, QualType SrcType,
4825 Expr *SrcExpr, const char *Flavor) {
4826 // Decode the result (notice that AST's are still created for extensions).
4827 bool isInvalid = false;
4828 unsigned DiagKind;
4829 switch (ConvTy) {
4830 default: assert(0 && "Unknown conversion type");
4831 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004832 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004833 DiagKind = diag::ext_typecheck_convert_pointer_int;
4834 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004835 case IntToPointer:
4836 DiagKind = diag::ext_typecheck_convert_int_pointer;
4837 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004838 case IncompatiblePointer:
4839 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4840 break;
Eli Friedman6ca28cb2009-03-22 23:59:44 +00004841 case IncompatiblePointerSign:
4842 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
4843 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004844 case FunctionVoidPointer:
4845 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4846 break;
4847 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004848 // If the qualifiers lost were because we were applying the
4849 // (deprecated) C++ conversion from a string literal to a char*
4850 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4851 // Ideally, this check would be performed in
4852 // CheckPointerTypesForAssignment. However, that would require a
4853 // bit of refactoring (so that the second argument is an
4854 // expression, rather than a type), which should be done as part
4855 // of a larger effort to fix CheckPointerTypesForAssignment for
4856 // C++ semantics.
4857 if (getLangOptions().CPlusPlus &&
4858 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4859 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004860 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4861 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004862 case IntToBlockPointer:
4863 DiagKind = diag::err_int_to_block_pointer;
4864 break;
4865 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004866 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004867 break;
Steve Naroff19608432008-10-14 22:18:38 +00004868 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00004869 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00004870 // it can give a more specific diagnostic.
4871 DiagKind = diag::warn_incompatible_qualified_id;
4872 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004873 case IncompatibleVectors:
4874 DiagKind = diag::warn_incompatible_vectors;
4875 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004876 case Incompatible:
4877 DiagKind = diag::err_typecheck_convert_incompatible;
4878 isInvalid = true;
4879 break;
4880 }
Mike Stump9afab102009-02-19 03:04:26 +00004881
Chris Lattner271d4c22008-11-24 05:29:24 +00004882 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4883 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004884 return isInvalid;
4885}
Anders Carlssond5201b92008-11-30 19:50:32 +00004886
4887bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4888{
4889 Expr::EvalResult EvalResult;
4890
Mike Stump9afab102009-02-19 03:04:26 +00004891 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00004892 EvalResult.HasSideEffects) {
4893 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4894
4895 if (EvalResult.Diag) {
4896 // We only show the note if it's not the usual "invalid subexpression"
4897 // or if it's actually in a subexpression.
4898 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4899 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4900 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4901 }
Mike Stump9afab102009-02-19 03:04:26 +00004902
Anders Carlssond5201b92008-11-30 19:50:32 +00004903 return true;
4904 }
4905
4906 if (EvalResult.Diag) {
Mike Stump9afab102009-02-19 03:04:26 +00004907 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
Anders Carlssond5201b92008-11-30 19:50:32 +00004908 E->getSourceRange();
4909
4910 // Print the reason it's not a constant.
4911 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4912 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4913 }
Mike Stump9afab102009-02-19 03:04:26 +00004914
Anders Carlssond5201b92008-11-30 19:50:32 +00004915 if (Result)
4916 *Result = EvalResult.Val.getInt();
4917 return false;
4918}