blob: 0dc3b87d524274680e3be2f26c5b1faa85d5c526 [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;
Chris Lattner79e9a422009-04-12 09:02:39 +00003063 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003064 }
3065
3066 // FIXME: Currently, we fall through and treat C++ classes like C
3067 // structures.
3068 }
3069
Steve Naroffcdee22d2007-11-27 17:58:44 +00003070 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3071 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00003072 if ((lhsType->isPointerType() ||
3073 lhsType->isObjCQualifiedIdType() ||
Mike Stump9afab102009-02-19 03:04:26 +00003074 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00003075 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003076 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00003077 return Compatible;
3078 }
Mike Stump9afab102009-02-19 03:04:26 +00003079
Chris Lattner5f505bf2007-10-16 02:55:40 +00003080 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00003081 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00003082 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00003083 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00003084 //
Mike Stump9afab102009-02-19 03:04:26 +00003085 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00003086 if (!lhsType->isReferenceType())
3087 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00003088
Chris Lattner005ed752008-01-04 18:04:52 +00003089 Sema::AssignConvertType result =
3090 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00003091
Steve Naroff0f32f432007-08-24 22:33:52 +00003092 // C99 6.5.16.1p2: The value of the right operand is converted to the
3093 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003094 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3095 // so that we can use references in built-in functions even in C.
3096 // The getNonReferenceType() call makes sure that the resulting expression
3097 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00003098 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003099 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00003100 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00003101}
3102
Chris Lattner005ed752008-01-04 18:04:52 +00003103Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003104Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
3105 return CheckAssignmentConstraints(lhsType, rhsType);
3106}
3107
Chris Lattner1eafdea2008-11-18 01:30:42 +00003108QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003109 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003110 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003111 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00003112 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003113}
3114
Mike Stump9afab102009-02-19 03:04:26 +00003115inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00003116 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00003117 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00003118 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003119 QualType lhsType =
3120 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3121 QualType rhsType =
3122 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00003123
Nate Begemanc5f0f652008-07-14 18:02:46 +00003124 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00003125 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00003126 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00003127
Nate Begemanc5f0f652008-07-14 18:02:46 +00003128 // Handle the case of a vector & extvector type of the same size and element
3129 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00003130 if (getLangOptions().LaxVectorConversions) {
3131 // FIXME: Should we warn here?
3132 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003133 if (const VectorType *RV = rhsType->getAsVectorType())
3134 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00003135 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003136 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00003137 }
3138 }
3139 }
Mike Stump9afab102009-02-19 03:04:26 +00003140
Nate Begemanc5f0f652008-07-14 18:02:46 +00003141 // If the lhs is an extended vector and the rhs is a scalar of the same type
3142 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00003143 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003144 QualType eltType = V->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00003145
3146 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00003147 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
3148 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003149 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00003150 return lhsType;
3151 }
3152 }
3153
Nate Begemanc5f0f652008-07-14 18:02:46 +00003154 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00003155 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00003156 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003157 QualType eltType = V->getElementType();
3158
Mike Stump9afab102009-02-19 03:04:26 +00003159 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00003160 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
3161 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003162 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00003163 return rhsType;
3164 }
3165 }
3166
Chris Lattner4b009652007-07-25 00:24:17 +00003167 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00003168 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003169 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003170 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003171 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00003172}
3173
Chris Lattner4b009652007-07-25 00:24:17 +00003174inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003175 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003176{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00003177 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003178 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003179
Steve Naroff8f708362007-08-24 19:07:16 +00003180 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003181
Chris Lattner4b009652007-07-25 00:24:17 +00003182 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00003183 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003184 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003185}
3186
3187inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003188 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003189{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00003190 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3191 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3192 return CheckVectorOperands(Loc, lex, rex);
3193 return InvalidOperands(Loc, lex, rex);
3194 }
Chris Lattner4b009652007-07-25 00:24:17 +00003195
Steve Naroff8f708362007-08-24 19:07:16 +00003196 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003197
Chris Lattner4b009652007-07-25 00:24:17 +00003198 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003199 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003200 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003201}
3202
3203inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Eli Friedman3cd92882009-03-28 01:22:36 +00003204 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
Chris Lattner4b009652007-07-25 00:24:17 +00003205{
Eli Friedman3cd92882009-03-28 01:22:36 +00003206 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3207 QualType compType = CheckVectorOperands(Loc, lex, rex);
3208 if (CompLHSTy) *CompLHSTy = compType;
3209 return compType;
3210 }
Chris Lattner4b009652007-07-25 00:24:17 +00003211
Eli Friedman3cd92882009-03-28 01:22:36 +00003212 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003213
Chris Lattner4b009652007-07-25 00:24:17 +00003214 // handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00003215 if (lex->getType()->isArithmeticType() &&
3216 rex->getType()->isArithmeticType()) {
3217 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00003218 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00003219 }
Chris Lattner4b009652007-07-25 00:24:17 +00003220
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003221 // Put any potential pointer into PExp
3222 Expr* PExp = lex, *IExp = rex;
3223 if (IExp->getType()->isPointerType())
3224 std::swap(PExp, IExp);
3225
3226 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
3227 if (IExp->getType()->isIntegerType()) {
3228 // Check for arithmetic on pointers to incomplete types
Douglas Gregor05e28f62009-03-24 19:52:54 +00003229 if (PTy->getPointeeType()->isVoidType()) {
3230 if (getLangOptions().CPlusPlus) {
3231 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner8ba580c2008-11-19 05:08:23 +00003232 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003233 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003234 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003235
3236 // GNU extension: arithmetic on pointer to void
3237 Diag(Loc, diag::ext_gnu_void_ptr)
3238 << lex->getSourceRange() << rex->getSourceRange();
3239 } else if (PTy->getPointeeType()->isFunctionType()) {
3240 if (getLangOptions().CPlusPlus) {
3241 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3242 << lex->getType() << lex->getSourceRange();
3243 return QualType();
3244 }
3245
3246 // GNU extension: arithmetic on pointer to function
3247 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3248 << lex->getType() << lex->getSourceRange();
3249 } else if (!PTy->isDependentType() &&
3250 RequireCompleteType(Loc, PTy->getPointeeType(),
3251 diag::err_typecheck_arithmetic_incomplete_type,
3252 lex->getSourceRange(), SourceRange(),
3253 lex->getType()))
3254 return QualType();
3255
Eli Friedman3cd92882009-03-28 01:22:36 +00003256 if (CompLHSTy) {
3257 QualType LHSTy = lex->getType();
3258 if (LHSTy->isPromotableIntegerType())
3259 LHSTy = Context.IntTy;
3260 *CompLHSTy = LHSTy;
3261 }
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003262 return PExp->getType();
3263 }
3264 }
3265
Chris Lattner1eafdea2008-11-18 01:30:42 +00003266 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003267}
3268
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003269// C99 6.5.6
3270QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman3cd92882009-03-28 01:22:36 +00003271 SourceLocation Loc, QualType* CompLHSTy) {
3272 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3273 QualType compType = CheckVectorOperands(Loc, lex, rex);
3274 if (CompLHSTy) *CompLHSTy = compType;
3275 return compType;
3276 }
Mike Stump9afab102009-02-19 03:04:26 +00003277
Eli Friedman3cd92882009-03-28 01:22:36 +00003278 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump9afab102009-02-19 03:04:26 +00003279
Chris Lattnerf6da2912007-12-09 21:53:25 +00003280 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00003281
Chris Lattnerf6da2912007-12-09 21:53:25 +00003282 // Handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00003283 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) {
3284 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00003285 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00003286 }
Mike Stump9afab102009-02-19 03:04:26 +00003287
Chris Lattnerf6da2912007-12-09 21:53:25 +00003288 // Either ptr - int or ptr - ptr.
3289 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00003290 QualType lpointee = LHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003291
Douglas Gregor05e28f62009-03-24 19:52:54 +00003292 // The LHS must be an completely-defined object type.
Douglas Gregorb3193242009-01-23 00:36:41 +00003293
Douglas Gregor05e28f62009-03-24 19:52:54 +00003294 bool ComplainAboutVoid = false;
3295 Expr *ComplainAboutFunc = 0;
3296 if (lpointee->isVoidType()) {
3297 if (getLangOptions().CPlusPlus) {
3298 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3299 << lex->getSourceRange() << rex->getSourceRange();
3300 return QualType();
3301 }
3302
3303 // GNU C extension: arithmetic on pointer to void
3304 ComplainAboutVoid = true;
3305 } else if (lpointee->isFunctionType()) {
3306 if (getLangOptions().CPlusPlus) {
3307 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003308 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003309 return QualType();
3310 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003311
3312 // GNU C extension: arithmetic on pointer to function
3313 ComplainAboutFunc = lex;
3314 } else if (!lpointee->isDependentType() &&
3315 RequireCompleteType(Loc, lpointee,
3316 diag::err_typecheck_sub_ptr_object,
3317 lex->getSourceRange(),
3318 SourceRange(),
3319 lex->getType()))
3320 return QualType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003321
3322 // The result type of a pointer-int computation is the pointer type.
Douglas Gregor05e28f62009-03-24 19:52:54 +00003323 if (rex->getType()->isIntegerType()) {
3324 if (ComplainAboutVoid)
3325 Diag(Loc, diag::ext_gnu_void_ptr)
3326 << lex->getSourceRange() << rex->getSourceRange();
3327 if (ComplainAboutFunc)
3328 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3329 << ComplainAboutFunc->getType()
3330 << ComplainAboutFunc->getSourceRange();
3331
Eli Friedman3cd92882009-03-28 01:22:36 +00003332 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003333 return lex->getType();
Douglas Gregor05e28f62009-03-24 19:52:54 +00003334 }
Mike Stump9afab102009-02-19 03:04:26 +00003335
Chris Lattnerf6da2912007-12-09 21:53:25 +00003336 // Handle pointer-pointer subtractions.
3337 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00003338 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003339
Douglas Gregor05e28f62009-03-24 19:52:54 +00003340 // RHS must be a completely-type object type.
3341 // Handle the GNU void* extension.
3342 if (rpointee->isVoidType()) {
3343 if (getLangOptions().CPlusPlus) {
3344 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3345 << lex->getSourceRange() << rex->getSourceRange();
3346 return QualType();
3347 }
Mike Stump9afab102009-02-19 03:04:26 +00003348
Douglas Gregor05e28f62009-03-24 19:52:54 +00003349 ComplainAboutVoid = true;
3350 } else if (rpointee->isFunctionType()) {
3351 if (getLangOptions().CPlusPlus) {
3352 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003353 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003354 return QualType();
3355 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003356
3357 // GNU extension: arithmetic on pointer to function
3358 if (!ComplainAboutFunc)
3359 ComplainAboutFunc = rex;
3360 } else if (!rpointee->isDependentType() &&
3361 RequireCompleteType(Loc, rpointee,
3362 diag::err_typecheck_sub_ptr_object,
3363 rex->getSourceRange(),
3364 SourceRange(),
3365 rex->getType()))
3366 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00003367
Chris Lattnerf6da2912007-12-09 21:53:25 +00003368 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00003369 if (!Context.typesAreCompatible(
Mike Stump9afab102009-02-19 03:04:26 +00003370 Context.getCanonicalType(lpointee).getUnqualifiedType(),
Eli Friedman583c31e2008-09-02 05:09:35 +00003371 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003372 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003373 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003374 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003375 return QualType();
3376 }
Mike Stump9afab102009-02-19 03:04:26 +00003377
Douglas Gregor05e28f62009-03-24 19:52:54 +00003378 if (ComplainAboutVoid)
3379 Diag(Loc, diag::ext_gnu_void_ptr)
3380 << lex->getSourceRange() << rex->getSourceRange();
3381 if (ComplainAboutFunc)
3382 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3383 << ComplainAboutFunc->getType()
3384 << ComplainAboutFunc->getSourceRange();
Eli Friedman3cd92882009-03-28 01:22:36 +00003385
3386 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003387 return Context.getPointerDiffType();
3388 }
3389 }
Mike Stump9afab102009-02-19 03:04:26 +00003390
Chris Lattner1eafdea2008-11-18 01:30:42 +00003391 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003392}
3393
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003394// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00003395QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003396 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00003397 // C99 6.5.7p2: Each of the operands shall have integer type.
3398 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003399 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003400
Chris Lattner2c8bff72007-12-12 05:47:28 +00003401 // Shifts don't perform usual arithmetic conversions, they just do integer
3402 // promotions on each operand. C99 6.5.7p3
Eli Friedman3cd92882009-03-28 01:22:36 +00003403 QualType LHSTy;
3404 if (lex->getType()->isPromotableIntegerType())
3405 LHSTy = Context.IntTy;
3406 else
3407 LHSTy = lex->getType();
Chris Lattnerbb19bc42007-12-13 07:28:16 +00003408 if (!isCompAssign)
Eli Friedman3cd92882009-03-28 01:22:36 +00003409 ImpCastExprToType(lex, LHSTy);
3410
Chris Lattner2c8bff72007-12-12 05:47:28 +00003411 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003412
Chris Lattner2c8bff72007-12-12 05:47:28 +00003413 // "The type of the result is that of the promoted left operand."
Eli Friedman3cd92882009-03-28 01:22:36 +00003414 return LHSTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003415}
3416
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003417// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00003418QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor1f12c352009-04-06 18:45:53 +00003419 unsigned OpaqueOpc, bool isRelational) {
3420 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
3421
Nate Begemanc5f0f652008-07-14 18:02:46 +00003422 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003423 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00003424
Chris Lattner254f3bc2007-08-26 01:18:55 +00003425 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00003426 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3427 UsualArithmeticConversions(lex, rex);
3428 else {
3429 UsualUnaryConversions(lex);
3430 UsualUnaryConversions(rex);
3431 }
Chris Lattner4b009652007-07-25 00:24:17 +00003432 QualType lType = lex->getType();
3433 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003434
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003435 if (!lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00003436 // For non-floating point types, check for self-comparisons of the form
3437 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3438 // often indicate logic errors in the program.
Ted Kremenek264b5cb2009-03-20 19:57:37 +00003439 // NOTE: Don't warn about comparisons of enum constants. These can arise
3440 // from macro expansions, and are usually quite deliberate.
Chris Lattner4e479f92009-03-08 19:39:53 +00003441 Expr *LHSStripped = lex->IgnoreParens();
3442 Expr *RHSStripped = rex->IgnoreParens();
3443 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
3444 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekf042dc62009-03-20 18:35:45 +00003445 if (DRL->getDecl() == DRR->getDecl() &&
3446 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump9afab102009-02-19 03:04:26 +00003447 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner4e479f92009-03-08 19:39:53 +00003448
3449 if (isa<CastExpr>(LHSStripped))
3450 LHSStripped = LHSStripped->IgnoreParenCasts();
3451 if (isa<CastExpr>(RHSStripped))
3452 RHSStripped = RHSStripped->IgnoreParenCasts();
3453
3454 // Warn about comparisons against a string constant (unless the other
3455 // operand is null), the user probably wants strcmp.
Douglas Gregor1f12c352009-04-06 18:45:53 +00003456 Expr *literalString = 0;
3457 Expr *literalStringStripped = 0;
Chris Lattner4e479f92009-03-08 19:39:53 +00003458 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00003459 !RHSStripped->isNullPointerConstant(Context)) {
3460 literalString = lex;
3461 literalStringStripped = LHSStripped;
3462 }
Chris Lattner4e479f92009-03-08 19:39:53 +00003463 else if ((isa<StringLiteral>(RHSStripped) ||
3464 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00003465 !LHSStripped->isNullPointerConstant(Context)) {
3466 literalString = rex;
3467 literalStringStripped = RHSStripped;
3468 }
3469
3470 if (literalString) {
3471 std::string resultComparison;
3472 switch (Opc) {
3473 case BinaryOperator::LT: resultComparison = ") < 0"; break;
3474 case BinaryOperator::GT: resultComparison = ") > 0"; break;
3475 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
3476 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
3477 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
3478 case BinaryOperator::NE: resultComparison = ") != 0"; break;
3479 default: assert(false && "Invalid comparison operator");
3480 }
3481 Diag(Loc, diag::warn_stringcompare)
3482 << isa<ObjCEncodeExpr>(literalStringStripped)
3483 << literalString->getSourceRange()
Douglas Gregor3faaa812009-04-01 23:51:29 +00003484 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
3485 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
3486 "strcmp(")
3487 << CodeModificationHint::CreateInsertion(
3488 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor1f12c352009-04-06 18:45:53 +00003489 resultComparison);
3490 }
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003491 }
Mike Stump9afab102009-02-19 03:04:26 +00003492
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003493 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner4e479f92009-03-08 19:39:53 +00003494 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003495
Chris Lattner254f3bc2007-08-26 01:18:55 +00003496 if (isRelational) {
3497 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003498 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003499 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00003500 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00003501 if (lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00003502 assert(rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003503 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00003504 }
Mike Stump9afab102009-02-19 03:04:26 +00003505
Chris Lattner254f3bc2007-08-26 01:18:55 +00003506 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003507 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003508 }
Mike Stump9afab102009-02-19 03:04:26 +00003509
Chris Lattner22be8422007-08-26 01:10:14 +00003510 bool LHSIsNull = lex->isNullPointerConstant(Context);
3511 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00003512
Chris Lattner254f3bc2007-08-26 01:18:55 +00003513 // All of the following pointer related warnings are GCC extensions, except
3514 // when handling null pointer constants. One day, we can consider making them
3515 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00003516 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003517 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003518 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00003519 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003520 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00003521
Steve Naroff3b435622007-11-13 14:57:38 +00003522 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003523 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3524 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00003525 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00003526 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003527 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003528 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003529 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003530 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003531 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003532 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003533 // Handle block pointer types.
3534 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3535 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3536 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003537
Steve Naroff3454b6c2008-09-04 15:10:53 +00003538 if (!LHSIsNull && !RHSIsNull &&
3539 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003540 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003541 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003542 }
3543 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003544 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003545 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003546 // Allow block pointers to be compared with null pointer constants.
3547 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3548 (lType->isPointerType() && rType->isBlockPointerType())) {
3549 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003550 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003551 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003552 }
3553 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003554 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003555 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003556
Steve Naroff936c4362008-06-03 14:04:54 +00003557 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003558 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003559 const PointerType *LPT = lType->getAsPointerType();
3560 const PointerType *RPT = rType->getAsPointerType();
Mike Stump9afab102009-02-19 03:04:26 +00003561 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003562 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003563 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003564 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003565
Steve Naroff030fcda2008-11-17 19:49:16 +00003566 if (!LPtrToVoid && !RPtrToVoid &&
3567 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003568 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003569 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003570 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003571 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003572 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003573 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003574 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003575 }
Steve Naroff936c4362008-06-03 14:04:54 +00003576 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3577 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003578 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003579 } else {
3580 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003581 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003582 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003583 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003584 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003585 }
Steve Naroff936c4362008-06-03 14:04:54 +00003586 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003587 }
Mike Stump9afab102009-02-19 03:04:26 +00003588 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
Steve Naroff936c4362008-06-03 14:04:54 +00003589 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003590 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003591 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003592 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003593 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003594 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003595 }
Mike Stump9afab102009-02-19 03:04:26 +00003596 if (lType->isIntegerType() &&
Steve Naroff936c4362008-06-03 14:04:54 +00003597 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003598 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003599 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003600 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003601 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003602 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003603 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003604 // Handle block pointers.
3605 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3606 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003607 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003608 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003609 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003610 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003611 }
3612 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3613 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003614 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003615 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003616 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003617 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003618 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003619 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003620}
3621
Nate Begemanc5f0f652008-07-14 18:02:46 +00003622/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00003623/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003624/// like a scalar comparison, a vector comparison produces a vector of integer
3625/// types.
3626QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003627 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003628 bool isRelational) {
3629 // Check to make sure we're operating on vectors of the same type and width,
3630 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003631 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003632 if (vType.isNull())
3633 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00003634
Nate Begemanc5f0f652008-07-14 18:02:46 +00003635 QualType lType = lex->getType();
3636 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003637
Nate Begemanc5f0f652008-07-14 18:02:46 +00003638 // For non-floating point types, check for self-comparisons of the form
3639 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3640 // often indicate logic errors in the program.
3641 if (!lType->isFloatingType()) {
3642 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3643 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3644 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003645 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003646 }
Mike Stump9afab102009-02-19 03:04:26 +00003647
Nate Begemanc5f0f652008-07-14 18:02:46 +00003648 // Check for comparisons of floating point operands using != and ==.
3649 if (!isRelational && lType->isFloatingType()) {
3650 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003651 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003652 }
Mike Stump9afab102009-02-19 03:04:26 +00003653
Chris Lattner10687e32009-03-31 07:46:52 +00003654 // FIXME: Vector compare support in the LLVM backend is not fully reliable,
3655 // just reject all vector comparisons for now.
3656 if (1) {
3657 Diag(Loc, diag::err_typecheck_vector_comparison)
3658 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3659 return QualType();
3660 }
3661
Nate Begemanc5f0f652008-07-14 18:02:46 +00003662 // Return the type for the comparison, which is the same as vector type for
3663 // integer vectors, or an integer type of identical size and number of
3664 // elements for floating point vectors.
3665 if (lType->isIntegerType())
3666 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00003667
Nate Begemanc5f0f652008-07-14 18:02:46 +00003668 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003669 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003670 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003671 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner10687e32009-03-31 07:46:52 +00003672 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begemand6d2f772009-01-18 03:20:47 +00003673 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3674
Mike Stump9afab102009-02-19 03:04:26 +00003675 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00003676 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003677 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3678}
3679
Chris Lattner4b009652007-07-25 00:24:17 +00003680inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003681 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003682{
3683 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003684 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003685
Steve Naroff8f708362007-08-24 19:07:16 +00003686 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003687
Chris Lattner4b009652007-07-25 00:24:17 +00003688 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003689 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003690 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003691}
3692
3693inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00003694 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003695{
3696 UsualUnaryConversions(lex);
3697 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003698
Eli Friedmanbea3f842008-05-13 20:16:47 +00003699 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003700 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003701 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003702}
3703
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003704/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3705/// is a read-only property; return true if so. A readonly property expression
3706/// depends on various declarations and thus must be treated specially.
3707///
Mike Stump9afab102009-02-19 03:04:26 +00003708static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003709{
3710 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3711 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3712 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3713 QualType BaseType = PropExpr->getBase()->getType();
3714 if (const PointerType *PTy = BaseType->getAsPointerType())
Mike Stump9afab102009-02-19 03:04:26 +00003715 if (const ObjCInterfaceType *IFTy =
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003716 PTy->getPointeeType()->getAsObjCInterfaceType())
3717 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3718 if (S.isPropertyReadonly(PDecl, IFace))
3719 return true;
3720 }
3721 }
3722 return false;
3723}
3724
Chris Lattner4c2642c2008-11-18 01:22:49 +00003725/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3726/// emit an error and return true. If so, return false.
3727static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003728 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3729 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3730 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003731 if (IsLV == Expr::MLV_Valid)
3732 return false;
Mike Stump9afab102009-02-19 03:04:26 +00003733
Chris Lattner4c2642c2008-11-18 01:22:49 +00003734 unsigned Diag = 0;
3735 bool NeedType = false;
3736 switch (IsLV) { // C99 6.5.16p2
3737 default: assert(0 && "Unknown result from isModifiableLvalue!");
3738 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00003739 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003740 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3741 NeedType = true;
3742 break;
Mike Stump9afab102009-02-19 03:04:26 +00003743 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003744 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3745 NeedType = true;
3746 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003747 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003748 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3749 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003750 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003751 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3752 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003753 case Expr::MLV_IncompleteType:
3754 case Expr::MLV_IncompleteVoidType:
Douglas Gregorc84d8932009-03-09 16:13:40 +00003755 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003756 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3757 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003758 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003759 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3760 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003761 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003762 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3763 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003764 case Expr::MLV_ReadonlyProperty:
3765 Diag = diag::error_readonly_property_assignment;
3766 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003767 case Expr::MLV_NoSetterProperty:
3768 Diag = diag::error_nosetter_property_assignment;
3769 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003770 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003771
Chris Lattner4c2642c2008-11-18 01:22:49 +00003772 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003773 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003774 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003775 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003776 return true;
3777}
3778
3779
3780
3781// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003782QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3783 SourceLocation Loc,
3784 QualType CompoundType) {
3785 // Verify that LHS is a modifiable lvalue, and emit error if not.
3786 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003787 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003788
3789 QualType LHSType = LHS->getType();
3790 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00003791
Chris Lattner005ed752008-01-04 18:04:52 +00003792 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003793 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003794 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003795 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003796 // Special case of NSObject attributes on c-style pointer types.
3797 if (ConvTy == IncompatiblePointer &&
3798 ((Context.isObjCNSObjectType(LHSType) &&
3799 Context.isObjCObjectPointerType(RHSType)) ||
3800 (Context.isObjCNSObjectType(RHSType) &&
3801 Context.isObjCObjectPointerType(LHSType))))
3802 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003803
Chris Lattner34c85082008-08-21 18:04:13 +00003804 // If the RHS is a unary plus or minus, check to see if they = and + are
3805 // right next to each other. If so, the user may have typo'd "x =+ 4"
3806 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003807 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003808 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3809 RHSCheck = ICE->getSubExpr();
3810 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3811 if ((UO->getOpcode() == UnaryOperator::Plus ||
3812 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003813 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003814 // Only if the two operators are exactly adjacent.
Chris Lattner55a17242009-03-08 06:51:10 +00003815 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
3816 // And there is a space or other character before the subexpr of the
3817 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnerf1e5d4a2009-03-09 07:11:10 +00003818 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
3819 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003820 Diag(Loc, diag::warn_not_compound_assign)
3821 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3822 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner55a17242009-03-08 06:51:10 +00003823 }
Chris Lattner34c85082008-08-21 18:04:13 +00003824 }
3825 } else {
3826 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003827 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003828 }
Chris Lattner005ed752008-01-04 18:04:52 +00003829
Chris Lattner1eafdea2008-11-18 01:30:42 +00003830 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3831 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003832 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00003833
Chris Lattner4b009652007-07-25 00:24:17 +00003834 // C99 6.5.16p3: The type of an assignment expression is the type of the
3835 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00003836 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00003837 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3838 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003839 // C++ 5.17p1: the type of the assignment expression is that of its left
3840 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003841 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003842}
3843
Chris Lattner1eafdea2008-11-18 01:30:42 +00003844// C99 6.5.17
3845QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00003846 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003847 DefaultFunctionArrayConversion(RHS);
Eli Friedman2b128322009-03-23 00:24:07 +00003848
3849 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
3850 // incomplete in C++).
3851
Chris Lattner1eafdea2008-11-18 01:30:42 +00003852 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003853}
3854
3855/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3856/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003857QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3858 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003859 if (Op->isTypeDependent())
3860 return Context.DependentTy;
3861
Chris Lattnere65182c2008-11-21 07:05:48 +00003862 QualType ResType = Op->getType();
3863 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003864
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003865 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3866 // Decrement of bool is not allowed.
3867 if (!isInc) {
3868 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3869 return QualType();
3870 }
3871 // Increment of bool sets it to true, but is deprecated.
3872 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3873 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003874 // OK!
3875 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3876 // C99 6.5.2.4p2, 6.5.6p2
Douglas Gregorcde3a2d2009-03-24 20:13:58 +00003877 if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003878 if (getLangOptions().CPlusPlus) {
3879 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3880 << Op->getSourceRange();
3881 return QualType();
3882 }
3883
3884 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003885 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003886 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003887 if (getLangOptions().CPlusPlus) {
3888 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3889 << Op->getType() << Op->getSourceRange();
3890 return QualType();
3891 }
3892
3893 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003894 << ResType << Op->getSourceRange();
Douglas Gregorcde3a2d2009-03-24 20:13:58 +00003895 } else if (RequireCompleteType(OpLoc, PT->getPointeeType(),
3896 diag::err_typecheck_arithmetic_incomplete_type,
3897 Op->getSourceRange(), SourceRange(),
3898 ResType))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003899 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003900 } else if (ResType->isComplexType()) {
3901 // C99 does not support ++/-- on complex types, we allow as an extension.
3902 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003903 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003904 } else {
3905 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003906 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003907 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003908 }
Mike Stump9afab102009-02-19 03:04:26 +00003909 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00003910 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003911 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003912 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003913 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003914}
3915
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003916/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003917/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003918/// where the declaration is needed for type checking. We only need to
3919/// handle cases when the expression references a function designator
3920/// or is an lvalue. Here are some examples:
3921/// - &(x) => x
3922/// - &*****f => f for f a function designator.
3923/// - &s.xx => s
3924/// - &s.zz[1].yy -> s, if zz is an array
3925/// - *(x + 1) -> x, if x is an array
3926/// - &"123"[2] -> 0
3927/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003928static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003929 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003930 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003931 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003932 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003933 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003934 // Fields cannot be declared with a 'register' storage class.
3935 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003936 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003937 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003938 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003939 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003940 // &X[4] and &4[X] refers to X if X is not a pointer.
Mike Stump9afab102009-02-19 03:04:26 +00003941
Douglas Gregord2baafd2008-10-21 16:13:35 +00003942 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003943 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003944 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003945 return 0;
3946 else
3947 return VD;
3948 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003949 case Stmt::UnaryOperatorClass: {
3950 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00003951
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003952 switch(UO->getOpcode()) {
3953 case UnaryOperator::Deref: {
3954 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003955 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3956 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3957 if (!VD || VD->getType()->isPointerType())
3958 return 0;
3959 return VD;
3960 }
3961 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003962 }
3963 case UnaryOperator::Real:
3964 case UnaryOperator::Imag:
3965 case UnaryOperator::Extension:
3966 return getPrimaryDecl(UO->getSubExpr());
3967 default:
3968 return 0;
3969 }
3970 }
3971 case Stmt::BinaryOperatorClass: {
3972 BinaryOperator *BO = cast<BinaryOperator>(E);
3973
3974 // Handle cases involving pointer arithmetic. The result of an
3975 // Assign or AddAssign is not an lvalue so they can be ignored.
3976
3977 // (x + n) or (n + x) => x
3978 if (BO->getOpcode() == BinaryOperator::Add) {
3979 if (BO->getLHS()->getType()->isPointerType()) {
3980 return getPrimaryDecl(BO->getLHS());
3981 } else if (BO->getRHS()->getType()->isPointerType()) {
3982 return getPrimaryDecl(BO->getRHS());
3983 }
3984 }
3985
3986 return 0;
3987 }
Chris Lattner4b009652007-07-25 00:24:17 +00003988 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003989 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003990 case Stmt::ImplicitCastExprClass:
3991 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003992 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003993 default:
3994 return 0;
3995 }
3996}
3997
3998/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00003999/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00004000/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00004001/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00004002/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00004003/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00004004/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00004005QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00004006 if (op->isTypeDependent())
4007 return Context.DependentTy;
4008
Steve Naroff9c6c3592008-01-13 17:10:08 +00004009 if (getLangOptions().C99) {
4010 // Implement C99-only parts of addressof rules.
4011 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
4012 if (uOp->getOpcode() == UnaryOperator::Deref)
4013 // Per C99 6.5.3.2, the address of a deref always returns a valid result
4014 // (assuming the deref expression is valid).
4015 return uOp->getSubExpr()->getType();
4016 }
4017 // Technically, there should be a check for array subscript
4018 // expressions here, but the result of one is always an lvalue anyway.
4019 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00004020 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00004021 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00004022
Chris Lattner4b009652007-07-25 00:24:17 +00004023 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00004024 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
4025 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00004026 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
4027 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004028 return QualType();
4029 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00004030 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00004031 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
4032 if (Field->isBitField()) {
4033 Diag(OpLoc, diag::err_typecheck_address_of)
4034 << "bit-field" << op->getSourceRange();
4035 return QualType();
4036 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00004037 }
4038 // Check for Apple extension for accessing vector components.
Nate Begemana9187ab2009-02-15 22:45:20 +00004039 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
4040 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Chris Lattner77d52da2008-11-20 06:06:08 +00004041 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00004042 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004043 return QualType();
4044 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00004045 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00004046 // with the register storage-class specifier.
4047 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
4048 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004049 Diag(OpLoc, diag::err_typecheck_address_of)
4050 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004051 return QualType();
4052 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00004053 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00004054 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00004055 } else if (isa<FieldDecl>(dcl)) {
4056 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00004057 // Could be a pointer to member, though, if there is an explicit
4058 // scope qualifier for the class.
4059 if (isa<QualifiedDeclRefExpr>(op)) {
4060 DeclContext *Ctx = dcl->getDeclContext();
4061 if (Ctx && Ctx->isRecord())
4062 return Context.getMemberPointerType(op->getType(),
4063 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
4064 }
Nuno Lopesdf239522008-12-16 22:58:26 +00004065 } else if (isa<FunctionDecl>(dcl)) {
4066 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00004067 // As above.
4068 if (isa<QualifiedDeclRefExpr>(op)) {
4069 DeclContext *Ctx = dcl->getDeclContext();
4070 if (Ctx && Ctx->isRecord())
4071 return Context.getMemberPointerType(op->getType(),
4072 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
4073 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00004074 }
Nuno Lopesdf239522008-12-16 22:58:26 +00004075 else
Chris Lattner4b009652007-07-25 00:24:17 +00004076 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00004077 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00004078
Chris Lattner4b009652007-07-25 00:24:17 +00004079 // If the operand has type "type", the result has type "pointer to type".
4080 return Context.getPointerType(op->getType());
4081}
4082
Chris Lattnerda5c0872008-11-23 09:13:29 +00004083QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004084 if (Op->isTypeDependent())
4085 return Context.DependentTy;
4086
Chris Lattnerda5c0872008-11-23 09:13:29 +00004087 UsualUnaryConversions(Op);
4088 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004089
Chris Lattnerda5c0872008-11-23 09:13:29 +00004090 // Note that per both C89 and C99, this is always legal, even if ptype is an
4091 // incomplete type or void. It would be possible to warn about dereferencing
4092 // a void pointer, but it's completely well-defined, and such a warning is
4093 // unlikely to catch any mistakes.
4094 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00004095 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004096
Chris Lattner77d52da2008-11-20 06:06:08 +00004097 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00004098 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004099 return QualType();
4100}
4101
4102static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
4103 tok::TokenKind Kind) {
4104 BinaryOperator::Opcode Opc;
4105 switch (Kind) {
4106 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00004107 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
4108 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00004109 case tok::star: Opc = BinaryOperator::Mul; break;
4110 case tok::slash: Opc = BinaryOperator::Div; break;
4111 case tok::percent: Opc = BinaryOperator::Rem; break;
4112 case tok::plus: Opc = BinaryOperator::Add; break;
4113 case tok::minus: Opc = BinaryOperator::Sub; break;
4114 case tok::lessless: Opc = BinaryOperator::Shl; break;
4115 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
4116 case tok::lessequal: Opc = BinaryOperator::LE; break;
4117 case tok::less: Opc = BinaryOperator::LT; break;
4118 case tok::greaterequal: Opc = BinaryOperator::GE; break;
4119 case tok::greater: Opc = BinaryOperator::GT; break;
4120 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
4121 case tok::equalequal: Opc = BinaryOperator::EQ; break;
4122 case tok::amp: Opc = BinaryOperator::And; break;
4123 case tok::caret: Opc = BinaryOperator::Xor; break;
4124 case tok::pipe: Opc = BinaryOperator::Or; break;
4125 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
4126 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
4127 case tok::equal: Opc = BinaryOperator::Assign; break;
4128 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
4129 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
4130 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
4131 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
4132 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
4133 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
4134 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
4135 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
4136 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
4137 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
4138 case tok::comma: Opc = BinaryOperator::Comma; break;
4139 }
4140 return Opc;
4141}
4142
4143static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
4144 tok::TokenKind Kind) {
4145 UnaryOperator::Opcode Opc;
4146 switch (Kind) {
4147 default: assert(0 && "Unknown unary op!");
4148 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
4149 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
4150 case tok::amp: Opc = UnaryOperator::AddrOf; break;
4151 case tok::star: Opc = UnaryOperator::Deref; break;
4152 case tok::plus: Opc = UnaryOperator::Plus; break;
4153 case tok::minus: Opc = UnaryOperator::Minus; break;
4154 case tok::tilde: Opc = UnaryOperator::Not; break;
4155 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00004156 case tok::kw___real: Opc = UnaryOperator::Real; break;
4157 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
4158 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
4159 }
4160 return Opc;
4161}
4162
Douglas Gregord7f915e2008-11-06 23:29:22 +00004163/// CreateBuiltinBinOp - Creates a new built-in binary operation with
4164/// operator @p Opc at location @c TokLoc. This routine only supports
4165/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004166Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
4167 unsigned Op,
4168 Expr *lhs, Expr *rhs) {
Eli Friedman3cd92882009-03-28 01:22:36 +00004169 QualType ResultTy; // Result type of the binary operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00004170 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman3cd92882009-03-28 01:22:36 +00004171 // The following two variables are used for compound assignment operators
4172 QualType CompLHSTy; // Type of LHS after promotions for computation
4173 QualType CompResultTy; // Type of computation result
Douglas Gregord7f915e2008-11-06 23:29:22 +00004174
4175 switch (Opc) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00004176 case BinaryOperator::Assign:
4177 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
4178 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00004179 case BinaryOperator::PtrMemD:
4180 case BinaryOperator::PtrMemI:
4181 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
4182 Opc == BinaryOperator::PtrMemI);
4183 break;
4184 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00004185 case BinaryOperator::Div:
4186 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
4187 break;
4188 case BinaryOperator::Rem:
4189 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
4190 break;
4191 case BinaryOperator::Add:
4192 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
4193 break;
4194 case BinaryOperator::Sub:
4195 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
4196 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00004197 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00004198 case BinaryOperator::Shr:
4199 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
4200 break;
4201 case BinaryOperator::LE:
4202 case BinaryOperator::LT:
4203 case BinaryOperator::GE:
4204 case BinaryOperator::GT:
Douglas Gregor1f12c352009-04-06 18:45:53 +00004205 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004206 break;
4207 case BinaryOperator::EQ:
4208 case BinaryOperator::NE:
Douglas Gregor1f12c352009-04-06 18:45:53 +00004209 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004210 break;
4211 case BinaryOperator::And:
4212 case BinaryOperator::Xor:
4213 case BinaryOperator::Or:
4214 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
4215 break;
4216 case BinaryOperator::LAnd:
4217 case BinaryOperator::LOr:
4218 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
4219 break;
4220 case BinaryOperator::MulAssign:
4221 case BinaryOperator::DivAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004222 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
4223 CompLHSTy = CompResultTy;
4224 if (!CompResultTy.isNull())
4225 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004226 break;
4227 case BinaryOperator::RemAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004228 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
4229 CompLHSTy = CompResultTy;
4230 if (!CompResultTy.isNull())
4231 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004232 break;
4233 case BinaryOperator::AddAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004234 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
4235 if (!CompResultTy.isNull())
4236 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004237 break;
4238 case BinaryOperator::SubAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004239 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
4240 if (!CompResultTy.isNull())
4241 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004242 break;
4243 case BinaryOperator::ShlAssign:
4244 case BinaryOperator::ShrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004245 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
4246 CompLHSTy = CompResultTy;
4247 if (!CompResultTy.isNull())
4248 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004249 break;
4250 case BinaryOperator::AndAssign:
4251 case BinaryOperator::XorAssign:
4252 case BinaryOperator::OrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004253 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
4254 CompLHSTy = CompResultTy;
4255 if (!CompResultTy.isNull())
4256 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004257 break;
4258 case BinaryOperator::Comma:
4259 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
4260 break;
4261 }
4262 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004263 return ExprError();
Eli Friedman3cd92882009-03-28 01:22:36 +00004264 if (CompResultTy.isNull())
Steve Naroff774e4152009-01-21 00:14:39 +00004265 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
4266 else
4267 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman3cd92882009-03-28 01:22:36 +00004268 CompLHSTy, CompResultTy,
4269 OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00004270}
4271
Chris Lattner4b009652007-07-25 00:24:17 +00004272// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004273Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
4274 tok::TokenKind Kind,
4275 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00004276 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004277 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00004278
Steve Naroff87d58b42007-09-16 03:34:24 +00004279 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
4280 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004281
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004282 if (getLangOptions().CPlusPlus &&
4283 (lhs->getType()->isOverloadableType() ||
4284 rhs->getType()->isOverloadableType())) {
4285 // Find all of the overloaded operators visible from this
4286 // point. We perform both an operator-name lookup from the local
4287 // scope and an argument-dependent lookup based on the types of
4288 // the arguments.
Douglas Gregor3fc092f2009-03-13 00:33:25 +00004289 FunctionSet Functions;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004290 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
4291 if (OverOp != OO_None) {
4292 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
4293 Functions);
4294 Expr *Args[2] = { lhs, rhs };
4295 DeclarationName OpName
4296 = Context.DeclarationNames.getCXXOperatorName(OverOp);
4297 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregor70d26122008-11-12 17:17:38 +00004298 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004299
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004300 // Build the (potentially-overloaded, potentially-dependent)
4301 // binary operation.
4302 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004303 }
4304
Douglas Gregord7f915e2008-11-06 23:29:22 +00004305 // Build a built-in binary operation.
4306 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00004307}
4308
Douglas Gregorc78182d2009-03-13 23:49:33 +00004309Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
4310 unsigned OpcIn,
4311 ExprArg InputArg) {
4312 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004313
Douglas Gregorc78182d2009-03-13 23:49:33 +00004314 // FIXME: Input is modified below, but InputArg is not updated
4315 // appropriately.
4316 Expr *Input = (Expr *)InputArg.get();
Chris Lattner4b009652007-07-25 00:24:17 +00004317 QualType resultType;
4318 switch (Opc) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00004319 case UnaryOperator::PostInc:
4320 case UnaryOperator::PostDec:
4321 case UnaryOperator::OffsetOf:
4322 assert(false && "Invalid unary operator");
4323 break;
4324
Chris Lattner4b009652007-07-25 00:24:17 +00004325 case UnaryOperator::PreInc:
4326 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004327 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4328 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00004329 break;
Mike Stump9afab102009-02-19 03:04:26 +00004330 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00004331 resultType = CheckAddressOfOperand(Input, OpLoc);
4332 break;
Mike Stump9afab102009-02-19 03:04:26 +00004333 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00004334 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00004335 resultType = CheckIndirectionOperand(Input, OpLoc);
4336 break;
4337 case UnaryOperator::Plus:
4338 case UnaryOperator::Minus:
4339 UsualUnaryConversions(Input);
4340 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004341 if (resultType->isDependentType())
4342 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004343 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4344 break;
4345 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4346 resultType->isEnumeralType())
4347 break;
4348 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4349 Opc == UnaryOperator::Plus &&
4350 resultType->isPointerType())
4351 break;
4352
Sebastian Redl8b769972009-01-19 00:08:26 +00004353 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4354 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004355 case UnaryOperator::Not: // bitwise complement
4356 UsualUnaryConversions(Input);
4357 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004358 if (resultType->isDependentType())
4359 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00004360 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4361 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4362 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00004363 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004364 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004365 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00004366 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4367 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004368 break;
4369 case UnaryOperator::LNot: // logical negation
4370 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4371 DefaultFunctionArrayConversion(Input);
4372 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004373 if (resultType->isDependentType())
4374 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004375 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004376 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4377 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004378 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004379 // In C++, it's bool. C++ 5.3.1p8
4380 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004381 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004382 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004383 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00004384 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00004385 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004386 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004387 resultType = Input->getType();
4388 break;
4389 }
4390 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004391 return ExprError();
Douglas Gregorc78182d2009-03-13 23:49:33 +00004392
4393 InputArg.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004394 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004395}
4396
Douglas Gregorc78182d2009-03-13 23:49:33 +00004397// Unary Operators. 'Tok' is the token for the operator.
4398Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4399 tok::TokenKind Op, ExprArg input) {
4400 Expr *Input = (Expr*)input.get();
4401 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
4402
4403 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
4404 // Find all of the overloaded operators visible from this
4405 // point. We perform both an operator-name lookup from the local
4406 // scope and an argument-dependent lookup based on the types of
4407 // the arguments.
4408 FunctionSet Functions;
4409 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
4410 if (OverOp != OO_None) {
4411 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
4412 Functions);
4413 DeclarationName OpName
4414 = Context.DeclarationNames.getCXXOperatorName(OverOp);
4415 ArgumentDependentLookup(OpName, &Input, 1, Functions);
4416 }
4417
4418 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
4419 }
4420
4421 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
4422}
4423
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004424/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004425Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
4426 SourceLocation LabLoc,
4427 IdentifierInfo *LabelII) {
Chris Lattner4b009652007-07-25 00:24:17 +00004428 // Look up the record for this label identifier.
Steve Naroffff9ecaf2009-03-13 16:03:38 +00004429 LabelStmt *&LabelDecl = CurBlock ? CurBlock->LabelMap[LabelII] :
4430 LabelMap[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00004431
Daniel Dunbar879788d2008-08-04 16:51:22 +00004432 // If we haven't seen this label yet, create a forward reference. It
4433 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffb88d81c2009-03-13 15:38:40 +00004434 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004435 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004436
Chris Lattner4b009652007-07-25 00:24:17 +00004437 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004438 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4439 Context.getPointerType(Context.VoidTy)));
Chris Lattner4b009652007-07-25 00:24:17 +00004440}
4441
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004442Sema::OwningExprResult
4443Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
4444 SourceLocation RPLoc) { // "({..})"
4445 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner4b009652007-07-25 00:24:17 +00004446 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4447 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4448
Eli Friedmanbc941e12009-01-24 23:09:00 +00004449 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4450 if (isFileScope) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004451 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmanbc941e12009-01-24 23:09:00 +00004452 }
4453
Chris Lattner4b009652007-07-25 00:24:17 +00004454 // FIXME: there are a variety of strange constraints to enforce here, for
4455 // example, it is not possible to goto into a stmt expression apparently.
4456 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00004457
Chris Lattner4b009652007-07-25 00:24:17 +00004458 // FIXME: the last statement in the compount stmt has its value used. We
4459 // should not warn about it being unused.
4460
4461 // If there are sub stmts in the compound stmt, take the type of the last one
4462 // as the type of the stmtexpr.
4463 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00004464
Chris Lattner200964f2008-07-26 19:51:01 +00004465 if (!Compound->body_empty()) {
4466 Stmt *LastStmt = Compound->body_back();
4467 // If LastStmt is a label, skip down through into the body.
4468 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4469 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00004470
Chris Lattner200964f2008-07-26 19:51:01 +00004471 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004472 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004473 }
Mike Stump9afab102009-02-19 03:04:26 +00004474
Eli Friedman2b128322009-03-23 00:24:07 +00004475 // FIXME: Check that expression type is complete/non-abstract; statement
4476 // expressions are not lvalues.
4477
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004478 substmt.release();
4479 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004480}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004481
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004482Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4483 SourceLocation BuiltinLoc,
4484 SourceLocation TypeLoc,
4485 TypeTy *argty,
4486 OffsetOfComponent *CompPtr,
4487 unsigned NumComponents,
4488 SourceLocation RPLoc) {
4489 // FIXME: This function leaks all expressions in the offset components on
4490 // error.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004491 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4492 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00004493
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004494 bool Dependent = ArgTy->isDependentType();
4495
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004496 // We must have at least one component that refers to the type, and the first
4497 // one is known to be a field designator. Verify that the ArgTy represents
4498 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004499 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004500 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump9afab102009-02-19 03:04:26 +00004501
Eli Friedman2b128322009-03-23 00:24:07 +00004502 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
4503 // with an incomplete type would be illegal.
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00004504
Eli Friedman342d9432009-02-27 06:44:11 +00004505 // Otherwise, create a null pointer as the base, and iteratively process
4506 // the offsetof designators.
4507 QualType ArgTyPtr = Context.getPointerType(ArgTy);
4508 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004509 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman342d9432009-02-27 06:44:11 +00004510 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004511
Chris Lattnerb37522e2007-08-31 21:49:13 +00004512 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4513 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00004514 // FIXME: This diagnostic isn't actually visible because the location is in
4515 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00004516 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004517 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4518 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00004519
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004520 if (!Dependent) {
4521 // FIXME: Dependent case loses a lot of information here. And probably
4522 // leaks like a sieve.
4523 for (unsigned i = 0; i != NumComponents; ++i) {
4524 const OffsetOfComponent &OC = CompPtr[i];
4525 if (OC.isBrackets) {
4526 // Offset of an array sub-field. TODO: Should we allow vector elements?
4527 const ArrayType *AT = Context.getAsArrayType(Res->getType());
4528 if (!AT) {
4529 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004530 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
4531 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004532 }
4533
4534 // FIXME: C++: Verify that operator[] isn't overloaded.
4535
Eli Friedman342d9432009-02-27 06:44:11 +00004536 // Promote the array so it looks more like a normal array subscript
4537 // expression.
4538 DefaultFunctionArrayConversion(Res);
4539
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004540 // C99 6.5.2.1p1
4541 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004542 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004543 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004544 return ExprError(Diag(Idx->getLocStart(),
4545 diag::err_typecheck_subscript)
4546 << Idx->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004547
4548 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4549 OC.LocEnd);
4550 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004551 }
Mike Stump9afab102009-02-19 03:04:26 +00004552
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004553 const RecordType *RC = Res->getType()->getAsRecordType();
4554 if (!RC) {
4555 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004556 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
4557 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004558 }
Chris Lattner2af6a802007-08-30 17:59:59 +00004559
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004560 // Get the decl corresponding to this.
4561 RecordDecl *RD = RC->getDecl();
4562 FieldDecl *MemberDecl
4563 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4564 LookupMemberName)
4565 .getAsDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004566 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004567 if (!MemberDecl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004568 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
4569 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump9afab102009-02-19 03:04:26 +00004570
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004571 // FIXME: C++: Verify that MemberDecl isn't a static field.
4572 // FIXME: Verify that MemberDecl isn't a bitfield.
4573 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4574 // matter here.
4575 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
Steve Naroff774e4152009-01-21 00:14:39 +00004576 MemberDecl->getType().getNonReferenceType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004577 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004578 }
Mike Stump9afab102009-02-19 03:04:26 +00004579
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004580 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4581 Context.getSizeType(), BuiltinLoc));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004582}
4583
4584
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004585Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
4586 TypeTy *arg1,TypeTy *arg2,
4587 SourceLocation RPLoc) {
Steve Naroff63bad2d2007-08-01 22:05:33 +00004588 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4589 QualType argT2 = QualType::getFromOpaquePtr(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00004590
Steve Naroff63bad2d2007-08-01 22:05:33 +00004591 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00004592
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004593 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
4594 argT1, argT2, RPLoc));
Steve Naroff63bad2d2007-08-01 22:05:33 +00004595}
4596
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004597Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
4598 ExprArg cond,
4599 ExprArg expr1, ExprArg expr2,
4600 SourceLocation RPLoc) {
4601 Expr *CondExpr = static_cast<Expr*>(cond.get());
4602 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
4603 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump9afab102009-02-19 03:04:26 +00004604
Steve Naroff93c53012007-08-03 21:21:27 +00004605 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4606
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004607 QualType resType;
4608 if (CondExpr->isValueDependent()) {
4609 resType = Context.DependentTy;
4610 } else {
4611 // The conditional expression is required to be a constant expression.
4612 llvm::APSInt condEval(32);
4613 SourceLocation ExpLoc;
4614 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004615 return ExprError(Diag(ExpLoc,
4616 diag::err_typecheck_choose_expr_requires_constant)
4617 << CondExpr->getSourceRange());
Steve Naroff93c53012007-08-03 21:21:27 +00004618
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004619 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4620 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
4621 }
4622
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004623 cond.release(); expr1.release(); expr2.release();
4624 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4625 resType, RPLoc));
Steve Naroff93c53012007-08-03 21:21:27 +00004626}
4627
Steve Naroff52a81c02008-09-03 18:15:37 +00004628//===----------------------------------------------------------------------===//
4629// Clang Extensions.
4630//===----------------------------------------------------------------------===//
4631
4632/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004633void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004634 // Analyze block parameters.
4635 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00004636
Steve Naroff52a81c02008-09-03 18:15:37 +00004637 // Add BSI to CurBlock.
4638 BSI->PrevBlockInfo = CurBlock;
4639 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00004640
Steve Naroff52a81c02008-09-03 18:15:37 +00004641 BSI->ReturnType = 0;
4642 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00004643 BSI->hasBlockDeclRefExprs = false;
Mike Stump9afab102009-02-19 03:04:26 +00004644
Steve Naroff52059382008-10-10 01:28:17 +00004645 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004646 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004647}
4648
Mike Stumpc1fddff2009-02-04 22:31:32 +00004649void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4650 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4651
4652 if (ParamInfo.getNumTypeObjects() == 0
4653 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4654 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4655
4656 // The type is entirely optional as well, if none, use DependentTy.
4657 if (T.isNull())
4658 T = Context.DependentTy;
4659
4660 // The parameter list is optional, if there was none, assume ().
4661 if (!T->isFunctionType())
4662 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4663
4664 CurBlock->hasPrototype = true;
4665 CurBlock->isVariadic = false;
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00004666
4667 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
4668
4669 // Do not allow returning a objc interface by-value.
4670 if (RetTy->isObjCInterfaceType()) {
4671 Diag(ParamInfo.getSourceRange().getBegin(),
4672 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
4673 return;
4674 }
Mike Stumpc1fddff2009-02-04 22:31:32 +00004675
4676 if (!RetTy->isDependentType())
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00004677 CurBlock->ReturnType = RetTy.getTypePtr();
Mike Stumpc1fddff2009-02-04 22:31:32 +00004678 return;
4679 }
4680
Steve Naroff52a81c02008-09-03 18:15:37 +00004681 // Analyze arguments to block.
4682 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4683 "Not a function declarator!");
4684 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00004685
Steve Naroff52059382008-10-10 01:28:17 +00004686 CurBlock->hasPrototype = FTI.hasPrototype;
4687 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00004688
Steve Naroff52a81c02008-09-03 18:15:37 +00004689 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4690 // no arguments, not a function that takes a single void argument.
4691 if (FTI.hasPrototype &&
4692 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner5261d0c2009-03-28 19:18:32 +00004693 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
4694 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004695 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004696 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004697 } else if (FTI.hasPrototype) {
4698 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner5261d0c2009-03-28 19:18:32 +00004699 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff52059382008-10-10 01:28:17 +00004700 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00004701 }
Steve Naroff494cb0f2009-03-13 16:56:44 +00004702 CurBlock->TheDecl->setParams(Context, &CurBlock->Params[0],
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00004703 CurBlock->Params.size());
Mike Stump9afab102009-02-19 03:04:26 +00004704
Steve Naroff52059382008-10-10 01:28:17 +00004705 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4706 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4707 // If this has an identifier, add it to the scope stack.
4708 if ((*AI)->getIdentifier())
4709 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00004710
4711 // Analyze the return type.
4712 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4713 QualType RetTy = T->getAsFunctionType()->getResultType();
4714
4715 // Do not allow returning a objc interface by-value.
4716 if (RetTy->isObjCInterfaceType()) {
4717 Diag(ParamInfo.getSourceRange().getBegin(),
4718 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
4719 } else if (!RetTy->isDependentType())
4720 CurBlock->ReturnType = RetTy.getTypePtr();
Steve Naroff52a81c02008-09-03 18:15:37 +00004721}
4722
4723/// ActOnBlockError - If there is an error parsing a block, this callback
4724/// is invoked to pop the information about the block from the action impl.
4725void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4726 // Ensure that CurBlock is deleted.
4727 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00004728
Steve Naroff52a81c02008-09-03 18:15:37 +00004729 // Pop off CurBlock, handle nested blocks.
4730 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004731
Steve Naroff52a81c02008-09-03 18:15:37 +00004732 // FIXME: Delete the ParmVarDecl objects as well???
Douglas Gregorc1408ea2009-03-11 23:54:15 +00004733
Steve Naroff52a81c02008-09-03 18:15:37 +00004734}
4735
4736/// ActOnBlockStmtExpr - This is called when the body of a block statement
4737/// literal was successfully completed. ^(int x){...}
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004738Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
4739 StmtArg body, Scope *CurScope) {
Chris Lattnerc14c7f02009-03-27 04:18:06 +00004740 // If blocks are disabled, emit an error.
4741 if (!LangOpts.Blocks)
4742 Diag(CaretLoc, diag::err_blocks_disable);
4743
Steve Naroff52a81c02008-09-03 18:15:37 +00004744 // Ensure that CurBlock is deleted.
4745 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff52a81c02008-09-03 18:15:37 +00004746
Steve Naroff52059382008-10-10 01:28:17 +00004747 PopDeclContext();
4748
Steve Naroff52a81c02008-09-03 18:15:37 +00004749 // Pop off CurBlock, handle nested blocks.
4750 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004751
Steve Naroff52a81c02008-09-03 18:15:37 +00004752 QualType RetTy = Context.VoidTy;
4753 if (BSI->ReturnType)
4754 RetTy = QualType(BSI->ReturnType, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004755
Steve Naroff52a81c02008-09-03 18:15:37 +00004756 llvm::SmallVector<QualType, 8> ArgTypes;
4757 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4758 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00004759
Steve Naroff52a81c02008-09-03 18:15:37 +00004760 QualType BlockTy;
4761 if (!BSI->hasPrototype)
Douglas Gregor4fa58902009-02-26 23:50:07 +00004762 BlockTy = Context.getFunctionNoProtoType(RetTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004763 else
4764 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004765 BSI->isVariadic, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004766
Eli Friedman2b128322009-03-23 00:24:07 +00004767 // FIXME: Check that return/parameter types are complete/non-abstract
4768
Steve Naroff52a81c02008-09-03 18:15:37 +00004769 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00004770
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004771 BSI->TheDecl->setBody(static_cast<CompoundStmt*>(body.release()));
4772 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
4773 BSI->hasBlockDeclRefExprs));
Steve Naroff52a81c02008-09-03 18:15:37 +00004774}
4775
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004776Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4777 ExprArg expr, TypeTy *type,
4778 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004779 QualType T = QualType::getFromOpaquePtr(type);
Chris Lattnerda139482009-04-05 15:49:53 +00004780 Expr *E = static_cast<Expr*>(expr.get());
4781 Expr *OrigExpr = E;
4782
Anders Carlsson36760332007-10-15 20:28:48 +00004783 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004784
4785 // Get the va_list type
4786 QualType VaListType = Context.getBuiltinVaListType();
4787 // Deal with implicit array decay; for example, on x86-64,
4788 // va_list is an array, but it's supposed to decay to
4789 // a pointer for va_arg.
4790 if (VaListType->isArrayType())
4791 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004792 // Make sure the input expression also decays appropriately.
4793 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004794
Chris Lattnercb9469d2009-04-06 17:07:34 +00004795 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004796 return ExprError(Diag(E->getLocStart(),
4797 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerda139482009-04-05 15:49:53 +00004798 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner89a72c52009-04-05 00:59:53 +00004799 }
Mike Stump9afab102009-02-19 03:04:26 +00004800
Eli Friedman2b128322009-03-23 00:24:07 +00004801 // FIXME: Check that type is complete/non-abstract
Anders Carlsson36760332007-10-15 20:28:48 +00004802 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00004803
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004804 expr.release();
4805 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
4806 RPLoc));
Anders Carlsson36760332007-10-15 20:28:48 +00004807}
4808
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004809Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregorad4b3792008-11-29 04:51:27 +00004810 // The type of __null will be int or long, depending on the size of
4811 // pointers on the target.
4812 QualType Ty;
4813 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4814 Ty = Context.IntTy;
4815 else
4816 Ty = Context.LongTy;
4817
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004818 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregorad4b3792008-11-29 04:51:27 +00004819}
4820
Chris Lattner005ed752008-01-04 18:04:52 +00004821bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4822 SourceLocation Loc,
4823 QualType DstType, QualType SrcType,
4824 Expr *SrcExpr, const char *Flavor) {
4825 // Decode the result (notice that AST's are still created for extensions).
4826 bool isInvalid = false;
4827 unsigned DiagKind;
4828 switch (ConvTy) {
4829 default: assert(0 && "Unknown conversion type");
4830 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004831 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004832 DiagKind = diag::ext_typecheck_convert_pointer_int;
4833 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004834 case IntToPointer:
4835 DiagKind = diag::ext_typecheck_convert_int_pointer;
4836 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004837 case IncompatiblePointer:
4838 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4839 break;
Eli Friedman6ca28cb2009-03-22 23:59:44 +00004840 case IncompatiblePointerSign:
4841 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
4842 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004843 case FunctionVoidPointer:
4844 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4845 break;
4846 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004847 // If the qualifiers lost were because we were applying the
4848 // (deprecated) C++ conversion from a string literal to a char*
4849 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4850 // Ideally, this check would be performed in
4851 // CheckPointerTypesForAssignment. However, that would require a
4852 // bit of refactoring (so that the second argument is an
4853 // expression, rather than a type), which should be done as part
4854 // of a larger effort to fix CheckPointerTypesForAssignment for
4855 // C++ semantics.
4856 if (getLangOptions().CPlusPlus &&
4857 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4858 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004859 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4860 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004861 case IntToBlockPointer:
4862 DiagKind = diag::err_int_to_block_pointer;
4863 break;
4864 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004865 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004866 break;
Steve Naroff19608432008-10-14 22:18:38 +00004867 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00004868 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00004869 // it can give a more specific diagnostic.
4870 DiagKind = diag::warn_incompatible_qualified_id;
4871 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004872 case IncompatibleVectors:
4873 DiagKind = diag::warn_incompatible_vectors;
4874 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004875 case Incompatible:
4876 DiagKind = diag::err_typecheck_convert_incompatible;
4877 isInvalid = true;
4878 break;
4879 }
Mike Stump9afab102009-02-19 03:04:26 +00004880
Chris Lattner271d4c22008-11-24 05:29:24 +00004881 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4882 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004883 return isInvalid;
4884}
Anders Carlssond5201b92008-11-30 19:50:32 +00004885
4886bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4887{
4888 Expr::EvalResult EvalResult;
4889
Mike Stump9afab102009-02-19 03:04:26 +00004890 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00004891 EvalResult.HasSideEffects) {
4892 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4893
4894 if (EvalResult.Diag) {
4895 // We only show the note if it's not the usual "invalid subexpression"
4896 // or if it's actually in a subexpression.
4897 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4898 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4899 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4900 }
Mike Stump9afab102009-02-19 03:04:26 +00004901
Anders Carlssond5201b92008-11-30 19:50:32 +00004902 return true;
4903 }
4904
4905 if (EvalResult.Diag) {
Mike Stump9afab102009-02-19 03:04:26 +00004906 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
Anders Carlssond5201b92008-11-30 19:50:32 +00004907 E->getSourceRange();
4908
4909 // Print the reason it's not a constant.
4910 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4911 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4912 }
Mike Stump9afab102009-02-19 03:04:26 +00004913
Anders Carlssond5201b92008-11-30 19:50:32 +00004914 if (Result)
4915 *Result = EvalResult.Val.getInt();
4916 return false;
4917}