blob: 3442cc1db9f8ccb1a0e8f5a629c2554f623e27a8 [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
Douglas Gregor70b307e2009-05-01 20:41:21 +0000125/// \brief Whether this is a promotable bitfield reference according
126/// to C99 6.3.1.1p2, bullet 2.
127///
128/// \returns the type this bit-field will promote to, or NULL if no
129/// promotion occurs.
130static QualType isPromotableBitField(Expr *E, ASTContext &Context) {
131 MemberExpr *MemRef = dyn_cast<MemberExpr>(E->IgnoreParenCasts());
132 if (!MemRef)
133 return QualType();
134
135 FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl());
136 if (!Field || !Field->isBitField())
137 return QualType();
138
139 const BuiltinType *BT = Field->getType()->getAsBuiltinType();
140 if (!BT)
141 return QualType();
142
143 if (BT->getKind() != BuiltinType::Bool &&
144 BT->getKind() != BuiltinType::Int &&
145 BT->getKind() != BuiltinType::UInt)
146 return QualType();
147
148 llvm::APSInt BitWidthAP;
149 if (!Field->getBitWidth()->isIntegerConstantExpr(BitWidthAP, Context))
150 return QualType();
151
152 uint64_t BitWidth = BitWidthAP.getZExtValue();
153 uint64_t IntSize = Context.getTypeSize(Context.IntTy);
154 if (BitWidth < IntSize ||
155 (Field->getType()->isSignedIntegerType() && BitWidth == IntSize))
156 return Context.IntTy;
157
158 if (BitWidth == IntSize && Field->getType()->isUnsignedIntegerType())
159 return Context.UnsignedIntTy;
160
161 return QualType();
162}
163
Chris Lattner299b8842008-07-25 21:10:04 +0000164/// UsualUnaryConversions - Performs various conversions that are common to most
165/// operators (C99 6.3). The conversions of array and function types are
166/// sometimes surpressed. For example, the array->pointer conversion doesn't
167/// apply if the array is an argument to the sizeof or address (&) operators.
168/// In these instances, this routine should *not* be called.
169Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
170 QualType Ty = Expr->getType();
171 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
172
Douglas Gregor70b307e2009-05-01 20:41:21 +0000173 // C99 6.3.1.1p2:
174 //
175 // The following may be used in an expression wherever an int or
176 // unsigned int may be used:
177 // - an object or expression with an integer type whose integer
178 // conversion rank is less than or equal to the rank of int
179 // and unsigned int.
180 // - A bit-field of type _Bool, int, signed int, or unsigned int.
181 //
182 // If an int can represent all values of the original type, the
183 // value is converted to an int; otherwise, it is converted to an
184 // unsigned int. These are called the integer promotions. All
185 // other types are unchanged by the integer promotions.
186 if (Ty->isPromotableIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000187 ImpCastExprToType(Expr, Context.IntTy);
Douglas Gregor70b307e2009-05-01 20:41:21 +0000188 return Expr;
189 } else {
190 QualType T = isPromotableBitField(Expr, Context);
191 if (!T.isNull()) {
192 ImpCastExprToType(Expr, T);
193 return Expr;
194 }
195 }
196
197 DefaultFunctionArrayConversion(Expr);
Chris Lattner299b8842008-07-25 21:10:04 +0000198 return Expr;
199}
200
Chris Lattner9305c3d2008-07-25 22:25:12 +0000201/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
202/// do not have a prototype. Arguments that have type float are promoted to
203/// double. All other argument types are converted by UsualUnaryConversions().
204void Sema::DefaultArgumentPromotion(Expr *&Expr) {
205 QualType Ty = Expr->getType();
206 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
207
208 // If this is a 'float' (CVR qualified or typedef) promote to double.
209 if (const BuiltinType *BT = Ty->getAsBuiltinType())
210 if (BT->getKind() == BuiltinType::Float)
211 return ImpCastExprToType(Expr, Context.DoubleTy);
212
213 UsualUnaryConversions(Expr);
214}
215
Chris Lattner81f00ed2009-04-12 08:11:20 +0000216/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
217/// will warn if the resulting type is not a POD type, and rejects ObjC
218/// interfaces passed by value. This returns true if the argument type is
219/// completely illegal.
220bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000221 DefaultArgumentPromotion(Expr);
222
Chris Lattner81f00ed2009-04-12 08:11:20 +0000223 if (Expr->getType()->isObjCInterfaceType()) {
224 Diag(Expr->getLocStart(),
225 diag::err_cannot_pass_objc_interface_to_vararg)
226 << Expr->getType() << CT;
227 return true;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000228 }
Chris Lattner81f00ed2009-04-12 08:11:20 +0000229
230 if (!Expr->getType()->isPODType())
231 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
232 << Expr->getType() << CT;
233
234 return false;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000235}
236
237
Chris Lattner299b8842008-07-25 21:10:04 +0000238/// UsualArithmeticConversions - Performs various conversions that are common to
239/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
240/// routine returns the first non-arithmetic type found. The client is
241/// responsible for emitting appropriate error diagnostics.
242/// FIXME: verify the conversion rules for "complex int" are consistent with
243/// GCC.
244QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
245 bool isCompAssign) {
Eli Friedman3cd92882009-03-28 01:22:36 +0000246 if (!isCompAssign)
Chris Lattner299b8842008-07-25 21:10:04 +0000247 UsualUnaryConversions(lhsExpr);
Eli Friedman3cd92882009-03-28 01:22:36 +0000248
249 UsualUnaryConversions(rhsExpr);
Douglas Gregor70d26122008-11-12 17:17:38 +0000250
Chris Lattner299b8842008-07-25 21:10:04 +0000251 // For conversion purposes, we ignore any qualifiers.
252 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000253 QualType lhs =
254 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
255 QualType rhs =
256 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000257
258 // If both types are identical, no conversion is needed.
259 if (lhs == rhs)
260 return lhs;
261
262 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
263 // The caller can deal with this (e.g. pointer + int).
264 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
265 return lhs;
266
267 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman3cd92882009-03-28 01:22:36 +0000268 if (!isCompAssign)
Douglas Gregor70d26122008-11-12 17:17:38 +0000269 ImpCastExprToType(lhsExpr, destType);
Eli Friedman3cd92882009-03-28 01:22:36 +0000270 ImpCastExprToType(rhsExpr, destType);
Douglas Gregor70d26122008-11-12 17:17:38 +0000271 return destType;
272}
273
274QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
275 // Perform the usual unary conversions. We do this early so that
276 // integral promotions to "int" can allow us to exit early, in the
277 // lhs == rhs check. Also, for conversion purposes, we ignore any
278 // qualifiers. For example, "const float" and "float" are
279 // equivalent.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000280 if (lhs->isPromotableIntegerType())
281 lhs = Context.IntTy;
282 else
283 lhs = lhs.getUnqualifiedType();
284 if (rhs->isPromotableIntegerType())
285 rhs = Context.IntTy;
286 else
287 rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000288
Chris Lattner299b8842008-07-25 21:10:04 +0000289 // If both types are identical, no conversion is needed.
290 if (lhs == rhs)
291 return lhs;
292
293 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
294 // The caller can deal with this (e.g. pointer + int).
295 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
296 return lhs;
297
298 // At this point, we have two different arithmetic types.
299
300 // Handle complex types first (C99 6.3.1.8p1).
301 if (lhs->isComplexType() || rhs->isComplexType()) {
302 // if we have an integer operand, the result is the complex type.
303 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
304 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000305 return lhs;
306 }
307 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
308 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000309 return rhs;
310 }
311 // This handles complex/complex, complex/float, or float/complex.
312 // When both operands are complex, the shorter operand is converted to the
313 // type of the longer, and that is the type of the result. This corresponds
314 // to what is done when combining two real floating-point operands.
315 // The fun begins when size promotion occur across type domains.
316 // From H&S 6.3.4: When one operand is complex and the other is a real
317 // floating-point type, the less precise type is converted, within it's
318 // real or complex domain, to the precision of the other type. For example,
319 // when combining a "long double" with a "double _Complex", the
320 // "double _Complex" is promoted to "long double _Complex".
321 int result = Context.getFloatingTypeOrder(lhs, rhs);
322
323 if (result > 0) { // The left side is bigger, convert rhs.
324 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000325 } else if (result < 0) { // The right side is bigger, convert lhs.
326 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000327 }
328 // At this point, lhs and rhs have the same rank/size. Now, make sure the
329 // domains match. This is a requirement for our implementation, C99
330 // does not require this promotion.
331 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
332 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000333 return rhs;
334 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000335 return lhs;
336 }
337 }
338 return lhs; // The domain/size match exactly.
339 }
340 // Now handle "real" floating types (i.e. float, double, long double).
341 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
342 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000343 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000344 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000345 return lhs;
346 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000347 if (rhs->isComplexIntegerType()) {
348 // convert rhs to the complex floating point type.
349 return Context.getComplexType(lhs);
350 }
351 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000352 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000353 return rhs;
354 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000355 if (lhs->isComplexIntegerType()) {
356 // convert lhs to the complex floating point type.
357 return Context.getComplexType(rhs);
358 }
Chris Lattner299b8842008-07-25 21:10:04 +0000359 // We have two real floating types, float/complex combos were handled above.
360 // Convert the smaller operand to the bigger result.
361 int result = Context.getFloatingTypeOrder(lhs, rhs);
Chris Lattner2cb744b2009-02-15 22:43:40 +0000362 if (result > 0) // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000363 return lhs;
Chris Lattner2cb744b2009-02-15 22:43:40 +0000364 assert(result < 0 && "illegal float comparison");
365 return rhs; // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000366 }
367 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
368 // Handle GCC complex int extension.
369 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
370 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
371
372 if (lhsComplexInt && rhsComplexInt) {
373 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
Chris Lattner2cb744b2009-02-15 22:43:40 +0000374 rhsComplexInt->getElementType()) >= 0)
375 return lhs; // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000376 return rhs;
377 } else if (lhsComplexInt && rhs->isIntegerType()) {
378 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000379 return lhs;
380 } else if (rhsComplexInt && lhs->isIntegerType()) {
381 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000382 return rhs;
383 }
384 }
385 // Finally, we have two differing integer types.
386 // The rules for this case are in C99 6.3.1.8
387 int compare = Context.getIntegerTypeOrder(lhs, rhs);
388 bool lhsSigned = lhs->isSignedIntegerType(),
389 rhsSigned = rhs->isSignedIntegerType();
390 QualType destType;
391 if (lhsSigned == rhsSigned) {
392 // Same signedness; use the higher-ranked type
393 destType = compare >= 0 ? lhs : rhs;
394 } else if (compare != (lhsSigned ? 1 : -1)) {
395 // The unsigned type has greater than or equal rank to the
396 // signed type, so use the unsigned type
397 destType = lhsSigned ? rhs : lhs;
398 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
399 // The two types are different widths; if we are here, that
400 // means the signed type is larger than the unsigned type, so
401 // use the signed type.
402 destType = lhsSigned ? lhs : rhs;
403 } else {
404 // The signed type is higher-ranked than the unsigned type,
405 // but isn't actually any bigger (like unsigned int and long
406 // on most 32-bit systems). Use the unsigned type corresponding
407 // to the signed type.
408 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
409 }
Chris Lattner299b8842008-07-25 21:10:04 +0000410 return destType;
411}
412
413//===----------------------------------------------------------------------===//
414// Semantic Analysis for various Expression Types
415//===----------------------------------------------------------------------===//
416
417
Steve Naroff87d58b42007-09-16 03:34:24 +0000418/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000419/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
420/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
421/// multiple tokens. However, the common case is that StringToks points to one
422/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000423///
424Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000425Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000426 assert(NumStringToks && "Must have at least one string!");
427
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000428 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000429 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000430 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000431
432 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
433 for (unsigned i = 0; i != NumStringToks; ++i)
434 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000435
Chris Lattnera6dcce32008-02-11 00:02:17 +0000436 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000437 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000438 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000439
440 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
441 if (getLangOptions().CPlusPlus)
442 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000443
Chris Lattnera6dcce32008-02-11 00:02:17 +0000444 // Get an array type for the string, according to C99 6.4.5. This includes
445 // the nul terminator character as well as the string length for pascal
446 // strings.
447 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattner14032222009-02-26 23:01:51 +0000448 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000449 ArrayType::Normal, 0);
Chris Lattnerc3144742009-02-18 05:49:11 +0000450
Chris Lattner4b009652007-07-25 00:24:17 +0000451 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattneraa491192009-02-18 06:40:38 +0000452 return Owned(StringLiteral::Create(Context, Literal.GetString(),
453 Literal.GetStringLength(),
454 Literal.AnyWide, StrTy,
455 &StringTokLocs[0],
456 StringTokLocs.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000457}
458
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000459/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
460/// CurBlock to VD should cause it to be snapshotted (as we do for auto
461/// variables defined outside the block) or false if this is not needed (e.g.
462/// for values inside the block or for globals).
463///
Chris Lattner0b464252009-04-21 22:26:47 +0000464/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
465/// up-to-date.
466///
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000467static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
468 ValueDecl *VD) {
469 // If the value is defined inside the block, we couldn't snapshot it even if
470 // we wanted to.
471 if (CurBlock->TheDecl == VD->getDeclContext())
472 return false;
473
474 // If this is an enum constant or function, it is constant, don't snapshot.
475 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
476 return false;
477
478 // If this is a reference to an extern, static, or global variable, no need to
479 // snapshot it.
480 // FIXME: What about 'const' variables in C++?
481 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner0b464252009-04-21 22:26:47 +0000482 if (!Var->hasLocalStorage())
483 return false;
484
485 // Blocks that have these can't be constant.
486 CurBlock->hasBlockDeclRefExprs = true;
487
488 // If we have nested blocks, the decl may be declared in an outer block (in
489 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
490 // be defined outside all of the current blocks (in which case the blocks do
491 // all get the bit). Walk the nesting chain.
492 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
493 NextBlock = NextBlock->PrevBlockInfo) {
494 // If we found the defining block for the variable, don't mark the block as
495 // having a reference outside it.
496 if (NextBlock->TheDecl == VD->getDeclContext())
497 break;
498
499 // Otherwise, the DeclRef from the inner block causes the outer one to need
500 // a snapshot as well.
501 NextBlock->hasBlockDeclRefExprs = true;
502 }
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000503
504 return true;
505}
506
507
508
Steve Naroff0acc9c92007-09-15 18:49:24 +0000509/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000510/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000511/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000512/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000513/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000514Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
515 IdentifierInfo &II,
516 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000517 const CXXScopeSpec *SS,
518 bool isAddressOfOperand) {
519 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000520 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000521}
522
Douglas Gregor566782a2009-01-06 05:10:23 +0000523/// BuildDeclRefExpr - Build either a DeclRefExpr or a
524/// QualifiedDeclRefExpr based on whether or not SS is a
525/// nested-name-specifier.
Sebastian Redl0c9da212009-02-03 20:19:35 +0000526DeclRefExpr *
527Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
528 bool TypeDependent, bool ValueDependent,
529 const CXXScopeSpec *SS) {
Douglas Gregor7e508262009-03-19 03:51:16 +0000530 if (SS && !SS->isEmpty()) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000531 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
532 ValueDependent, SS->getRange(),
Douglas Gregor041e9292009-03-26 23:56:24 +0000533 static_cast<NestedNameSpecifier *>(SS->getScopeRep()));
Douglas Gregor7e508262009-03-19 03:51:16 +0000534 } else
Steve Naroff774e4152009-01-21 00:14:39 +0000535 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000536}
537
Douglas Gregor723d3332009-01-07 00:43:41 +0000538/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
539/// variable corresponding to the anonymous union or struct whose type
540/// is Record.
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000541static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
542 RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000543 assert(Record->isAnonymousStructOrUnion() &&
544 "Record must be an anonymous struct or union!");
545
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000546 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000547 // be an O(1) operation rather than a slow walk through DeclContext's
548 // vector (which itself will be eliminated). DeclGroups might make
549 // this even better.
550 DeclContext *Ctx = Record->getDeclContext();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000551 for (DeclContext::decl_iterator D = Ctx->decls_begin(Context),
552 DEnd = Ctx->decls_end(Context);
Douglas Gregor723d3332009-01-07 00:43:41 +0000553 D != DEnd; ++D) {
554 if (*D == Record) {
555 // The object for the anonymous struct/union directly
556 // follows its type in the list of declarations.
557 ++D;
558 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000559 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000560 return *D;
561 }
562 }
563
564 assert(false && "Missing object for anonymous record");
565 return 0;
566}
567
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000568/// \brief Given a field that represents a member of an anonymous
569/// struct/union, build the path from that field's context to the
570/// actual member.
571///
572/// Construct the sequence of field member references we'll have to
573/// perform to get to the field in the anonymous union/struct. The
574/// list of members is built from the field outward, so traverse it
575/// backwards to go from an object in the current context to the field
576/// we found.
577///
578/// \returns The variable from which the field access should begin,
579/// for an anonymous struct/union that is not a member of another
580/// class. Otherwise, returns NULL.
581VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
582 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000583 assert(Field->getDeclContext()->isRecord() &&
584 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
585 && "Field must be stored inside an anonymous struct or union");
586
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000587 Path.push_back(Field);
Douglas Gregor723d3332009-01-07 00:43:41 +0000588 VarDecl *BaseObject = 0;
589 DeclContext *Ctx = Field->getDeclContext();
590 do {
591 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000592 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000593 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000594 Path.push_back(AnonField);
Douglas Gregor723d3332009-01-07 00:43:41 +0000595 else {
596 BaseObject = cast<VarDecl>(AnonObject);
597 break;
598 }
599 Ctx = Ctx->getParent();
600 } while (Ctx->isRecord() &&
601 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000602
603 return BaseObject;
604}
605
606Sema::OwningExprResult
607Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
608 FieldDecl *Field,
609 Expr *BaseObjectExpr,
610 SourceLocation OpLoc) {
611 llvm::SmallVector<FieldDecl *, 4> AnonFields;
612 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
613 AnonFields);
614
Douglas Gregor723d3332009-01-07 00:43:41 +0000615 // Build the expression that refers to the base object, from
616 // which we will build a sequence of member references to each
617 // of the anonymous union objects and, eventually, the field we
618 // found via name lookup.
619 bool BaseObjectIsPointer = false;
620 unsigned ExtraQuals = 0;
621 if (BaseObject) {
622 // BaseObject is an anonymous struct/union variable (and is,
623 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000624 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff774e4152009-01-21 00:14:39 +0000625 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump9afab102009-02-19 03:04:26 +0000626 SourceLocation());
Douglas Gregor723d3332009-01-07 00:43:41 +0000627 ExtraQuals
628 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
629 } else if (BaseObjectExpr) {
630 // The caller provided the base object expression. Determine
631 // whether its a pointer and whether it adds any qualifiers to the
632 // anonymous struct/union fields we're looking into.
633 QualType ObjectType = BaseObjectExpr->getType();
634 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
635 BaseObjectIsPointer = true;
636 ObjectType = ObjectPtr->getPointeeType();
637 }
638 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
639 } else {
640 // We've found a member of an anonymous struct/union that is
641 // inside a non-anonymous struct/union, so in a well-formed
642 // program our base object expression is "this".
643 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
644 if (!MD->isStatic()) {
645 QualType AnonFieldType
646 = Context.getTagDeclType(
647 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
648 QualType ThisType = Context.getTagDeclType(MD->getParent());
649 if ((Context.getCanonicalType(AnonFieldType)
650 == Context.getCanonicalType(ThisType)) ||
651 IsDerivedFrom(ThisType, AnonFieldType)) {
652 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000653 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000654 MD->getThisType(Context));
Douglas Gregor723d3332009-01-07 00:43:41 +0000655 BaseObjectIsPointer = true;
656 }
657 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000658 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
659 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000660 }
661 ExtraQuals = MD->getTypeQualifiers();
662 }
663
664 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000665 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
666 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000667 }
668
669 // Build the implicit member references to the field of the
670 // anonymous struct/union.
671 Expr *Result = BaseObjectExpr;
672 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
673 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
674 FI != FIEnd; ++FI) {
675 QualType MemberType = (*FI)->getType();
676 if (!(*FI)->isMutable()) {
677 unsigned combinedQualifiers
678 = MemberType.getCVRQualifiers() | ExtraQuals;
679 MemberType = MemberType.getQualifiedType(combinedQualifiers);
680 }
Steve Naroff774e4152009-01-21 00:14:39 +0000681 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
682 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000683 BaseObjectIsPointer = false;
684 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregor723d3332009-01-07 00:43:41 +0000685 }
686
Sebastian Redlcd883f72009-01-18 18:53:16 +0000687 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000688}
689
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000690/// ActOnDeclarationNameExpr - The parser has read some kind of name
691/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
692/// performs lookup on that name and returns an expression that refers
693/// to that name. This routine isn't directly called from the parser,
694/// because the parser doesn't know about DeclarationName. Rather,
695/// this routine is called by ActOnIdentifierExpr,
696/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
697/// which form the DeclarationName from the corresponding syntactic
698/// forms.
699///
700/// HasTrailingLParen indicates whether this identifier is used in a
701/// function call context. LookupCtx is only used for a C++
702/// qualified-id (foo::bar) to indicate the class or namespace that
703/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000704///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000705/// isAddressOfOperand means that this expression is the direct operand
706/// of an address-of operator. This matters because this is the only
707/// situation where a qualified name referencing a non-static member may
708/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000709Sema::OwningExprResult
710Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
711 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000712 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000713 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000714 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000715 if (SS && SS->isInvalid())
716 return ExprError();
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000717
718 // C++ [temp.dep.expr]p3:
719 // An id-expression is type-dependent if it contains:
720 // -- a nested-name-specifier that contains a class-name that
721 // names a dependent type.
722 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000723 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
724 Loc, SS->getRange(),
Douglas Gregor041e9292009-03-26 23:56:24 +0000725 static_cast<NestedNameSpecifier *>(SS->getScopeRep())));
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000726 }
727
Douglas Gregor411889e2009-02-13 23:20:09 +0000728 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
729 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000730
Sebastian Redlcd883f72009-01-18 18:53:16 +0000731 if (Lookup.isAmbiguous()) {
732 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
733 SS && SS->isSet() ? SS->getRange()
734 : SourceRange());
735 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000736 }
737
738 NamedDecl *D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000739
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000740 // If this reference is in an Objective-C method, then ivar lookup happens as
741 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000742 IdentifierInfo *II = Name.getAsIdentifierInfo();
743 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000744 // There are two cases to handle here. 1) scoped lookup could have failed,
745 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000746 // found a decl, but that decl is outside the current instance method (i.e.
747 // a global variable). In these two cases, we do a lookup for an ivar with
748 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000749 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000750 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000751 ObjCInterfaceDecl *ClassDeclared;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000752 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(Context, II,
753 ClassDeclared)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000754 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000755 if (DiagnoseUseOfDecl(IV, Loc))
756 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000757
758 // If we're referencing an invalid decl, just return this as a silent
759 // error node. The error diagnostic was already emitted on the decl.
760 if (IV->isInvalidDecl())
761 return ExprError();
762
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000763 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
764 // If a class method attemps to use a free standing ivar, this is
765 // an error.
766 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
767 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
768 << IV->getDeclName());
769 // If a class method uses a global variable, even if an ivar with
770 // same name exists, use the global.
771 if (!IsClsMethod) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000772 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
773 ClassDeclared != IFace)
774 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000775 // FIXME: This should use a new expr for a direct reference, don't turn
776 // this into Self->ivar, just return a BareIVarExpr or something.
777 IdentifierInfo &II = Context.Idents.get("self");
778 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Daniel Dunbarf5254bd2009-04-21 01:19:28 +0000779 return Owned(new (Context)
780 ObjCIvarRefExpr(IV, IV->getType(), Loc,
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000781 SelfExpr.takeAs<Expr>(), true, true));
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000782 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000783 }
784 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000785 else if (getCurMethodDecl()->isInstanceMethod()) {
786 // We should warn if a local variable hides an ivar.
787 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000788 ObjCInterfaceDecl *ClassDeclared;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000789 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(Context, II,
790 ClassDeclared)) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000791 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
792 IFace == ClassDeclared)
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000793 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000794 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000795 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000796 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000797 if (D == 0 && II->isStr("super")) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000798 QualType T;
799
800 if (getCurMethodDecl()->isInstanceMethod())
801 T = Context.getPointerType(Context.getObjCInterfaceType(
802 getCurMethodDecl()->getClassInterface()));
803 else
804 T = Context.getObjCClassType();
Steve Naroff774e4152009-01-21 00:14:39 +0000805 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000806 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000807 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000808
Douglas Gregoraa57e862009-02-18 21:56:37 +0000809 // Determine whether this name might be a candidate for
810 // argument-dependent lookup.
811 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
812 HasTrailingLParen;
813
814 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000815 // We've seen something of the form
816 //
817 // identifier(
818 //
819 // and we did not find any entity by the name
820 // "identifier". However, this identifier is still subject to
821 // argument-dependent lookup, so keep track of the name.
822 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
823 Context.OverloadTy,
824 Loc));
825 }
826
Chris Lattner4b009652007-07-25 00:24:17 +0000827 if (D == 0) {
828 // Otherwise, this could be an implicitly declared function reference (legal
829 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000830 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000831 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000832 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000833 else {
834 // If this name wasn't predeclared and if this is not a function call,
835 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000836 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000837 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
838 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000839 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
840 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000841 return ExprError(Diag(Loc, diag::err_undeclared_use)
842 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000843 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000844 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000845 }
846 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000847
Sebastian Redl0c9da212009-02-03 20:19:35 +0000848 // If this is an expression of the form &Class::member, don't build an
849 // implicit member ref, because we want a pointer to the member in general,
850 // not any specific instance's member.
851 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000852 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor09be81b2009-02-04 17:27:36 +0000853 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000854 QualType DType;
855 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
856 DType = FD->getType().getNonReferenceType();
857 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
858 DType = Method->getType();
859 } else if (isa<OverloadedFunctionDecl>(D)) {
860 DType = Context.OverloadTy;
861 }
862 // Could be an inner type. That's diagnosed below, so ignore it here.
863 if (!DType.isNull()) {
864 // The pointer is type- and value-dependent if it points into something
865 // dependent.
866 bool Dependent = false;
867 for (; DC; DC = DC->getParent()) {
868 // FIXME: could stop early at namespace scope.
869 if (DC->isRecord()) {
870 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
871 if (Context.getTypeDeclType(Record)->isDependentType()) {
872 Dependent = true;
873 break;
874 }
875 }
876 }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000877 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000878 }
879 }
880 }
881
Douglas Gregor723d3332009-01-07 00:43:41 +0000882 // We may have found a field within an anonymous union or struct
883 // (C++ [class.union]).
884 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
885 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
886 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000887
Douglas Gregor3257fb52008-12-22 05:46:06 +0000888 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
889 if (!MD->isStatic()) {
890 // C++ [class.mfct.nonstatic]p2:
891 // [...] if name lookup (3.4.1) resolves the name in the
892 // id-expression to a nonstatic nontype member of class X or of
893 // a base class of X, the id-expression is transformed into a
894 // class member access expression (5.2.5) using (*this) (9.3.2)
895 // as the postfix-expression to the left of the '.' operator.
896 DeclContext *Ctx = 0;
897 QualType MemberType;
898 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
899 Ctx = FD->getDeclContext();
900 MemberType = FD->getType();
901
902 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
903 MemberType = RefType->getPointeeType();
904 else if (!FD->isMutable()) {
905 unsigned combinedQualifiers
906 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
907 MemberType = MemberType.getQualifiedType(combinedQualifiers);
908 }
909 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
910 if (!Method->isStatic()) {
911 Ctx = Method->getParent();
912 MemberType = Method->getType();
913 }
914 } else if (OverloadedFunctionDecl *Ovl
915 = dyn_cast<OverloadedFunctionDecl>(D)) {
916 for (OverloadedFunctionDecl::function_iterator
917 Func = Ovl->function_begin(),
918 FuncEnd = Ovl->function_end();
919 Func != FuncEnd; ++Func) {
920 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
921 if (!DMethod->isStatic()) {
922 Ctx = Ovl->getDeclContext();
923 MemberType = Context.OverloadTy;
924 break;
925 }
926 }
927 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000928
929 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000930 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
931 QualType ThisType = Context.getTagDeclType(MD->getParent());
932 if ((Context.getCanonicalType(CtxType)
933 == Context.getCanonicalType(ThisType)) ||
934 IsDerivedFrom(ThisType, CtxType)) {
935 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000936 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000937 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +0000938 return Owned(new (Context) MemberExpr(This, true, D,
Eli Friedman1653e232009-04-29 17:56:47 +0000939 Loc, MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000940 }
941 }
942 }
943 }
944
Douglas Gregor8acb7272008-12-11 16:49:14 +0000945 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000946 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
947 if (MD->isStatic())
948 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000949 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
950 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000951 }
952
Douglas Gregor3257fb52008-12-22 05:46:06 +0000953 // Any other ways we could have found the field in a well-formed
954 // program would have been turned into implicit member expressions
955 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000956 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
957 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000958 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000959
Chris Lattner4b009652007-07-25 00:24:17 +0000960 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000961 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000962 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000963 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000964 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000965 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000966
Steve Naroffd6163f32008-09-05 22:11:13 +0000967 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000968 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000969 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
970 false, false, SS));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000971 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
972 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
973 false, false, SS));
Steve Naroffd6163f32008-09-05 22:11:13 +0000974 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000975
Douglas Gregoraa57e862009-02-18 21:56:37 +0000976 // Check whether this declaration can be used. Note that we suppress
977 // this check when we're going to perform argument-dependent lookup
978 // on this function name, because this might not be the function
979 // that overload resolution actually selects.
980 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
981 return ExprError();
982
Douglas Gregor48840c72008-12-10 23:01:14 +0000983 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000984 // Warn about constructs like:
985 // if (void *X = foo()) { ... } else { X }.
986 // In the else block, the pointer is always false.
Douglas Gregor48840c72008-12-10 23:01:14 +0000987 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
988 Scope *CheckS = S;
989 while (CheckS) {
990 if (CheckS->isWithinElse() &&
Chris Lattner5261d0c2009-03-28 19:18:32 +0000991 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
Douglas Gregor48840c72008-12-10 23:01:14 +0000992 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000993 ExprError(Diag(Loc, diag::warn_value_always_false)
994 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000995 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000996 ExprError(Diag(Loc, diag::warn_value_always_zero)
997 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000998 break;
999 }
1000
1001 // Move up one more control parent to check again.
1002 CheckS = CheckS->getControlParent();
1003 if (CheckS)
1004 CheckS = CheckS->getParent();
1005 }
1006 }
Douglas Gregor1f88aa72009-02-25 16:33:18 +00001007 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(VD)) {
1008 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1009 // C99 DR 316 says that, if a function type comes from a
1010 // function definition (without a prototype), that type is only
1011 // used for checking compatibility. Therefore, when referencing
1012 // the function, we pretend that we don't have the full function
1013 // type.
1014 QualType T = Func->getType();
1015 QualType NoProtoType = T;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001016 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
1017 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
Douglas Gregor1f88aa72009-02-25 16:33:18 +00001018 return Owned(BuildDeclRefExpr(VD, NoProtoType, Loc, false, false, SS));
1019 }
Douglas Gregor48840c72008-12-10 23:01:14 +00001020 }
Steve Naroffd6163f32008-09-05 22:11:13 +00001021
1022 // Only create DeclRefExpr's for valid Decl's.
1023 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001024 return ExprError();
1025
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001026 // If the identifier reference is inside a block, and it refers to a value
1027 // that is outside the block, create a BlockDeclRefExpr instead of a
1028 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1029 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +00001030 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001031 // We do not do this for things like enum constants, global variables, etc,
1032 // as they do not get snapshotted.
1033 //
1034 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001035 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff52059382008-10-10 01:28:17 +00001036 // The BlocksAttr indicates the variable is bound by-reference.
1037 if (VD->getAttr<BlocksAttr>())
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001038 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001039
Steve Naroff52059382008-10-10 01:28:17 +00001040 // Variable will be bound by-copy, make it const within the closure.
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001041 ExprTy.addConst();
1042 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +00001043 }
1044 // If this reference is not in a block or if the referenced variable is
1045 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001046
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001047 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +00001048 bool ValueDependent = false;
1049 if (getLangOptions().CPlusPlus) {
1050 // C++ [temp.dep.expr]p3:
1051 // An id-expression is type-dependent if it contains:
1052 // - an identifier that was declared with a dependent type,
1053 if (VD->getType()->isDependentType())
1054 TypeDependent = true;
1055 // - FIXME: a template-id that is dependent,
1056 // - a conversion-function-id that specifies a dependent type,
1057 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1058 Name.getCXXNameType()->isDependentType())
1059 TypeDependent = true;
1060 // - a nested-name-specifier that contains a class-name that
1061 // names a dependent type.
1062 else if (SS && !SS->isEmpty()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001063 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregora5d84612008-12-10 20:57:37 +00001064 DC; DC = DC->getParent()) {
1065 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +00001066 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +00001067 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1068 if (Context.getTypeDeclType(Record)->isDependentType()) {
1069 TypeDependent = true;
1070 break;
1071 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001072 }
1073 }
1074 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001075
Douglas Gregora5d84612008-12-10 20:57:37 +00001076 // C++ [temp.dep.constexpr]p2:
1077 //
1078 // An identifier is value-dependent if it is:
1079 // - a name declared with a dependent type,
1080 if (TypeDependent)
1081 ValueDependent = true;
1082 // - the name of a non-type template parameter,
1083 else if (isa<NonTypeTemplateParmDecl>(VD))
1084 ValueDependent = true;
1085 // - a constant with integral or enumeration type and is
1086 // initialized with an expression that is value-dependent
1087 // (FIXME!).
1088 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001089
Sebastian Redlcd883f72009-01-18 18:53:16 +00001090 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1091 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +00001092}
1093
Sebastian Redlcd883f72009-01-18 18:53:16 +00001094Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1095 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +00001096 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001097
Chris Lattner4b009652007-07-25 00:24:17 +00001098 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001099 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +00001100 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1101 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1102 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001103 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001104
Chris Lattner7e637512008-01-12 08:14:25 +00001105 // Pre-defined identifiers are of type char[x], where x is the length of the
1106 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001107 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +00001108 if (FunctionDecl *FD = getCurFunctionDecl())
1109 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +00001110 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1111 Length = MD->getSynthesizedMethodSize();
1112 else {
1113 Diag(Loc, diag::ext_predef_outside_function);
1114 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1115 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1116 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001117
1118
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001119 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001120 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001121 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +00001122 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +00001123}
1124
Sebastian Redlcd883f72009-01-18 18:53:16 +00001125Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +00001126 llvm::SmallString<16> CharBuffer;
1127 CharBuffer.resize(Tok.getLength());
1128 const char *ThisTokBegin = &CharBuffer[0];
1129 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001130
Chris Lattner4b009652007-07-25 00:24:17 +00001131 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1132 Tok.getLocation(), PP);
1133 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001134 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001135
1136 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1137
Sebastian Redl75324932009-01-20 22:23:13 +00001138 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1139 Literal.isWide(),
1140 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001141}
1142
Sebastian Redlcd883f72009-01-18 18:53:16 +00001143Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1144 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001145 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1146 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001147 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001148 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001149 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001150 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001151 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001152
Chris Lattner4b009652007-07-25 00:24:17 +00001153 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001154 // Add padding so that NumericLiteralParser can overread by one character.
1155 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001156 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001157
Chris Lattner4b009652007-07-25 00:24:17 +00001158 // Get the spelling of the token, which eliminates trigraphs, etc.
1159 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001160
Chris Lattner4b009652007-07-25 00:24:17 +00001161 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1162 Tok.getLocation(), PP);
1163 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001164 return ExprError();
1165
Chris Lattner1de66eb2007-08-26 03:42:43 +00001166 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001167
Chris Lattner1de66eb2007-08-26 03:42:43 +00001168 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001169 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001170 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001171 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001172 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001173 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001174 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001175 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001176
1177 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1178
Ted Kremenekddedbe22007-11-29 00:56:49 +00001179 // isExact will be set by GetFloatValue().
1180 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +00001181 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
1182 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001183
Chris Lattner1de66eb2007-08-26 03:42:43 +00001184 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001185 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001186 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001187 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001188
Neil Booth7421e9c2007-08-29 22:00:19 +00001189 // long long is a C99 feature.
1190 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001191 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001192 Diag(Tok.getLocation(), diag::ext_longlong);
1193
Chris Lattner4b009652007-07-25 00:24:17 +00001194 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001195 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001196
Chris Lattner4b009652007-07-25 00:24:17 +00001197 if (Literal.GetIntegerValue(ResultVal)) {
1198 // If this value didn't fit into uintmax_t, warn and force to ull.
1199 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001200 Ty = Context.UnsignedLongLongTy;
1201 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001202 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001203 } else {
1204 // If this value fits into a ULL, try to figure out what else it fits into
1205 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001206
Chris Lattner4b009652007-07-25 00:24:17 +00001207 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1208 // be an unsigned int.
1209 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1210
1211 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001212 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001213 if (!Literal.isLong && !Literal.isLongLong) {
1214 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001215 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001216
Chris Lattner4b009652007-07-25 00:24:17 +00001217 // Does it fit in a unsigned int?
1218 if (ResultVal.isIntN(IntSize)) {
1219 // Does it fit in a signed int?
1220 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001221 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001222 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001223 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001224 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001225 }
Chris Lattner4b009652007-07-25 00:24:17 +00001226 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001227
Chris Lattner4b009652007-07-25 00:24:17 +00001228 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001229 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001230 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001231
Chris Lattner4b009652007-07-25 00:24:17 +00001232 // Does it fit in a unsigned long?
1233 if (ResultVal.isIntN(LongSize)) {
1234 // Does it fit in a signed long?
1235 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001236 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001237 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001238 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001239 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001240 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001241 }
1242
Chris Lattner4b009652007-07-25 00:24:17 +00001243 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001244 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001245 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001246
Chris Lattner4b009652007-07-25 00:24:17 +00001247 // Does it fit in a unsigned long long?
1248 if (ResultVal.isIntN(LongLongSize)) {
1249 // Does it fit in a signed long long?
1250 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001251 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001252 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001253 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001254 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001255 }
1256 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001257
Chris Lattner4b009652007-07-25 00:24:17 +00001258 // If we still couldn't decide a type, we probably have something that
1259 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001260 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001261 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001262 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001263 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001264 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001265
Chris Lattnere4068872008-05-09 05:59:00 +00001266 if (ResultVal.getBitWidth() != Width)
1267 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001268 }
Sebastian Redl75324932009-01-20 22:23:13 +00001269 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001270 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001271
Chris Lattner1de66eb2007-08-26 03:42:43 +00001272 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1273 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001274 Res = new (Context) ImaginaryLiteral(Res,
1275 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001276
1277 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001278}
1279
Sebastian Redlcd883f72009-01-18 18:53:16 +00001280Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1281 SourceLocation R, ExprArg Val) {
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001282 Expr *E = Val.takeAs<Expr>();
Chris Lattner48d7f382008-04-02 04:24:33 +00001283 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001284 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001285}
1286
1287/// The UsualUnaryConversions() function is *not* called by this routine.
1288/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001289bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001290 SourceLocation OpLoc,
1291 const SourceRange &ExprRange,
1292 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001293 if (exprType->isDependentType())
1294 return false;
1295
Chris Lattner4b009652007-07-25 00:24:17 +00001296 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001297 if (isa<FunctionType>(exprType)) {
Chris Lattner95933c12009-04-24 00:30:45 +00001298 // alignof(function) is allowed as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001299 if (isSizeof)
1300 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1301 return false;
1302 }
1303
Chris Lattner95933c12009-04-24 00:30:45 +00001304 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001305 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001306 Diag(OpLoc, diag::ext_sizeof_void_type)
1307 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001308 return false;
1309 }
Chris Lattnere1127c42009-04-21 19:55:16 +00001310
Chris Lattner95933c12009-04-24 00:30:45 +00001311 if (RequireCompleteType(OpLoc, exprType,
1312 isSizeof ? diag::err_sizeof_incomplete_type :
1313 diag::err_alignof_incomplete_type,
1314 ExprRange))
1315 return true;
1316
1317 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianbf2b0952009-04-24 17:34:33 +00001318 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner95933c12009-04-24 00:30:45 +00001319 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnerf3ce8572009-04-24 22:30:50 +00001320 << exprType << isSizeof << ExprRange;
1321 return true;
Chris Lattnere1127c42009-04-21 19:55:16 +00001322 }
1323
Chris Lattner95933c12009-04-24 00:30:45 +00001324 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001325}
1326
Chris Lattner8d9f7962009-01-24 20:17:12 +00001327bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1328 const SourceRange &ExprRange) {
1329 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001330
Chris Lattner8d9f7962009-01-24 20:17:12 +00001331 // alignof decl is always ok.
1332 if (isa<DeclRefExpr>(E))
1333 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001334
1335 // Cannot know anything else if the expression is dependent.
1336 if (E->isTypeDependent())
1337 return false;
1338
Chris Lattner8d9f7962009-01-24 20:17:12 +00001339 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1340 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1341 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001342 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001343 return true;
1344 }
1345 // Other fields are ok.
1346 return false;
1347 }
1348 }
1349 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1350}
1351
Douglas Gregor396f1142009-03-13 21:01:28 +00001352/// \brief Build a sizeof or alignof expression given a type operand.
1353Action::OwningExprResult
1354Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1355 bool isSizeOf, SourceRange R) {
1356 if (T.isNull())
1357 return ExprError();
1358
1359 if (!T->isDependentType() &&
1360 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1361 return ExprError();
1362
1363 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1364 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1365 Context.getSizeType(), OpLoc,
1366 R.getEnd()));
1367}
1368
1369/// \brief Build a sizeof or alignof expression given an expression
1370/// operand.
1371Action::OwningExprResult
1372Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1373 bool isSizeOf, SourceRange R) {
1374 // Verify that the operand is valid.
1375 bool isInvalid = false;
1376 if (E->isTypeDependent()) {
1377 // Delay type-checking for type-dependent expressions.
1378 } else if (!isSizeOf) {
1379 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
1380 } else if (E->isBitField()) { // C99 6.5.3.4p1.
1381 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1382 isInvalid = true;
1383 } else {
1384 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1385 }
1386
1387 if (isInvalid)
1388 return ExprError();
1389
1390 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1391 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1392 Context.getSizeType(), OpLoc,
1393 R.getEnd()));
1394}
1395
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001396/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1397/// the same for @c alignof and @c __alignof
1398/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001399Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001400Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1401 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001402 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001403 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001404
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001405 if (isType) {
Douglas Gregor396f1142009-03-13 21:01:28 +00001406 QualType ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1407 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1408 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001409
Douglas Gregor396f1142009-03-13 21:01:28 +00001410 // Get the end location.
1411 Expr *ArgEx = (Expr *)TyOrEx;
1412 Action::OwningExprResult Result
1413 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1414
1415 if (Result.isInvalid())
1416 DeleteExpr(ArgEx);
1417
1418 return move(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001419}
1420
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001421QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001422 if (V->isTypeDependent())
1423 return Context.DependentTy;
Chris Lattner03931a72007-08-24 21:16:53 +00001424
Chris Lattnera16e42d2007-08-26 05:39:26 +00001425 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001426 if (const ComplexType *CT = V->getType()->getAsComplexType())
1427 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001428
1429 // Otherwise they pass through real integer and floating point types here.
1430 if (V->getType()->isArithmeticType())
1431 return V->getType();
1432
1433 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001434 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1435 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001436 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001437}
1438
1439
Chris Lattner4b009652007-07-25 00:24:17 +00001440
Sebastian Redl8b769972009-01-19 00:08:26 +00001441Action::OwningExprResult
1442Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1443 tok::TokenKind Kind, ExprArg Input) {
1444 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001445
Chris Lattner4b009652007-07-25 00:24:17 +00001446 UnaryOperator::Opcode Opc;
1447 switch (Kind) {
1448 default: assert(0 && "Unknown unary op!");
1449 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1450 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1451 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001452
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001453 if (getLangOptions().CPlusPlus &&
1454 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1455 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001456 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001457 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1458
1459 // C++ [over.inc]p1:
1460 //
1461 // [...] If the function is a member function with one
1462 // parameter (which shall be of type int) or a non-member
1463 // function with two parameters (the second of which shall be
1464 // of type int), it defines the postfix increment operator ++
1465 // for objects of that type. When the postfix increment is
1466 // called as a result of using the ++ operator, the int
1467 // argument will have value zero.
1468 Expr *Args[2] = {
1469 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001470 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1471 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001472 };
1473
1474 // Build the candidate set for overloading
1475 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001476 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001477
1478 // Perform overload resolution.
1479 OverloadCandidateSet::iterator Best;
1480 switch (BestViableFunction(CandidateSet, Best)) {
1481 case OR_Success: {
1482 // We found a built-in operator or an overloaded operator.
1483 FunctionDecl *FnDecl = Best->Function;
1484
1485 if (FnDecl) {
1486 // We matched an overloaded operator. Build a call to that
1487 // operator.
1488
1489 // Convert the arguments.
1490 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1491 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001492 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001493 } else {
1494 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001495 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001496 FnDecl->getParamDecl(0)->getType(),
1497 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001498 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001499 }
1500
1501 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001502 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001503 = FnDecl->getType()->getAsFunctionType()->getResultType();
1504 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001505
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001506 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001507 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001508 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001509 UsualUnaryConversions(FnExpr);
1510
Sebastian Redl8b769972009-01-19 00:08:26 +00001511 Input.release();
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001512 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1513 Args, 2, ResultTy,
1514 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001515 } else {
1516 // We matched a built-in operator. Convert the arguments, then
1517 // break out so that we will build the appropriate built-in
1518 // operator node.
1519 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1520 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001521 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001522
1523 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001524 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001525 }
1526
1527 case OR_No_Viable_Function:
1528 // No viable function; fall through to handling this as a
1529 // built-in operator, which will produce an error message for us.
1530 break;
1531
1532 case OR_Ambiguous:
1533 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1534 << UnaryOperator::getOpcodeStr(Opc)
1535 << Arg->getSourceRange();
1536 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001537 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001538
1539 case OR_Deleted:
1540 Diag(OpLoc, diag::err_ovl_deleted_oper)
1541 << Best->Function->isDeleted()
1542 << UnaryOperator::getOpcodeStr(Opc)
1543 << Arg->getSourceRange();
1544 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1545 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001546 }
1547
1548 // Either we found no viable overloaded operator or we matched a
1549 // built-in operator. In either case, fall through to trying to
1550 // build a built-in operation.
1551 }
1552
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001553 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1554 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001555 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001556 return ExprError();
1557 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001558 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001559}
1560
Sebastian Redl8b769972009-01-19 00:08:26 +00001561Action::OwningExprResult
1562Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1563 ExprArg Idx, SourceLocation RLoc) {
1564 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1565 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001566
Douglas Gregor80723c52008-11-19 17:17:41 +00001567 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001568 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001569 LHSExp->getType()->isEnumeralType() ||
1570 RHSExp->getType()->isRecordType() ||
1571 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001572 // Add the appropriate overloaded operators (C++ [over.match.oper])
1573 // to the candidate set.
1574 OverloadCandidateSet CandidateSet;
1575 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001576 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1577 SourceRange(LLoc, RLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001578
Douglas Gregor80723c52008-11-19 17:17:41 +00001579 // Perform overload resolution.
1580 OverloadCandidateSet::iterator Best;
1581 switch (BestViableFunction(CandidateSet, Best)) {
1582 case OR_Success: {
1583 // We found a built-in operator or an overloaded operator.
1584 FunctionDecl *FnDecl = Best->Function;
1585
1586 if (FnDecl) {
1587 // We matched an overloaded operator. Build a call to that
1588 // operator.
1589
1590 // Convert the arguments.
1591 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1592 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1593 PerformCopyInitialization(RHSExp,
1594 FnDecl->getParamDecl(0)->getType(),
1595 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001596 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001597 } else {
1598 // Convert the arguments.
1599 if (PerformCopyInitialization(LHSExp,
1600 FnDecl->getParamDecl(0)->getType(),
1601 "passing") ||
1602 PerformCopyInitialization(RHSExp,
1603 FnDecl->getParamDecl(1)->getType(),
1604 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001605 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001606 }
1607
1608 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001609 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001610 = FnDecl->getType()->getAsFunctionType()->getResultType();
1611 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001612
Douglas Gregor80723c52008-11-19 17:17:41 +00001613 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001614 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1615 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001616 UsualUnaryConversions(FnExpr);
1617
Sebastian Redl8b769972009-01-19 00:08:26 +00001618 Base.release();
1619 Idx.release();
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001620 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1621 FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001622 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001623 } else {
1624 // We matched a built-in operator. Convert the arguments, then
1625 // break out so that we will build the appropriate built-in
1626 // operator node.
1627 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1628 "passing") ||
1629 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1630 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001631 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001632
1633 break;
1634 }
1635 }
1636
1637 case OR_No_Viable_Function:
1638 // No viable function; fall through to handling this as a
1639 // built-in operator, which will produce an error message for us.
1640 break;
1641
1642 case OR_Ambiguous:
1643 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1644 << "[]"
1645 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1646 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001647 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001648
1649 case OR_Deleted:
1650 Diag(LLoc, diag::err_ovl_deleted_oper)
1651 << Best->Function->isDeleted()
1652 << "[]"
1653 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1654 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1655 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001656 }
1657
1658 // Either we found no viable overloaded operator or we matched a
1659 // built-in operator. In either case, fall through to trying to
1660 // build a built-in operation.
1661 }
1662
Chris Lattner4b009652007-07-25 00:24:17 +00001663 // Perform default conversions.
1664 DefaultFunctionArrayConversion(LHSExp);
1665 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001666
Chris Lattner4b009652007-07-25 00:24:17 +00001667 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1668
1669 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001670 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001671 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001672 // and index from the expression types.
1673 Expr *BaseExpr, *IndexExpr;
1674 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001675 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1676 BaseExpr = LHSExp;
1677 IndexExpr = RHSExp;
1678 ResultType = Context.DependentTy;
1679 } else if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001680 BaseExpr = LHSExp;
1681 IndexExpr = RHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001682 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001683 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001684 // Handle the uncommon case of "123[Ptr]".
1685 BaseExpr = RHSExp;
1686 IndexExpr = LHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001687 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001688 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1689 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001690 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001691
Chris Lattner4b009652007-07-25 00:24:17 +00001692 // FIXME: need to deal with const...
1693 ResultType = VTy->getElementType();
Eli Friedmand4614072009-04-25 23:46:54 +00001694 } else if (LHSTy->isArrayType()) {
1695 // If we see an array that wasn't promoted by
1696 // DefaultFunctionArrayConversion, it must be an array that
1697 // wasn't promoted because of the C90 rule that doesn't
1698 // allow promoting non-lvalue arrays. Warn, then
1699 // force the promotion here.
1700 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1701 LHSExp->getSourceRange();
1702 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1703 LHSTy = LHSExp->getType();
1704
1705 BaseExpr = LHSExp;
1706 IndexExpr = RHSExp;
1707 ResultType = LHSTy->getAsPointerType()->getPointeeType();
1708 } else if (RHSTy->isArrayType()) {
1709 // Same as previous, except for 123[f().a] case
1710 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1711 RHSExp->getSourceRange();
1712 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1713 RHSTy = RHSExp->getType();
1714
1715 BaseExpr = RHSExp;
1716 IndexExpr = LHSExp;
1717 ResultType = RHSTy->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001718 } else {
Chris Lattner7264d212009-04-25 22:50:55 +00001719 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1720 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00001721 }
Chris Lattner4b009652007-07-25 00:24:17 +00001722 // C99 6.5.2.1p1
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001723 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner7264d212009-04-25 22:50:55 +00001724 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1725 << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001726
Douglas Gregor05e28f62009-03-24 19:52:54 +00001727 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1728 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1729 // type. Note that Functions are not objects, and that (in C99 parlance)
1730 // incomplete types are not object types.
1731 if (ResultType->isFunctionType()) {
1732 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1733 << ResultType << BaseExpr->getSourceRange();
1734 return ExprError();
1735 }
Chris Lattner95933c12009-04-24 00:30:45 +00001736
Douglas Gregor05e28f62009-03-24 19:52:54 +00001737 if (!ResultType->isDependentType() &&
Chris Lattner95933c12009-04-24 00:30:45 +00001738 RequireCompleteType(LLoc, ResultType, diag::err_subscript_incomplete_type,
Douglas Gregor05e28f62009-03-24 19:52:54 +00001739 BaseExpr->getSourceRange()))
1740 return ExprError();
Chris Lattner95933c12009-04-24 00:30:45 +00001741
1742 // Diagnose bad cases where we step over interface counts.
1743 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1744 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1745 << ResultType << BaseExpr->getSourceRange();
1746 return ExprError();
1747 }
1748
Sebastian Redl8b769972009-01-19 00:08:26 +00001749 Base.release();
1750 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001751 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001752 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001753}
1754
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001755QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001756CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001757 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001758 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001759
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001760 // The vector accessor can't exceed the number of elements.
1761 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001762
Mike Stump9afab102009-02-19 03:04:26 +00001763 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001764 // special names that indicate a subset of exactly half the elements are
1765 // to be selected.
1766 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001767
Nate Begeman1486b502009-01-18 01:47:54 +00001768 // This flag determines whether or not CompName has an 's' char prefix,
1769 // indicating that it is a string of hex values to be used as vector indices.
1770 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001771
1772 // Check that we've found one of the special components, or that the component
1773 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001774 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001775 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1776 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001777 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001778 do
1779 compStr++;
1780 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001781 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001782 do
1783 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001784 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001785 }
Nate Begeman1486b502009-01-18 01:47:54 +00001786
Mike Stump9afab102009-02-19 03:04:26 +00001787 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001788 // We didn't get to the end of the string. This means the component names
1789 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001790 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1791 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001792 return QualType();
1793 }
Mike Stump9afab102009-02-19 03:04:26 +00001794
Nate Begeman1486b502009-01-18 01:47:54 +00001795 // Ensure no component accessor exceeds the width of the vector type it
1796 // operates on.
1797 if (!HalvingSwizzle) {
1798 compStr = CompName.getName();
1799
1800 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001801 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001802
1803 while (*compStr) {
1804 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1805 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1806 << baseType << SourceRange(CompLoc);
1807 return QualType();
1808 }
1809 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001810 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001811
Nate Begeman1486b502009-01-18 01:47:54 +00001812 // If this is a halving swizzle, verify that the base type has an even
1813 // number of elements.
1814 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001815 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001816 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001817 return QualType();
1818 }
Mike Stump9afab102009-02-19 03:04:26 +00001819
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001820 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001821 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001822 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001823 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001824 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001825 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1826 : CompName.getLength();
1827 if (HexSwizzle)
1828 CompSize--;
1829
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001830 if (CompSize == 1)
1831 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001832
Nate Begemanaf6ed502008-04-18 23:10:10 +00001833 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001834 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001835 // diagostics look bad. We want extended vector types to appear built-in.
1836 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1837 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1838 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001839 }
1840 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001841}
1842
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001843static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
1844 IdentifierInfo &Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001845 const Selector &Sel,
1846 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001847
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001848 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Context, &Member))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001849 return PD;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001850 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Context, Sel))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001851 return OMD;
1852
1853 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1854 E = PDecl->protocol_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001855 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
1856 Context))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001857 return D;
1858 }
1859 return 0;
1860}
1861
1862static Decl *FindGetterNameDecl(const ObjCQualifiedIdType *QIdTy,
1863 IdentifierInfo &Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001864 const Selector &Sel,
1865 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001866 // Check protocols on qualified interfaces.
1867 Decl *GDecl = 0;
1868 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1869 E = QIdTy->qual_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001870 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Context, &Member)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001871 GDecl = PD;
1872 break;
1873 }
1874 // Also must look for a getter name which uses property syntax.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001875 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Context, Sel)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001876 GDecl = OMD;
1877 break;
1878 }
1879 }
1880 if (!GDecl) {
1881 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1882 E = QIdTy->qual_end(); I != E; ++I) {
1883 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001884 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001885 if (GDecl)
1886 return GDecl;
1887 }
1888 }
1889 return GDecl;
1890}
Chris Lattner2cb744b2009-02-15 22:43:40 +00001891
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001892/// FindMethodInNestedImplementations - Look up a method in current and
1893/// all base class implementations.
1894///
1895ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
1896 const ObjCInterfaceDecl *IFace,
1897 const Selector &Sel) {
1898 ObjCMethodDecl *Method = 0;
Douglas Gregorafd5eb32009-04-24 00:11:27 +00001899 if (ObjCImplementationDecl *ImpDecl
1900 = LookupObjCImplementation(IFace->getIdentifier()))
Douglas Gregorcd19b572009-04-23 01:02:12 +00001901 Method = ImpDecl->getInstanceMethod(Context, Sel);
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001902
1903 if (!Method && IFace->getSuperClass())
1904 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
1905 return Method;
1906}
1907
Sebastian Redl8b769972009-01-19 00:08:26 +00001908Action::OwningExprResult
1909Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1910 tok::TokenKind OpKind, SourceLocation MemberLoc,
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00001911 IdentifierInfo &Member,
Chris Lattner5261d0c2009-03-28 19:18:32 +00001912 DeclPtrTy ObjCImpDecl) {
Anders Carlssonc154a722009-05-01 19:30:39 +00001913 Expr *BaseExpr = Base.takeAs<Expr>();
Steve Naroff2cb66382007-07-26 03:11:44 +00001914 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001915
1916 // Perform default conversions.
1917 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001918
Steve Naroff2cb66382007-07-26 03:11:44 +00001919 QualType BaseType = BaseExpr->getType();
1920 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001921
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001922 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1923 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001924 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001925 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001926 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001927 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001928 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1929 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001930 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001931 return ExprError(Diag(MemberLoc,
1932 diag::err_typecheck_member_reference_arrow)
1933 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001934 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001935
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001936 // Handle field access to simple records. This also handles access to fields
1937 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001938 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001939 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorc84d8932009-03-09 16:13:40 +00001940 if (RequireCompleteType(OpLoc, BaseType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001941 diag::err_typecheck_incomplete_tag,
1942 BaseExpr->getSourceRange()))
1943 return ExprError();
1944
Steve Naroff2cb66382007-07-26 03:11:44 +00001945 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001946 // FIXME: Qualified name lookup for C++ is a bit more complicated
1947 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001948 LookupResult Result
Mike Stump9afab102009-02-19 03:04:26 +00001949 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001950 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001951
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001952 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001953 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1954 << &Member << BaseExpr->getSourceRange());
Chris Lattner84ad8332009-03-31 08:18:48 +00001955 if (Result.isAmbiguous()) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001956 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1957 MemberLoc, BaseExpr->getSourceRange());
1958 return ExprError();
Chris Lattner84ad8332009-03-31 08:18:48 +00001959 }
1960
1961 NamedDecl *MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001962
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001963 // If the decl being referenced had an error, return an error for this
1964 // sub-expr without emitting another error, in order to avoid cascading
1965 // error cases.
1966 if (MemberDecl->isInvalidDecl())
1967 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001968
Douglas Gregoraa57e862009-02-18 21:56:37 +00001969 // Check the use of this field
1970 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1971 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001972
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001973 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001974 // We may have found a field within an anonymous union or struct
1975 // (C++ [class.union]).
1976 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001977 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001978 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001979
Douglas Gregor82d44772008-12-20 23:49:58 +00001980 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1981 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001982 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001983 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1984 MemberType = Ref->getPointeeType();
1985 else {
1986 unsigned combinedQualifiers =
1987 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001988 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001989 combinedQualifiers &= ~QualType::Const;
1990 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1991 }
Eli Friedman76b49832008-02-06 22:48:16 +00001992
Steve Naroff774e4152009-01-21 00:14:39 +00001993 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1994 MemberLoc, MemberType));
Chris Lattner84ad8332009-03-31 08:18:48 +00001995 }
1996
1997 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001998 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Chris Lattner84ad8332009-03-31 08:18:48 +00001999 Var, MemberLoc,
2000 Var->getType().getNonReferenceType()));
2001 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00002002 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Chris Lattner84ad8332009-03-31 08:18:48 +00002003 MemberFn, MemberLoc,
2004 MemberFn->getType()));
2005 if (OverloadedFunctionDecl *Ovl
2006 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00002007 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Chris Lattner84ad8332009-03-31 08:18:48 +00002008 MemberLoc, Context.OverloadTy));
2009 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00002010 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
2011 Enum, MemberLoc, Enum->getType()));
Chris Lattner84ad8332009-03-31 08:18:48 +00002012 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00002013 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2014 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00002015
Douglas Gregor82d44772008-12-20 23:49:58 +00002016 // We found a declaration kind that we didn't expect. This is a
2017 // generic error message that tells the user that she can't refer
2018 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00002019 return ExprError(Diag(MemberLoc,
2020 diag::err_typecheck_member_reference_unknown)
2021 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00002022 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002023
Chris Lattnere9d71612008-07-21 04:59:05 +00002024 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2025 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002026 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002027 ObjCInterfaceDecl *ClassDeclared;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002028 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(Context,
2029 &Member,
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002030 ClassDeclared)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002031 // If the decl being referenced had an error, return an error for this
2032 // sub-expr without emitting another error, in order to avoid cascading
2033 // error cases.
2034 if (IV->isInvalidDecl())
2035 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00002036
2037 // Check whether we can reference this field.
2038 if (DiagnoseUseOfDecl(IV, MemberLoc))
2039 return ExprError();
Steve Naroff8c56ee02009-03-26 16:01:08 +00002040 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2041 IV->getAccessControl() != ObjCIvarDecl::Package) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002042 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2043 if (ObjCMethodDecl *MD = getCurMethodDecl())
2044 ClassOfMethodDecl = MD->getClassInterface();
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00002045 else if (ObjCImpDecl && getCurFunctionDecl()) {
2046 // Case of a c-function declared inside an objc implementation.
2047 // FIXME: For a c-style function nested inside an objc implementation
2048 // class, there is no implementation context available, so we pass down
2049 // the context as argument to this routine. Ideally, this context need
2050 // be passed down in the AST node and somehow calculated from the AST
2051 // for a function decl.
Chris Lattner5261d0c2009-03-28 19:18:32 +00002052 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00002053 if (ObjCImplementationDecl *IMPD =
2054 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2055 ClassOfMethodDecl = IMPD->getClassInterface();
2056 else if (ObjCCategoryImplDecl* CatImplClass =
2057 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2058 ClassOfMethodDecl = CatImplClass->getClassInterface();
Steve Narofff9606572009-03-04 18:34:24 +00002059 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002060
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00002061 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002062 if (ClassDeclared != IFTy->getDecl() ||
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00002063 ClassOfMethodDecl != ClassDeclared)
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002064 Diag(MemberLoc, diag::error_private_ivar_access) << IV->getDeclName();
2065 }
2066 // @protected
2067 else if (!IFTy->getDecl()->isSuperClassOf(ClassOfMethodDecl))
2068 Diag(MemberLoc, diag::error_protected_ivar_access) << IV->getDeclName();
2069 }
Mike Stump9afab102009-02-19 03:04:26 +00002070
Daniel Dunbarf5254bd2009-04-21 01:19:28 +00002071 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +00002072 MemberLoc, BaseExpr,
Daniel Dunbarf5254bd2009-04-21 01:19:28 +00002073 OpKind == tok::arrow));
Fariborz Jahanian09772392008-12-13 22:20:28 +00002074 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002075 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
2076 << IFTy->getDecl()->getDeclName() << &Member
2077 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00002078 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002079
Chris Lattnere9d71612008-07-21 04:59:05 +00002080 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2081 // pointer to a (potentially qualified) interface type.
2082 const PointerType *PTy;
2083 const ObjCInterfaceType *IFTy;
2084 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
2085 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
2086 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00002087
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002088 // Search for a declared property first.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002089 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Context,
2090 &Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002091 // Check whether we can reference this property.
2092 if (DiagnoseUseOfDecl(PD, MemberLoc))
2093 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00002094
Steve Naroff774e4152009-01-21 00:14:39 +00002095 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002096 MemberLoc, BaseExpr));
2097 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002098
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002099 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00002100 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
2101 E = IFTy->qual_end(); I != E; ++I)
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002102 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Context,
2103 &Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002104 // Check whether we can reference this property.
2105 if (DiagnoseUseOfDecl(PD, MemberLoc))
2106 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00002107
Steve Naroff774e4152009-01-21 00:14:39 +00002108 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002109 MemberLoc, BaseExpr));
2110 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002111
2112 // If that failed, look for an "implicit" property by seeing if the nullary
2113 // selector is implemented.
2114
2115 // FIXME: The logic for looking up nullary and unary selectors should be
2116 // shared with the code in ActOnInstanceMessage.
2117
2118 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002119 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Context, Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002120
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002121 // If this reference is in an @implementation, check for 'private' methods.
2122 if (!Getter)
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002123 Getter = FindMethodInNestedImplementations(IFace, Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002124
Steve Naroff04151f32008-10-22 19:16:27 +00002125 // Look through local category implementations associated with the class.
2126 if (!Getter) {
2127 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
2128 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
Douglas Gregorcd19b572009-04-23 01:02:12 +00002129 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Context, Sel);
Steve Naroff04151f32008-10-22 19:16:27 +00002130 }
2131 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002132 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002133 // Check if we can reference this property.
2134 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2135 return ExprError();
Steve Naroffdede0c92009-03-11 13:48:17 +00002136 }
2137 // If we found a getter then this may be a valid dot-reference, we
2138 // will look for the matching setter, in case it is needed.
2139 Selector SetterSel =
2140 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2141 PP.getSelectorTable(), &Member);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002142 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(Context, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002143 if (!Setter) {
2144 // If this reference is in an @implementation, also check for 'private'
2145 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002146 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002147 }
2148 // Look through local category implementations associated with the class.
2149 if (!Setter) {
2150 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
2151 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
Douglas Gregorcd19b572009-04-23 01:02:12 +00002152 Setter = ObjCCategoryImpls[i]->getInstanceMethod(Context, SetterSel);
Fariborz Jahanianc05da422008-11-22 20:25:50 +00002153 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002154 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002155
Steve Naroffdede0c92009-03-11 13:48:17 +00002156 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2157 return ExprError();
2158
2159 if (Getter || Setter) {
2160 QualType PType;
2161
2162 if (Getter)
2163 PType = Getter->getResultType();
2164 else {
2165 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2166 E = Setter->param_end(); PI != E; ++PI)
2167 PType = (*PI)->getType();
2168 }
2169 // FIXME: we must check that the setter has property type.
2170 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2171 Setter, MemberLoc, BaseExpr));
2172 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002173 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2174 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00002175 }
Steve Naroffd1d44402008-10-20 22:53:06 +00002176 // Handle properties on qualified "id" protocols.
2177 const ObjCQualifiedIdType *QIdTy;
2178 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
2179 // Check protocols on qualified interfaces.
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002180 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002181 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002182 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002183 // Check the use of this declaration
2184 if (DiagnoseUseOfDecl(PD, MemberLoc))
2185 return ExprError();
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002186
Steve Naroff774e4152009-01-21 00:14:39 +00002187 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002188 MemberLoc, BaseExpr));
2189 }
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002190 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002191 // Check the use of this method.
2192 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2193 return ExprError();
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002194
Mike Stump9afab102009-02-19 03:04:26 +00002195 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002196 OMD->getResultType(),
2197 OMD, OpLoc, MemberLoc,
2198 NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00002199 }
2200 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002201
2202 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2203 << &Member << BaseType);
Mike Stump9afab102009-02-19 03:04:26 +00002204 }
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002205 // Handle properties on ObjC 'Class' types.
2206 if (OpKind == tok::period && (BaseType == Context.getObjCClassType())) {
2207 // Also must look for a getter name which uses property syntax.
2208 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2209 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002210 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2211 ObjCMethodDecl *Getter;
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002212 // FIXME: need to also look locally in the implementation.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002213 if ((Getter = IFace->lookupClassMethod(Context, Sel))) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002214 // Check the use of this method.
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002215 if (DiagnoseUseOfDecl(Getter, MemberLoc))
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002216 return ExprError();
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002217 }
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002218 // If we found a getter then this may be a valid dot-reference, we
2219 // will look for the matching setter, in case it is needed.
2220 Selector SetterSel =
2221 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2222 PP.getSelectorTable(), &Member);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002223 ObjCMethodDecl *Setter = IFace->lookupClassMethod(Context, SetterSel);
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002224 if (!Setter) {
2225 // If this reference is in an @implementation, also check for 'private'
2226 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002227 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002228 }
2229 // Look through local category implementations associated with the class.
2230 if (!Setter) {
2231 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
2232 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
Douglas Gregorcd19b572009-04-23 01:02:12 +00002233 Setter = ObjCCategoryImpls[i]->getClassMethod(Context, SetterSel);
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002234 }
2235 }
2236
2237 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2238 return ExprError();
2239
2240 if (Getter || Setter) {
2241 QualType PType;
2242
2243 if (Getter)
2244 PType = Getter->getResultType();
2245 else {
2246 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2247 E = Setter->param_end(); PI != E; ++PI)
2248 PType = (*PI)->getType();
2249 }
2250 // FIXME: we must check that the setter has property type.
2251 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2252 Setter, MemberLoc, BaseExpr));
2253 }
2254 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2255 << &Member << BaseType);
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002256 }
2257 }
2258
Chris Lattnera57cf472008-07-21 04:28:12 +00002259 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00002260 if (BaseType->isExtVectorType()) {
Chris Lattnera57cf472008-07-21 04:28:12 +00002261 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2262 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00002263 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002264 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
Steve Naroff774e4152009-01-21 00:14:39 +00002265 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00002266 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002267
Douglas Gregor762da552009-03-27 06:00:30 +00002268 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2269 << BaseType << BaseExpr->getSourceRange();
2270
2271 // If the user is trying to apply -> or . to a function or function
2272 // pointer, it's probably because they forgot parentheses to call
2273 // the function. Suggest the addition of those parentheses.
2274 if (BaseType == Context.OverloadTy ||
2275 BaseType->isFunctionType() ||
2276 (BaseType->isPointerType() &&
2277 BaseType->getAsPointerType()->isFunctionType())) {
2278 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2279 Diag(Loc, diag::note_member_reference_needs_call)
2280 << CodeModificationHint::CreateInsertion(Loc, "()");
2281 }
2282
2283 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00002284}
2285
Douglas Gregor3257fb52008-12-22 05:46:06 +00002286/// ConvertArgumentsForCall - Converts the arguments specified in
2287/// Args/NumArgs to the parameter types of the function FDecl with
2288/// function prototype Proto. Call is the call expression itself, and
2289/// Fn is the function expression. For a C++ member function, this
2290/// routine does not attempt to convert the object argument. Returns
2291/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00002292bool
2293Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002294 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002295 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002296 Expr **Args, unsigned NumArgs,
2297 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00002298 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00002299 // assignment, to the types of the corresponding parameter, ...
2300 unsigned NumArgsInProto = Proto->getNumArgs();
2301 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002302 bool Invalid = false;
2303
Douglas Gregor3257fb52008-12-22 05:46:06 +00002304 // If too few arguments are available (and we don't have default
2305 // arguments for the remaining parameters), don't make the call.
2306 if (NumArgs < NumArgsInProto) {
2307 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2308 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2309 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2310 // Use default arguments for missing arguments
2311 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00002312 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002313 }
2314
2315 // If too many are passed and not variadic, error on the extras and drop
2316 // them.
2317 if (NumArgs > NumArgsInProto) {
2318 if (!Proto->isVariadic()) {
2319 Diag(Args[NumArgsInProto]->getLocStart(),
2320 diag::err_typecheck_call_too_many_args)
2321 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2322 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2323 Args[NumArgs-1]->getLocEnd());
2324 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002325 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002326 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002327 }
2328 NumArgsToCheck = NumArgsInProto;
2329 }
Mike Stump9afab102009-02-19 03:04:26 +00002330
Douglas Gregor3257fb52008-12-22 05:46:06 +00002331 // Continue to check argument types (even if we have too few/many args).
2332 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2333 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00002334
Douglas Gregor3257fb52008-12-22 05:46:06 +00002335 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002336 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002337 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002338
Eli Friedman83dec9e2009-03-22 22:00:50 +00002339 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2340 ProtoArgType,
2341 diag::err_call_incomplete_argument,
2342 Arg->getSourceRange()))
2343 return true;
2344
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002345 // Pass the argument.
2346 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2347 return true;
Mike Stump9afab102009-02-19 03:04:26 +00002348 } else
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002349 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00002350 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002351 QualType ArgType = Arg->getType();
Mike Stump9afab102009-02-19 03:04:26 +00002352
Douglas Gregor3257fb52008-12-22 05:46:06 +00002353 Call->setArg(i, Arg);
2354 }
Mike Stump9afab102009-02-19 03:04:26 +00002355
Douglas Gregor3257fb52008-12-22 05:46:06 +00002356 // If this is a variadic call, handle args passed through "...".
2357 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002358 VariadicCallType CallType = VariadicFunction;
2359 if (Fn->getType()->isBlockPointerType())
2360 CallType = VariadicBlock; // Block
2361 else if (isa<MemberExpr>(Fn))
2362 CallType = VariadicMethod;
2363
Douglas Gregor3257fb52008-12-22 05:46:06 +00002364 // Promote the arguments (C99 6.5.2.2p7).
2365 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2366 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00002367 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002368 Call->setArg(i, Arg);
2369 }
2370 }
2371
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002372 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002373}
2374
Steve Naroff87d58b42007-09-16 03:34:24 +00002375/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002376/// This provides the location of the left/right parens and a list of comma
2377/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002378Action::OwningExprResult
2379Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2380 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002381 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002382 unsigned NumArgs = args.size();
Anders Carlssonc154a722009-05-01 19:30:39 +00002383 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl8b769972009-01-19 00:08:26 +00002384 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002385 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002386 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002387 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002388
Douglas Gregor3257fb52008-12-22 05:46:06 +00002389 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002390 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002391 // in which case we won't do any semantic analysis now.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002392 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
2393 bool Dependent = false;
2394 if (Fn->isTypeDependent())
2395 Dependent = true;
2396 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2397 Dependent = true;
2398
2399 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002400 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002401 Context.DependentTy, RParenLoc));
2402
2403 // Determine whether this is a call to an object (C++ [over.call.object]).
2404 if (Fn->getType()->isRecordType())
2405 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2406 CommaLocs, RParenLoc));
2407
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002408 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002409 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
2410 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
2411 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00002412 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2413 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002414 }
2415
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002416 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00002417 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002418 Expr *FnExpr = Fn;
2419 bool ADL = true;
2420 while (true) {
2421 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2422 FnExpr = IcExpr->getSubExpr();
2423 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002424 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002425 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002426 ADL = false;
2427 FnExpr = PExpr->getSubExpr();
2428 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002429 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002430 == UnaryOperator::AddrOf) {
2431 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002432 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
2433 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2434 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2435 break;
Mike Stump9afab102009-02-19 03:04:26 +00002436 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002437 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2438 UnqualifiedName = DepName->getName();
2439 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002440 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002441 // Any kind of name that does not refer to a declaration (or
2442 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2443 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002444 break;
2445 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002446 }
Mike Stump9afab102009-02-19 03:04:26 +00002447
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002448 OverloadedFunctionDecl *Ovl = 0;
2449 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002450 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002451 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
2452 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002453
Douglas Gregorfcb19192009-02-11 23:02:49 +00002454 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002455 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002456 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002457 ADL = false;
2458
Douglas Gregorfcb19192009-02-11 23:02:49 +00002459 // We don't perform ADL in C.
2460 if (!getLangOptions().CPlusPlus)
2461 ADL = false;
2462
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002463 if (Ovl || ADL) {
Mike Stump9afab102009-02-19 03:04:26 +00002464 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2465 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002466 NumArgs, CommaLocs, RParenLoc, ADL);
2467 if (!FDecl)
2468 return ExprError();
2469
2470 // Update Fn to refer to the actual function selected.
2471 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002472 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002473 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Douglas Gregor1e589cc2009-03-26 23:50:42 +00002474 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2475 QDRExpr->getLocation(),
2476 false, false,
2477 QDRExpr->getQualifierRange(),
2478 QDRExpr->getQualifier());
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002479 else
Mike Stump9afab102009-02-19 03:04:26 +00002480 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002481 Fn->getSourceRange().getBegin());
2482 Fn->Destroy(Context);
2483 Fn = NewFn;
2484 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002485 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002486
2487 // Promote the function operand.
2488 UsualUnaryConversions(Fn);
2489
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002490 // Make the call expr early, before semantic checks. This guarantees cleanup
2491 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002492 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2493 Args, NumArgs,
2494 Context.BoolTy,
2495 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002496
Steve Naroffd6163f32008-09-05 22:11:13 +00002497 const FunctionType *FuncT;
2498 if (!Fn->getType()->isBlockPointerType()) {
2499 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2500 // have type pointer to function".
2501 const PointerType *PT = Fn->getType()->getAsPointerType();
2502 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002503 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2504 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002505 FuncT = PT->getPointeeType()->getAsFunctionType();
2506 } else { // This is a block call.
2507 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2508 getAsFunctionType();
2509 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002510 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002511 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2512 << Fn->getType() << Fn->getSourceRange());
2513
Eli Friedman83dec9e2009-03-22 22:00:50 +00002514 // Check for a valid return type
2515 if (!FuncT->getResultType()->isVoidType() &&
2516 RequireCompleteType(Fn->getSourceRange().getBegin(),
2517 FuncT->getResultType(),
2518 diag::err_call_incomplete_return,
2519 TheCall->getSourceRange()))
2520 return ExprError();
2521
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002522 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002523 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002524
Douglas Gregor4fa58902009-02-26 23:50:07 +00002525 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002526 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002527 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002528 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002529 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002530 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002531
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002532 if (FDecl) {
2533 // Check if we have too few/too many template arguments, based
2534 // on our knowledge of the function definition.
2535 const FunctionDecl *Def = 0;
Douglas Gregore3241e92009-04-18 00:02:19 +00002536 if (FDecl->getBody(Context, Def) && NumArgs != Def->param_size())
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002537 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2538 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2539 }
2540
Steve Naroffdb65e052007-08-28 23:30:39 +00002541 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002542 for (unsigned i = 0; i != NumArgs; i++) {
2543 Expr *Arg = Args[i];
2544 DefaultArgumentPromotion(Arg);
Eli Friedman83dec9e2009-03-22 22:00:50 +00002545 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2546 Arg->getType(),
2547 diag::err_call_incomplete_argument,
2548 Arg->getSourceRange()))
2549 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002550 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002551 }
Chris Lattner4b009652007-07-25 00:24:17 +00002552 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002553
Douglas Gregor3257fb52008-12-22 05:46:06 +00002554 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2555 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002556 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2557 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002558
Chris Lattner2e64c072007-08-10 20:18:51 +00002559 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00002560 if (FDecl)
2561 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002562
Sebastian Redl8b769972009-01-19 00:08:26 +00002563 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002564}
2565
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002566Action::OwningExprResult
2567Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2568 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002569 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002570 QualType literalType = QualType::getFromOpaquePtr(Ty);
2571 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002572 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002573 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002574
Eli Friedman8c2173d2008-05-20 05:22:08 +00002575 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002576 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002577 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2578 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregorc84d8932009-03-09 16:13:40 +00002579 } else if (RequireCompleteType(LParenLoc, literalType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002580 diag::err_typecheck_decl_incomplete_type,
2581 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002582 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002583
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002584 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002585 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002586 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002587
Chris Lattnere5cb5862008-12-04 23:50:19 +00002588 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002589 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002590 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002591 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002592 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002593 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002594 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002595 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002596}
2597
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002598Action::OwningExprResult
2599Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002600 SourceLocation RBraceLoc) {
2601 unsigned NumInit = initlist.size();
2602 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002603
Steve Naroff0acc9c92007-09-15 18:49:24 +00002604 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002605 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002606
Mike Stump9afab102009-02-19 03:04:26 +00002607 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002608 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002609 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002610 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002611}
2612
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002613/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002614bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002615 UsualUnaryConversions(castExpr);
2616
2617 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2618 // type needs to be scalar.
2619 if (castType->isVoidType()) {
2620 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002621 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2622 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002623 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002624 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2625 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2626 (castType->isStructureType() || castType->isUnionType())) {
2627 // GCC struct/union extension: allow cast to self.
Eli Friedman2b128322009-03-23 00:24:07 +00002628 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002629 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2630 << castType << castExpr->getSourceRange();
2631 } else if (castType->isUnionType()) {
2632 // GCC cast to union extension
2633 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2634 RecordDecl::field_iterator Field, FieldEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002635 for (Field = RD->field_begin(Context), FieldEnd = RD->field_end(Context);
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002636 Field != FieldEnd; ++Field) {
2637 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2638 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2639 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2640 << castExpr->getSourceRange();
2641 break;
2642 }
2643 }
2644 if (Field == FieldEnd)
2645 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2646 << castExpr->getType() << castExpr->getSourceRange();
2647 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002648 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002649 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002650 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002651 }
Mike Stump9afab102009-02-19 03:04:26 +00002652 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002653 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002654 return Diag(castExpr->getLocStart(),
2655 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002656 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002657 } else if (castExpr->getType()->isVectorType()) {
2658 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2659 return true;
2660 } else if (castType->isVectorType()) {
2661 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2662 return true;
Steve Naroffff6c8022009-03-04 15:11:40 +00002663 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroff49fd7ad2009-04-08 23:52:26 +00002664 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Eli Friedman970e56c2009-05-01 02:23:58 +00002665 } else if (!castType->isArithmeticType()) {
2666 QualType castExprType = castExpr->getType();
2667 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
2668 return Diag(castExpr->getLocStart(),
2669 diag::err_cast_pointer_from_non_pointer_int)
2670 << castExprType << castExpr->getSourceRange();
2671 } else if (!castExpr->getType()->isArithmeticType()) {
2672 if (!castType->isIntegralType() && castType->isArithmeticType())
2673 return Diag(castExpr->getLocStart(),
2674 diag::err_cast_pointer_to_non_pointer_int)
2675 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002676 }
2677 return false;
2678}
2679
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002680bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002681 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00002682
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002683 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002684 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002685 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00002686 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002687 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002688 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002689 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002690 } else
2691 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002692 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002693 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00002694
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002695 return false;
2696}
2697
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002698Action::OwningExprResult
2699Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2700 SourceLocation RParenLoc, ExprArg Op) {
2701 assert((Ty != 0) && (Op.get() != 0) &&
2702 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002703
Anders Carlssonc154a722009-05-01 19:30:39 +00002704 Expr *castExpr = Op.takeAs<Expr>();
Chris Lattner4b009652007-07-25 00:24:17 +00002705 QualType castType = QualType::getFromOpaquePtr(Ty);
2706
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002707 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002708 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002709 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Mike Stump9afab102009-02-19 03:04:26 +00002710 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002711}
2712
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00002713/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
2714/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00002715/// C99 6.5.15
2716QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2717 SourceLocation QuestionLoc) {
Sebastian Redlbd261962009-04-16 17:51:27 +00002718 // C++ is sufficiently different to merit its own checker.
2719 if (getLangOptions().CPlusPlus)
2720 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
2721
Chris Lattnere2897262009-02-18 04:28:32 +00002722 UsualUnaryConversions(Cond);
2723 UsualUnaryConversions(LHS);
2724 UsualUnaryConversions(RHS);
2725 QualType CondTy = Cond->getType();
2726 QualType LHSTy = LHS->getType();
2727 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002728
2729 // first, check the condition.
Sebastian Redlbd261962009-04-16 17:51:27 +00002730 if (!CondTy->isScalarType()) { // C99 6.5.15p2
2731 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2732 << CondTy;
2733 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002734 }
Mike Stump9afab102009-02-19 03:04:26 +00002735
Chris Lattner992ae932008-01-06 22:42:25 +00002736 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002737
Chris Lattner992ae932008-01-06 22:42:25 +00002738 // If both operands have arithmetic type, do the usual arithmetic conversions
2739 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00002740 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2741 UsualArithmeticConversions(LHS, RHS);
2742 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002743 }
Mike Stump9afab102009-02-19 03:04:26 +00002744
Chris Lattner992ae932008-01-06 22:42:25 +00002745 // If both operands are the same structure or union type, the result is that
2746 // type.
Chris Lattnere2897262009-02-18 04:28:32 +00002747 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
2748 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002749 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00002750 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00002751 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00002752 return LHSTy.getUnqualifiedType();
Eli Friedman2b128322009-03-23 00:24:07 +00002753 // FIXME: Type of conditional expression must be complete in C mode.
Chris Lattner4b009652007-07-25 00:24:17 +00002754 }
Mike Stump9afab102009-02-19 03:04:26 +00002755
Chris Lattner992ae932008-01-06 22:42:25 +00002756 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002757 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00002758 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2759 if (!LHSTy->isVoidType())
2760 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2761 << RHS->getSourceRange();
2762 if (!RHSTy->isVoidType())
2763 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2764 << LHS->getSourceRange();
2765 ImpCastExprToType(LHS, Context.VoidTy);
2766 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00002767 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002768 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002769 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2770 // the type of the other operand."
Chris Lattnere2897262009-02-18 04:28:32 +00002771 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2772 Context.isObjCObjectPointerType(LHSTy)) &&
2773 RHS->isNullPointerConstant(Context)) {
2774 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2775 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002776 }
Chris Lattnere2897262009-02-18 04:28:32 +00002777 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2778 Context.isObjCObjectPointerType(RHSTy)) &&
2779 LHS->isNullPointerConstant(Context)) {
2780 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2781 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002782 }
Mike Stump9afab102009-02-19 03:04:26 +00002783
Chris Lattner0ac51632008-01-06 22:50:31 +00002784 // Handle the case where both operands are pointers before we handle null
2785 // pointer constants in case both operands are null pointer constants.
Chris Lattnere2897262009-02-18 04:28:32 +00002786 if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6
2787 if (const PointerType *RHSPT = RHSTy->getAsPointerType()) {
Chris Lattner71225142007-07-31 21:27:01 +00002788 // get the "pointed to" types
2789 QualType lhptee = LHSPT->getPointeeType();
2790 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002791
Chris Lattner71225142007-07-31 21:27:01 +00002792 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2793 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002794 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002795 // Figure out necessary qualifiers (C99 6.5.15p6)
2796 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002797 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002798 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2799 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002800 return destType;
2801 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002802 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002803 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002804 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002805 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2806 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002807 return destType;
2808 }
Chris Lattner4b009652007-07-25 00:24:17 +00002809
Chris Lattner9c039b52009-02-18 04:38:20 +00002810 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
Chris Lattner676c86a2009-02-19 04:44:58 +00002811 // Two identical pointer types are always compatible.
Chris Lattner9c039b52009-02-18 04:38:20 +00002812 return LHSTy;
2813 }
Mike Stump9afab102009-02-19 03:04:26 +00002814
Chris Lattnere2897262009-02-18 04:28:32 +00002815 QualType compositeType = LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002816
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002817 // If either type is an Objective-C object type then check
2818 // compatibility according to Objective-C.
Mike Stump9afab102009-02-19 03:04:26 +00002819 if (Context.isObjCObjectPointerType(LHSTy) ||
Chris Lattnere2897262009-02-18 04:28:32 +00002820 Context.isObjCObjectPointerType(RHSTy)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002821 // If both operands are interfaces and either operand can be
2822 // assigned to the other, use that type as the composite
2823 // type. This allows
2824 // xxx ? (A*) a : (B*) b
2825 // where B is a subclass of A.
2826 //
2827 // Additionally, as for assignment, if either type is 'id'
2828 // allow silent coercion. Finally, if the types are
2829 // incompatible then make sure to use 'id' as the composite
2830 // type so the result is acceptable for sending messages to.
2831
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002832 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
Mike Stump9afab102009-02-19 03:04:26 +00002833 // It could return the composite type.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002834 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2835 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2836 if (LHSIface && RHSIface &&
2837 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002838 compositeType = LHSTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002839 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002840 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002841 compositeType = RHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002842 } else if (Context.isObjCIdStructType(lhptee) ||
2843 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002844 compositeType = Context.getObjCIdType();
2845 } else {
Chris Lattnere2897262009-02-18 04:28:32 +00002846 Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
Mike Stump9afab102009-02-19 03:04:26 +00002847 << LHSTy << RHSTy
Chris Lattnere2897262009-02-18 04:28:32 +00002848 << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002849 QualType incompatTy = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002850 ImpCastExprToType(LHS, incompatTy);
2851 ImpCastExprToType(RHS, incompatTy);
Mike Stump9afab102009-02-19 03:04:26 +00002852 return incompatTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002853 }
Mike Stump9afab102009-02-19 03:04:26 +00002854 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002855 rhptee.getUnqualifiedType())) {
Chris Lattnere2897262009-02-18 04:28:32 +00002856 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2857 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002858 // In this situation, we assume void* type. No especially good
2859 // reason, but this is what gcc does, and we do have to pick
2860 // to get a consistent AST.
2861 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Chris Lattnere2897262009-02-18 04:28:32 +00002862 ImpCastExprToType(LHS, incompatTy);
2863 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002864 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002865 }
2866 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002867 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2868 // differently qualified versions of compatible types, the result type is
2869 // a pointer to an appropriately qualified version of the *composite*
2870 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002871 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002872 // FIXME: Need to add qualifiers
Chris Lattnere2897262009-02-18 04:28:32 +00002873 ImpCastExprToType(LHS, compositeType);
2874 ImpCastExprToType(RHS, compositeType);
Eli Friedmane38150e2008-05-16 20:37:07 +00002875 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002876 }
Chris Lattner4b009652007-07-25 00:24:17 +00002877 }
Mike Stump9afab102009-02-19 03:04:26 +00002878
Steve Naroff6ba22682009-04-08 17:05:15 +00002879 // GCC compatibility: soften pointer/integer mismatch.
2880 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
2881 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
2882 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
2883 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
2884 return RHSTy;
2885 }
2886 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
2887 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
2888 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
2889 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
2890 return LHSTy;
2891 }
2892
Chris Lattner9c039b52009-02-18 04:38:20 +00002893 // Selection between block pointer types is ok as long as they are the same.
2894 if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() &&
2895 Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))
2896 return LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002897
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002898 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2899 // evaluates to "struct objc_object *" (and is handled above when comparing
Mike Stump9afab102009-02-19 03:04:26 +00002900 // id with statically typed objects).
2901 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002902 // GCC allows qualified id and any Objective-C type to devolve to
2903 // id. Currently localizing to here until clear this should be
2904 // part of ObjCQualifiedIdTypesAreCompatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002905 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
Mike Stump9afab102009-02-19 03:04:26 +00002906 (LHSTy->isObjCQualifiedIdType() &&
Chris Lattnere2897262009-02-18 04:28:32 +00002907 Context.isObjCObjectPointerType(RHSTy)) ||
2908 (RHSTy->isObjCQualifiedIdType() &&
2909 Context.isObjCObjectPointerType(LHSTy))) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002910 // FIXME: This is not the correct composite type. This only
2911 // happens to work because id can more or less be used anywhere,
2912 // however this may change the type of method sends.
2913 // FIXME: gcc adds some type-checking of the arguments and emits
2914 // (confusing) incompatible comparison warnings in some
2915 // cases. Investigate.
2916 QualType compositeType = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002917 ImpCastExprToType(LHS, compositeType);
2918 ImpCastExprToType(RHS, compositeType);
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002919 return compositeType;
2920 }
2921 }
2922
Chris Lattner992ae932008-01-06 22:42:25 +00002923 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002924 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2925 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002926 return QualType();
2927}
2928
Steve Naroff87d58b42007-09-16 03:34:24 +00002929/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002930/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002931Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2932 SourceLocation ColonLoc,
2933 ExprArg Cond, ExprArg LHS,
2934 ExprArg RHS) {
2935 Expr *CondExpr = (Expr *) Cond.get();
2936 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002937
2938 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2939 // was the condition.
2940 bool isLHSNull = LHSExpr == 0;
2941 if (isLHSNull)
2942 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002943
2944 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002945 RHSExpr, QuestionLoc);
2946 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002947 return ExprError();
2948
2949 Cond.release();
2950 LHS.release();
2951 RHS.release();
Mike Stump9afab102009-02-19 03:04:26 +00002952 return Owned(new (Context) ConditionalOperator(CondExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00002953 isLHSNull ? 0 : LHSExpr,
2954 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002955}
2956
Chris Lattner4b009652007-07-25 00:24:17 +00002957
2958// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00002959// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00002960// routine is it effectively iqnores the qualifiers on the top level pointee.
2961// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2962// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00002963Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002964Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2965 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00002966
Chris Lattner4b009652007-07-25 00:24:17 +00002967 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002968 lhptee = lhsType->getAsPointerType()->getPointeeType();
2969 rhptee = rhsType->getAsPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002970
Chris Lattner4b009652007-07-25 00:24:17 +00002971 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002972 lhptee = Context.getCanonicalType(lhptee);
2973 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002974
Chris Lattner005ed752008-01-04 18:04:52 +00002975 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00002976
2977 // C99 6.5.16.1p1: This following citation is common to constraints
2978 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2979 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00002980 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002981 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002982 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002983
Mike Stump9afab102009-02-19 03:04:26 +00002984 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2985 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00002986 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002987 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002988 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002989 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00002990
Chris Lattner4ca3d772008-01-03 22:56:36 +00002991 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002992 assert(rhptee->isFunctionType());
2993 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002994 }
Mike Stump9afab102009-02-19 03:04:26 +00002995
Chris Lattner4ca3d772008-01-03 22:56:36 +00002996 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002997 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002998 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002999
3000 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003001 assert(lhptee->isFunctionType());
3002 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003003 }
Mike Stump9afab102009-02-19 03:04:26 +00003004 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00003005 // unqualified versions of compatible types, ...
Eli Friedman6ca28cb2009-03-22 23:59:44 +00003006 lhptee = lhptee.getUnqualifiedType();
3007 rhptee = rhptee.getUnqualifiedType();
3008 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3009 // Check if the pointee types are compatible ignoring the sign.
3010 // We explicitly check for char so that we catch "char" vs
3011 // "unsigned char" on systems where "char" is unsigned.
3012 if (lhptee->isCharType()) {
3013 lhptee = Context.UnsignedCharTy;
3014 } else if (lhptee->isSignedIntegerType()) {
3015 lhptee = Context.getCorrespondingUnsignedType(lhptee);
3016 }
3017 if (rhptee->isCharType()) {
3018 rhptee = Context.UnsignedCharTy;
3019 } else if (rhptee->isSignedIntegerType()) {
3020 rhptee = Context.getCorrespondingUnsignedType(rhptee);
3021 }
3022 if (lhptee == rhptee) {
3023 // Types are compatible ignoring the sign. Qualifier incompatibility
3024 // takes priority over sign incompatibility because the sign
3025 // warning can be disabled.
3026 if (ConvTy != Compatible)
3027 return ConvTy;
3028 return IncompatiblePointerSign;
3029 }
3030 // General pointer incompatibility takes priority over qualifiers.
3031 return IncompatiblePointer;
3032 }
Chris Lattner005ed752008-01-04 18:04:52 +00003033 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003034}
3035
Steve Naroff3454b6c2008-09-04 15:10:53 +00003036/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3037/// block pointer types are compatible or whether a block and normal pointer
3038/// are compatible. It is more restrict than comparing two function pointer
3039// types.
Mike Stump9afab102009-02-19 03:04:26 +00003040Sema::AssignConvertType
3041Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00003042 QualType rhsType) {
3043 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003044
Steve Naroff3454b6c2008-09-04 15:10:53 +00003045 // get the "pointed to" type (ignoring qualifiers at the top level)
3046 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003047 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
3048
Steve Naroff3454b6c2008-09-04 15:10:53 +00003049 // make sure we operate on the canonical type
3050 lhptee = Context.getCanonicalType(lhptee);
3051 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00003052
Steve Naroff3454b6c2008-09-04 15:10:53 +00003053 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003054
Steve Naroff3454b6c2008-09-04 15:10:53 +00003055 // For blocks we enforce that qualifiers are identical.
3056 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3057 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00003058
Steve Naroff3454b6c2008-09-04 15:10:53 +00003059 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00003060 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003061 return ConvTy;
3062}
3063
Mike Stump9afab102009-02-19 03:04:26 +00003064/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3065/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00003066/// pointers. Here are some objectionable examples that GCC considers warnings:
3067///
3068/// int a, *pint;
3069/// short *pshort;
3070/// struct foo *pfoo;
3071///
3072/// pint = pshort; // warning: assignment from incompatible pointer type
3073/// a = pint; // warning: assignment makes integer from pointer without a cast
3074/// pint = a; // warning: assignment makes pointer from integer without a cast
3075/// pint = pfoo; // warning: assignment from incompatible pointer type
3076///
3077/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00003078/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00003079///
Chris Lattner005ed752008-01-04 18:04:52 +00003080Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003081Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00003082 // Get canonical types. We're not formatting these types, just comparing
3083 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003084 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3085 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00003086
3087 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00003088 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00003089
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003090 // If the left-hand side is a reference type, then we are in a
3091 // (rare!) case where we've allowed the use of references in C,
3092 // e.g., as a parameter type in a built-in function. In this case,
3093 // just make sure that the type referenced is compatible with the
3094 // right-hand side type. The caller is responsible for adjusting
3095 // lhsType so that the resulting expression does not have reference
3096 // type.
3097 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
3098 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00003099 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003100 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003101 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003102
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003103 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
3104 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003105 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00003106 // Relax integer conversions like we do for pointers below.
3107 if (rhsType->isIntegerType())
3108 return IntToPointer;
3109 if (lhsType->isIntegerType())
3110 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00003111 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003112 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003113
Nate Begemanc5f0f652008-07-14 18:02:46 +00003114 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00003115 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00003116 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
3117 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003118 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003119
Nate Begemanc5f0f652008-07-14 18:02:46 +00003120 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00003121 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00003122 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003123 if (getLangOptions().LaxVectorConversions &&
3124 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003125 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00003126 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003127 }
3128 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00003129 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003130
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003131 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00003132 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003133
Chris Lattner390564e2008-04-07 06:49:41 +00003134 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003135 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003136 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003137
Chris Lattner390564e2008-04-07 06:49:41 +00003138 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003139 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003140
Steve Naroffa982c712008-09-29 18:10:17 +00003141 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00003142 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003143 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00003144
3145 // Treat block pointers as objects.
3146 if (getLangOptions().ObjC1 &&
3147 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
3148 return Compatible;
3149 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003150 return Incompatible;
3151 }
3152
3153 if (isa<BlockPointerType>(lhsType)) {
3154 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00003155 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00003156
Steve Naroffa982c712008-09-29 18:10:17 +00003157 // Treat block pointers as objects.
3158 if (getLangOptions().ObjC1 &&
3159 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
3160 return Compatible;
3161
Steve Naroff3454b6c2008-09-04 15:10:53 +00003162 if (rhsType->isBlockPointerType())
3163 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003164
Steve Naroff3454b6c2008-09-04 15:10:53 +00003165 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
3166 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003167 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003168 }
Chris Lattner1853da22008-01-04 23:18:45 +00003169 return Incompatible;
3170 }
3171
Chris Lattner390564e2008-04-07 06:49:41 +00003172 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003173 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00003174 if (lhsType == Context.BoolTy)
3175 return Compatible;
3176
3177 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003178 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00003179
Mike Stump9afab102009-02-19 03:04:26 +00003180 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003181 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003182
3183 if (isa<BlockPointerType>(lhsType) &&
Steve Naroff3454b6c2008-09-04 15:10:53 +00003184 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003185 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003186 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003187 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003188
Chris Lattner1853da22008-01-04 23:18:45 +00003189 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00003190 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003191 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00003192 }
3193 return Incompatible;
3194}
3195
Douglas Gregor144b06c2009-04-29 22:16:16 +00003196/// \brief Constructs a transparent union from an expression that is
3197/// used to initialize the transparent union.
3198static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3199 QualType UnionType, FieldDecl *Field) {
3200 // Build an initializer list that designates the appropriate member
3201 // of the transparent union.
3202 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3203 &E, 1,
3204 SourceLocation());
3205 Initializer->setType(UnionType);
3206 Initializer->setInitializedFieldInUnion(Field);
3207
3208 // Build a compound literal constructing a value of the transparent
3209 // union type from this initializer list.
3210 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3211 false);
3212}
3213
3214Sema::AssignConvertType
3215Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3216 QualType FromType = rExpr->getType();
3217
3218 // If the ArgType is a Union type, we want to handle a potential
3219 // transparent_union GCC extension.
3220 const RecordType *UT = ArgType->getAsUnionType();
3221 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
3222 return Incompatible;
3223
3224 // The field to initialize within the transparent union.
3225 RecordDecl *UD = UT->getDecl();
3226 FieldDecl *InitField = 0;
3227 // It's compatible if the expression matches any of the fields.
3228 for (RecordDecl::field_iterator it = UD->field_begin(Context),
3229 itend = UD->field_end(Context);
3230 it != itend; ++it) {
3231 if (it->getType()->isPointerType()) {
3232 // If the transparent union contains a pointer type, we allow:
3233 // 1) void pointer
3234 // 2) null pointer constant
3235 if (FromType->isPointerType())
3236 if (FromType->getAsPointerType()->getPointeeType()->isVoidType()) {
3237 ImpCastExprToType(rExpr, it->getType());
3238 InitField = *it;
3239 break;
3240 }
3241
3242 if (rExpr->isNullPointerConstant(Context)) {
3243 ImpCastExprToType(rExpr, it->getType());
3244 InitField = *it;
3245 break;
3246 }
3247 }
3248
3249 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3250 == Compatible) {
3251 InitField = *it;
3252 break;
3253 }
3254 }
3255
3256 if (!InitField)
3257 return Incompatible;
3258
3259 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3260 return Compatible;
3261}
3262
Chris Lattner005ed752008-01-04 18:04:52 +00003263Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003264Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003265 if (getLangOptions().CPlusPlus) {
3266 if (!lhsType->isRecordType()) {
3267 // C++ 5.17p3: If the left operand is not of class type, the
3268 // expression is implicitly converted (C++ 4) to the
3269 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00003270 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3271 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003272 return Incompatible;
Chris Lattner79e9a422009-04-12 09:02:39 +00003273 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003274 }
3275
3276 // FIXME: Currently, we fall through and treat C++ classes like C
3277 // structures.
3278 }
3279
Steve Naroffcdee22d2007-11-27 17:58:44 +00003280 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3281 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00003282 if ((lhsType->isPointerType() ||
3283 lhsType->isObjCQualifiedIdType() ||
Mike Stump9afab102009-02-19 03:04:26 +00003284 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00003285 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003286 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00003287 return Compatible;
3288 }
Mike Stump9afab102009-02-19 03:04:26 +00003289
Chris Lattner5f505bf2007-10-16 02:55:40 +00003290 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00003291 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00003292 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00003293 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00003294 //
Mike Stump9afab102009-02-19 03:04:26 +00003295 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00003296 if (!lhsType->isReferenceType())
3297 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00003298
Chris Lattner005ed752008-01-04 18:04:52 +00003299 Sema::AssignConvertType result =
3300 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00003301
Steve Naroff0f32f432007-08-24 22:33:52 +00003302 // C99 6.5.16.1p2: The value of the right operand is converted to the
3303 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003304 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3305 // so that we can use references in built-in functions even in C.
3306 // The getNonReferenceType() call makes sure that the resulting expression
3307 // does not have reference type.
Douglas Gregor144b06c2009-04-29 22:16:16 +00003308 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003309 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00003310 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00003311}
3312
Chris Lattner005ed752008-01-04 18:04:52 +00003313Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003314Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
3315 return CheckAssignmentConstraints(lhsType, rhsType);
3316}
3317
Chris Lattner1eafdea2008-11-18 01:30:42 +00003318QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003319 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003320 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003321 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00003322 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003323}
3324
Mike Stump9afab102009-02-19 03:04:26 +00003325inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00003326 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00003327 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00003328 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003329 QualType lhsType =
3330 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3331 QualType rhsType =
3332 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00003333
Nate Begemanc5f0f652008-07-14 18:02:46 +00003334 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00003335 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00003336 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00003337
Nate Begemanc5f0f652008-07-14 18:02:46 +00003338 // Handle the case of a vector & extvector type of the same size and element
3339 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00003340 if (getLangOptions().LaxVectorConversions) {
3341 // FIXME: Should we warn here?
3342 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003343 if (const VectorType *RV = rhsType->getAsVectorType())
3344 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00003345 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003346 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00003347 }
3348 }
3349 }
Mike Stump9afab102009-02-19 03:04:26 +00003350
Nate Begemanc5f0f652008-07-14 18:02:46 +00003351 // If the lhs is an extended vector and the rhs is a scalar of the same type
3352 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00003353 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003354 QualType eltType = V->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00003355
3356 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00003357 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
3358 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003359 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00003360 return lhsType;
3361 }
3362 }
3363
Nate Begemanc5f0f652008-07-14 18:02:46 +00003364 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00003365 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00003366 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003367 QualType eltType = V->getElementType();
3368
Mike Stump9afab102009-02-19 03:04:26 +00003369 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00003370 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
3371 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003372 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00003373 return rhsType;
3374 }
3375 }
3376
Chris Lattner4b009652007-07-25 00:24:17 +00003377 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00003378 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003379 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003380 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003381 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00003382}
3383
Chris Lattner4b009652007-07-25 00:24:17 +00003384inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003385 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003386{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00003387 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003388 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003389
Steve Naroff8f708362007-08-24 19:07:16 +00003390 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003391
Chris Lattner4b009652007-07-25 00:24:17 +00003392 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00003393 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003394 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003395}
3396
3397inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003398 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003399{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00003400 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3401 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3402 return CheckVectorOperands(Loc, lex, rex);
3403 return InvalidOperands(Loc, lex, rex);
3404 }
Chris Lattner4b009652007-07-25 00:24:17 +00003405
Steve Naroff8f708362007-08-24 19:07:16 +00003406 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003407
Chris Lattner4b009652007-07-25 00:24:17 +00003408 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003409 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003410 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003411}
3412
3413inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Eli Friedman3cd92882009-03-28 01:22:36 +00003414 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
Chris Lattner4b009652007-07-25 00:24:17 +00003415{
Eli Friedman3cd92882009-03-28 01:22:36 +00003416 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3417 QualType compType = CheckVectorOperands(Loc, lex, rex);
3418 if (CompLHSTy) *CompLHSTy = compType;
3419 return compType;
3420 }
Chris Lattner4b009652007-07-25 00:24:17 +00003421
Eli Friedman3cd92882009-03-28 01:22:36 +00003422 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003423
Chris Lattner4b009652007-07-25 00:24:17 +00003424 // handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00003425 if (lex->getType()->isArithmeticType() &&
3426 rex->getType()->isArithmeticType()) {
3427 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00003428 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00003429 }
Chris Lattner4b009652007-07-25 00:24:17 +00003430
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003431 // Put any potential pointer into PExp
3432 Expr* PExp = lex, *IExp = rex;
3433 if (IExp->getType()->isPointerType())
3434 std::swap(PExp, IExp);
3435
Chris Lattner184f92d2009-04-24 23:50:08 +00003436 if (const PointerType *PTy = PExp->getType()->getAsPointerType()) {
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003437 if (IExp->getType()->isIntegerType()) {
Chris Lattner184f92d2009-04-24 23:50:08 +00003438 QualType PointeeTy = PTy->getPointeeType();
3439 // Check for arithmetic on pointers to incomplete types.
3440 if (PointeeTy->isVoidType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00003441 if (getLangOptions().CPlusPlus) {
3442 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner8ba580c2008-11-19 05:08:23 +00003443 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003444 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003445 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003446
3447 // GNU extension: arithmetic on pointer to void
3448 Diag(Loc, diag::ext_gnu_void_ptr)
3449 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner184f92d2009-04-24 23:50:08 +00003450 } else if (PointeeTy->isFunctionType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00003451 if (getLangOptions().CPlusPlus) {
3452 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3453 << lex->getType() << lex->getSourceRange();
3454 return QualType();
3455 }
3456
3457 // GNU extension: arithmetic on pointer to function
3458 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3459 << lex->getType() << lex->getSourceRange();
3460 } else if (!PTy->isDependentType() &&
Chris Lattner184f92d2009-04-24 23:50:08 +00003461 RequireCompleteType(Loc, PointeeTy,
Douglas Gregor05e28f62009-03-24 19:52:54 +00003462 diag::err_typecheck_arithmetic_incomplete_type,
Chris Lattner184f92d2009-04-24 23:50:08 +00003463 PExp->getSourceRange(), SourceRange(),
3464 PExp->getType()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00003465 return QualType();
3466
Chris Lattner184f92d2009-04-24 23:50:08 +00003467 // Diagnose bad cases where we step over interface counts.
3468 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
3469 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
3470 << PointeeTy << PExp->getSourceRange();
3471 return QualType();
3472 }
3473
Eli Friedman3cd92882009-03-28 01:22:36 +00003474 if (CompLHSTy) {
3475 QualType LHSTy = lex->getType();
3476 if (LHSTy->isPromotableIntegerType())
3477 LHSTy = Context.IntTy;
3478 *CompLHSTy = LHSTy;
3479 }
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003480 return PExp->getType();
3481 }
3482 }
3483
Chris Lattner1eafdea2008-11-18 01:30:42 +00003484 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003485}
3486
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003487// C99 6.5.6
3488QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman3cd92882009-03-28 01:22:36 +00003489 SourceLocation Loc, QualType* CompLHSTy) {
3490 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3491 QualType compType = CheckVectorOperands(Loc, lex, rex);
3492 if (CompLHSTy) *CompLHSTy = compType;
3493 return compType;
3494 }
Mike Stump9afab102009-02-19 03:04:26 +00003495
Eli Friedman3cd92882009-03-28 01:22:36 +00003496 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump9afab102009-02-19 03:04:26 +00003497
Chris Lattnerf6da2912007-12-09 21:53:25 +00003498 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00003499
Chris Lattnerf6da2912007-12-09 21:53:25 +00003500 // Handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00003501 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) {
3502 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00003503 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00003504 }
Mike Stump9afab102009-02-19 03:04:26 +00003505
Chris Lattnerf6da2912007-12-09 21:53:25 +00003506 // Either ptr - int or ptr - ptr.
3507 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00003508 QualType lpointee = LHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003509
Douglas Gregor05e28f62009-03-24 19:52:54 +00003510 // The LHS must be an completely-defined object type.
Douglas Gregorb3193242009-01-23 00:36:41 +00003511
Douglas Gregor05e28f62009-03-24 19:52:54 +00003512 bool ComplainAboutVoid = false;
3513 Expr *ComplainAboutFunc = 0;
3514 if (lpointee->isVoidType()) {
3515 if (getLangOptions().CPlusPlus) {
3516 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3517 << lex->getSourceRange() << rex->getSourceRange();
3518 return QualType();
3519 }
3520
3521 // GNU C extension: arithmetic on pointer to void
3522 ComplainAboutVoid = true;
3523 } else if (lpointee->isFunctionType()) {
3524 if (getLangOptions().CPlusPlus) {
3525 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003526 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003527 return QualType();
3528 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003529
3530 // GNU C extension: arithmetic on pointer to function
3531 ComplainAboutFunc = lex;
3532 } else if (!lpointee->isDependentType() &&
3533 RequireCompleteType(Loc, lpointee,
3534 diag::err_typecheck_sub_ptr_object,
3535 lex->getSourceRange(),
3536 SourceRange(),
3537 lex->getType()))
3538 return QualType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003539
Chris Lattner184f92d2009-04-24 23:50:08 +00003540 // Diagnose bad cases where we step over interface counts.
3541 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
3542 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
3543 << lpointee << lex->getSourceRange();
3544 return QualType();
3545 }
3546
Chris Lattnerf6da2912007-12-09 21:53:25 +00003547 // The result type of a pointer-int computation is the pointer type.
Douglas Gregor05e28f62009-03-24 19:52:54 +00003548 if (rex->getType()->isIntegerType()) {
3549 if (ComplainAboutVoid)
3550 Diag(Loc, diag::ext_gnu_void_ptr)
3551 << lex->getSourceRange() << rex->getSourceRange();
3552 if (ComplainAboutFunc)
3553 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3554 << ComplainAboutFunc->getType()
3555 << ComplainAboutFunc->getSourceRange();
3556
Eli Friedman3cd92882009-03-28 01:22:36 +00003557 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003558 return lex->getType();
Douglas Gregor05e28f62009-03-24 19:52:54 +00003559 }
Mike Stump9afab102009-02-19 03:04:26 +00003560
Chris Lattnerf6da2912007-12-09 21:53:25 +00003561 // Handle pointer-pointer subtractions.
3562 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00003563 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003564
Douglas Gregor05e28f62009-03-24 19:52:54 +00003565 // RHS must be a completely-type object type.
3566 // Handle the GNU void* extension.
3567 if (rpointee->isVoidType()) {
3568 if (getLangOptions().CPlusPlus) {
3569 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3570 << lex->getSourceRange() << rex->getSourceRange();
3571 return QualType();
3572 }
Mike Stump9afab102009-02-19 03:04:26 +00003573
Douglas Gregor05e28f62009-03-24 19:52:54 +00003574 ComplainAboutVoid = true;
3575 } else if (rpointee->isFunctionType()) {
3576 if (getLangOptions().CPlusPlus) {
3577 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003578 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003579 return QualType();
3580 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003581
3582 // GNU extension: arithmetic on pointer to function
3583 if (!ComplainAboutFunc)
3584 ComplainAboutFunc = rex;
3585 } else if (!rpointee->isDependentType() &&
3586 RequireCompleteType(Loc, rpointee,
3587 diag::err_typecheck_sub_ptr_object,
3588 rex->getSourceRange(),
3589 SourceRange(),
3590 rex->getType()))
3591 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00003592
Chris Lattnerf6da2912007-12-09 21:53:25 +00003593 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00003594 if (!Context.typesAreCompatible(
Mike Stump9afab102009-02-19 03:04:26 +00003595 Context.getCanonicalType(lpointee).getUnqualifiedType(),
Eli Friedman583c31e2008-09-02 05:09:35 +00003596 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003597 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003598 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003599 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003600 return QualType();
3601 }
Mike Stump9afab102009-02-19 03:04:26 +00003602
Douglas Gregor05e28f62009-03-24 19:52:54 +00003603 if (ComplainAboutVoid)
3604 Diag(Loc, diag::ext_gnu_void_ptr)
3605 << lex->getSourceRange() << rex->getSourceRange();
3606 if (ComplainAboutFunc)
3607 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3608 << ComplainAboutFunc->getType()
3609 << ComplainAboutFunc->getSourceRange();
Eli Friedman3cd92882009-03-28 01:22:36 +00003610
3611 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003612 return Context.getPointerDiffType();
3613 }
3614 }
Mike Stump9afab102009-02-19 03:04:26 +00003615
Chris Lattner1eafdea2008-11-18 01:30:42 +00003616 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003617}
3618
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003619// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00003620QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003621 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00003622 // C99 6.5.7p2: Each of the operands shall have integer type.
3623 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003624 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003625
Chris Lattner2c8bff72007-12-12 05:47:28 +00003626 // Shifts don't perform usual arithmetic conversions, they just do integer
3627 // promotions on each operand. C99 6.5.7p3
Eli Friedman3cd92882009-03-28 01:22:36 +00003628 QualType LHSTy;
3629 if (lex->getType()->isPromotableIntegerType())
3630 LHSTy = Context.IntTy;
3631 else
3632 LHSTy = lex->getType();
Chris Lattnerbb19bc42007-12-13 07:28:16 +00003633 if (!isCompAssign)
Eli Friedman3cd92882009-03-28 01:22:36 +00003634 ImpCastExprToType(lex, LHSTy);
3635
Chris Lattner2c8bff72007-12-12 05:47:28 +00003636 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003637
Chris Lattner2c8bff72007-12-12 05:47:28 +00003638 // "The type of the result is that of the promoted left operand."
Eli Friedman3cd92882009-03-28 01:22:36 +00003639 return LHSTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003640}
3641
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003642// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00003643QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor1f12c352009-04-06 18:45:53 +00003644 unsigned OpaqueOpc, bool isRelational) {
3645 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
3646
Nate Begemanc5f0f652008-07-14 18:02:46 +00003647 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003648 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00003649
Chris Lattner254f3bc2007-08-26 01:18:55 +00003650 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00003651 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3652 UsualArithmeticConversions(lex, rex);
3653 else {
3654 UsualUnaryConversions(lex);
3655 UsualUnaryConversions(rex);
3656 }
Chris Lattner4b009652007-07-25 00:24:17 +00003657 QualType lType = lex->getType();
3658 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003659
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003660 if (!lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00003661 // For non-floating point types, check for self-comparisons of the form
3662 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3663 // often indicate logic errors in the program.
Ted Kremenek264b5cb2009-03-20 19:57:37 +00003664 // NOTE: Don't warn about comparisons of enum constants. These can arise
3665 // from macro expansions, and are usually quite deliberate.
Chris Lattner4e479f92009-03-08 19:39:53 +00003666 Expr *LHSStripped = lex->IgnoreParens();
3667 Expr *RHSStripped = rex->IgnoreParens();
3668 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
3669 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekf042dc62009-03-20 18:35:45 +00003670 if (DRL->getDecl() == DRR->getDecl() &&
3671 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump9afab102009-02-19 03:04:26 +00003672 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner4e479f92009-03-08 19:39:53 +00003673
3674 if (isa<CastExpr>(LHSStripped))
3675 LHSStripped = LHSStripped->IgnoreParenCasts();
3676 if (isa<CastExpr>(RHSStripped))
3677 RHSStripped = RHSStripped->IgnoreParenCasts();
3678
3679 // Warn about comparisons against a string constant (unless the other
3680 // operand is null), the user probably wants strcmp.
Douglas Gregor1f12c352009-04-06 18:45:53 +00003681 Expr *literalString = 0;
3682 Expr *literalStringStripped = 0;
Chris Lattner4e479f92009-03-08 19:39:53 +00003683 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00003684 !RHSStripped->isNullPointerConstant(Context)) {
3685 literalString = lex;
3686 literalStringStripped = LHSStripped;
3687 }
Chris Lattner4e479f92009-03-08 19:39:53 +00003688 else if ((isa<StringLiteral>(RHSStripped) ||
3689 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00003690 !LHSStripped->isNullPointerConstant(Context)) {
3691 literalString = rex;
3692 literalStringStripped = RHSStripped;
3693 }
3694
3695 if (literalString) {
3696 std::string resultComparison;
3697 switch (Opc) {
3698 case BinaryOperator::LT: resultComparison = ") < 0"; break;
3699 case BinaryOperator::GT: resultComparison = ") > 0"; break;
3700 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
3701 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
3702 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
3703 case BinaryOperator::NE: resultComparison = ") != 0"; break;
3704 default: assert(false && "Invalid comparison operator");
3705 }
3706 Diag(Loc, diag::warn_stringcompare)
3707 << isa<ObjCEncodeExpr>(literalStringStripped)
3708 << literalString->getSourceRange()
Douglas Gregor3faaa812009-04-01 23:51:29 +00003709 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
3710 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
3711 "strcmp(")
3712 << CodeModificationHint::CreateInsertion(
3713 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor1f12c352009-04-06 18:45:53 +00003714 resultComparison);
3715 }
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003716 }
Mike Stump9afab102009-02-19 03:04:26 +00003717
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003718 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner4e479f92009-03-08 19:39:53 +00003719 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003720
Chris Lattner254f3bc2007-08-26 01:18:55 +00003721 if (isRelational) {
3722 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003723 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003724 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00003725 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00003726 if (lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00003727 assert(rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003728 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00003729 }
Mike Stump9afab102009-02-19 03:04:26 +00003730
Chris Lattner254f3bc2007-08-26 01:18:55 +00003731 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003732 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003733 }
Mike Stump9afab102009-02-19 03:04:26 +00003734
Chris Lattner22be8422007-08-26 01:10:14 +00003735 bool LHSIsNull = lex->isNullPointerConstant(Context);
3736 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00003737
Chris Lattner254f3bc2007-08-26 01:18:55 +00003738 // All of the following pointer related warnings are GCC extensions, except
3739 // when handling null pointer constants. One day, we can consider making them
3740 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00003741 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003742 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003743 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00003744 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003745 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00003746
Steve Naroff3b435622007-11-13 14:57:38 +00003747 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003748 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3749 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00003750 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00003751 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003752 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003753 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003754 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003755 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003756 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003757 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003758 // Handle block pointer types.
3759 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3760 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3761 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003762
Steve Naroff3454b6c2008-09-04 15:10:53 +00003763 if (!LHSIsNull && !RHSIsNull &&
3764 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003765 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003766 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003767 }
3768 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003769 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003770 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003771 // Allow block pointers to be compared with null pointer constants.
3772 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3773 (lType->isPointerType() && rType->isBlockPointerType())) {
3774 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003775 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003776 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003777 }
3778 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003779 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003780 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003781
Steve Naroff936c4362008-06-03 14:04:54 +00003782 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003783 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003784 const PointerType *LPT = lType->getAsPointerType();
3785 const PointerType *RPT = rType->getAsPointerType();
Mike Stump9afab102009-02-19 03:04:26 +00003786 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003787 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003788 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003789 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003790
Steve Naroff030fcda2008-11-17 19:49:16 +00003791 if (!LPtrToVoid && !RPtrToVoid &&
3792 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003793 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003794 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003795 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003796 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003797 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003798 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003799 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003800 }
Steve Naroff936c4362008-06-03 14:04:54 +00003801 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3802 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003803 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003804 } else {
3805 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003806 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003807 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003808 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003809 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003810 }
Steve Naroff936c4362008-06-03 14:04:54 +00003811 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003812 }
Mike Stump9afab102009-02-19 03:04:26 +00003813 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
Steve Naroff936c4362008-06-03 14:04:54 +00003814 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003815 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003816 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003817 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003818 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003819 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003820 }
Mike Stump9afab102009-02-19 03:04:26 +00003821 if (lType->isIntegerType() &&
Steve Naroff936c4362008-06-03 14:04:54 +00003822 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003823 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003824 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003825 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003826 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003827 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003828 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003829 // Handle block pointers.
3830 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3831 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003832 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003833 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003834 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003835 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003836 }
3837 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3838 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003839 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003840 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003841 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003842 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003843 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003844 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003845}
3846
Nate Begemanc5f0f652008-07-14 18:02:46 +00003847/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00003848/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003849/// like a scalar comparison, a vector comparison produces a vector of integer
3850/// types.
3851QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003852 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003853 bool isRelational) {
3854 // Check to make sure we're operating on vectors of the same type and width,
3855 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003856 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003857 if (vType.isNull())
3858 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00003859
Nate Begemanc5f0f652008-07-14 18:02:46 +00003860 QualType lType = lex->getType();
3861 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003862
Nate Begemanc5f0f652008-07-14 18:02:46 +00003863 // For non-floating point types, check for self-comparisons of the form
3864 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3865 // often indicate logic errors in the program.
3866 if (!lType->isFloatingType()) {
3867 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3868 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3869 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003870 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003871 }
Mike Stump9afab102009-02-19 03:04:26 +00003872
Nate Begemanc5f0f652008-07-14 18:02:46 +00003873 // Check for comparisons of floating point operands using != and ==.
3874 if (!isRelational && lType->isFloatingType()) {
3875 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003876 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003877 }
Mike Stump9afab102009-02-19 03:04:26 +00003878
Chris Lattner10687e32009-03-31 07:46:52 +00003879 // FIXME: Vector compare support in the LLVM backend is not fully reliable,
3880 // just reject all vector comparisons for now.
3881 if (1) {
3882 Diag(Loc, diag::err_typecheck_vector_comparison)
3883 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3884 return QualType();
3885 }
3886
Nate Begemanc5f0f652008-07-14 18:02:46 +00003887 // Return the type for the comparison, which is the same as vector type for
3888 // integer vectors, or an integer type of identical size and number of
3889 // elements for floating point vectors.
3890 if (lType->isIntegerType())
3891 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00003892
Nate Begemanc5f0f652008-07-14 18:02:46 +00003893 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003894 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003895 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003896 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner10687e32009-03-31 07:46:52 +00003897 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begemand6d2f772009-01-18 03:20:47 +00003898 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3899
Mike Stump9afab102009-02-19 03:04:26 +00003900 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00003901 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003902 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3903}
3904
Chris Lattner4b009652007-07-25 00:24:17 +00003905inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003906 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003907{
3908 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003909 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003910
Steve Naroff8f708362007-08-24 19:07:16 +00003911 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003912
Chris Lattner4b009652007-07-25 00:24:17 +00003913 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003914 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003915 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003916}
3917
3918inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00003919 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003920{
3921 UsualUnaryConversions(lex);
3922 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003923
Eli Friedmanbea3f842008-05-13 20:16:47 +00003924 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003925 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003926 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003927}
3928
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003929/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3930/// is a read-only property; return true if so. A readonly property expression
3931/// depends on various declarations and thus must be treated specially.
3932///
Mike Stump9afab102009-02-19 03:04:26 +00003933static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003934{
3935 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3936 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3937 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3938 QualType BaseType = PropExpr->getBase()->getType();
3939 if (const PointerType *PTy = BaseType->getAsPointerType())
Mike Stump9afab102009-02-19 03:04:26 +00003940 if (const ObjCInterfaceType *IFTy =
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003941 PTy->getPointeeType()->getAsObjCInterfaceType())
3942 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3943 if (S.isPropertyReadonly(PDecl, IFace))
3944 return true;
3945 }
3946 }
3947 return false;
3948}
3949
Chris Lattner4c2642c2008-11-18 01:22:49 +00003950/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3951/// emit an error and return true. If so, return false.
3952static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00003953 SourceLocation OrigLoc = Loc;
3954 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
3955 &Loc);
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003956 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3957 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003958 if (IsLV == Expr::MLV_Valid)
3959 return false;
Mike Stump9afab102009-02-19 03:04:26 +00003960
Chris Lattner4c2642c2008-11-18 01:22:49 +00003961 unsigned Diag = 0;
3962 bool NeedType = false;
3963 switch (IsLV) { // C99 6.5.16p2
3964 default: assert(0 && "Unknown result from isModifiableLvalue!");
3965 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00003966 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003967 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3968 NeedType = true;
3969 break;
Mike Stump9afab102009-02-19 03:04:26 +00003970 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003971 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3972 NeedType = true;
3973 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003974 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003975 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3976 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003977 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003978 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3979 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003980 case Expr::MLV_IncompleteType:
3981 case Expr::MLV_IncompleteVoidType:
Douglas Gregorc84d8932009-03-09 16:13:40 +00003982 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003983 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3984 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003985 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003986 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3987 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003988 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003989 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3990 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003991 case Expr::MLV_ReadonlyProperty:
3992 Diag = diag::error_readonly_property_assignment;
3993 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003994 case Expr::MLV_NoSetterProperty:
3995 Diag = diag::error_nosetter_property_assignment;
3996 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003997 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003998
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00003999 SourceRange Assign;
4000 if (Loc != OrigLoc)
4001 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner4c2642c2008-11-18 01:22:49 +00004002 if (NeedType)
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004003 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004004 else
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004005 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004006 return true;
4007}
4008
4009
4010
4011// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00004012QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4013 SourceLocation Loc,
4014 QualType CompoundType) {
4015 // Verify that LHS is a modifiable lvalue, and emit error if not.
4016 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00004017 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00004018
4019 QualType LHSType = LHS->getType();
4020 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00004021
Chris Lattner005ed752008-01-04 18:04:52 +00004022 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004023 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00004024 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004025 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004026 // Special case of NSObject attributes on c-style pointer types.
4027 if (ConvTy == IncompatiblePointer &&
4028 ((Context.isObjCNSObjectType(LHSType) &&
4029 Context.isObjCObjectPointerType(RHSType)) ||
4030 (Context.isObjCNSObjectType(RHSType) &&
4031 Context.isObjCObjectPointerType(LHSType))))
4032 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00004033
Chris Lattner34c85082008-08-21 18:04:13 +00004034 // If the RHS is a unary plus or minus, check to see if they = and + are
4035 // right next to each other. If so, the user may have typo'd "x =+ 4"
4036 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004037 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00004038 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4039 RHSCheck = ICE->getSubExpr();
4040 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4041 if ((UO->getOpcode() == UnaryOperator::Plus ||
4042 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00004043 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00004044 // Only if the two operators are exactly adjacent.
Chris Lattner55a17242009-03-08 06:51:10 +00004045 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4046 // And there is a space or other character before the subexpr of the
4047 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnerf1e5d4a2009-03-09 07:11:10 +00004048 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4049 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004050 Diag(Loc, diag::warn_not_compound_assign)
4051 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4052 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner55a17242009-03-08 06:51:10 +00004053 }
Chris Lattner34c85082008-08-21 18:04:13 +00004054 }
4055 } else {
4056 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00004057 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00004058 }
Chris Lattner005ed752008-01-04 18:04:52 +00004059
Chris Lattner1eafdea2008-11-18 01:30:42 +00004060 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4061 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00004062 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004063
Chris Lattner4b009652007-07-25 00:24:17 +00004064 // C99 6.5.16p3: The type of an assignment expression is the type of the
4065 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00004066 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00004067 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4068 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004069 // C++ 5.17p1: the type of the assignment expression is that of its left
4070 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004071 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00004072}
4073
Chris Lattner1eafdea2008-11-18 01:30:42 +00004074// C99 6.5.17
4075QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00004076 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004077 DefaultFunctionArrayConversion(RHS);
Eli Friedman2b128322009-03-23 00:24:07 +00004078
4079 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4080 // incomplete in C++).
4081
Chris Lattner1eafdea2008-11-18 01:30:42 +00004082 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00004083}
4084
4085/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4086/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004087QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4088 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004089 if (Op->isTypeDependent())
4090 return Context.DependentTy;
4091
Chris Lattnere65182c2008-11-21 07:05:48 +00004092 QualType ResType = Op->getType();
4093 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004094
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004095 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4096 // Decrement of bool is not allowed.
4097 if (!isInc) {
4098 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4099 return QualType();
4100 }
4101 // Increment of bool sets it to true, but is deprecated.
4102 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4103 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00004104 // OK!
4105 } else if (const PointerType *PT = ResType->getAsPointerType()) {
4106 // C99 6.5.2.4p2, 6.5.6p2
Douglas Gregorcde3a2d2009-03-24 20:13:58 +00004107 if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004108 if (getLangOptions().CPlusPlus) {
4109 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4110 << Op->getSourceRange();
4111 return QualType();
4112 }
4113
4114 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00004115 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004116 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004117 if (getLangOptions().CPlusPlus) {
4118 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4119 << Op->getType() << Op->getSourceRange();
4120 return QualType();
4121 }
4122
4123 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004124 << ResType << Op->getSourceRange();
Douglas Gregorcde3a2d2009-03-24 20:13:58 +00004125 } else if (RequireCompleteType(OpLoc, PT->getPointeeType(),
4126 diag::err_typecheck_arithmetic_incomplete_type,
4127 Op->getSourceRange(), SourceRange(),
4128 ResType))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004129 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00004130 } else if (ResType->isComplexType()) {
4131 // C99 does not support ++/-- on complex types, we allow as an extension.
4132 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004133 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004134 } else {
4135 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004136 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004137 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00004138 }
Mike Stump9afab102009-02-19 03:04:26 +00004139 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00004140 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00004141 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00004142 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00004143 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00004144}
4145
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004146/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00004147/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004148/// where the declaration is needed for type checking. We only need to
4149/// handle cases when the expression references a function designator
4150/// or is an lvalue. Here are some examples:
4151/// - &(x) => x
4152/// - &*****f => f for f a function designator.
4153/// - &s.xx => s
4154/// - &s.zz[1].yy -> s, if zz is an array
4155/// - *(x + 1) -> x, if x is an array
4156/// - &"123"[2] -> 0
4157/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00004158static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00004159 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00004160 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00004161 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004162 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00004163 case Stmt::MemberExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004164 // If this is an arrow operator, the address is an offset from
4165 // the base's value, so the object the base refers to is
4166 // irrelevant.
Chris Lattner48d7f382008-04-02 04:24:33 +00004167 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00004168 return 0;
Eli Friedman93ecce22009-04-20 08:23:18 +00004169 // Otherwise, the expression refers to a part of the base
Chris Lattner48d7f382008-04-02 04:24:33 +00004170 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004171 case Stmt::ArraySubscriptExprClass: {
Eli Friedman93ecce22009-04-20 08:23:18 +00004172 // FIXME: This code shouldn't be necessary! We should catch the
4173 // implicit promotion of register arrays earlier.
4174 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4175 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4176 if (ICE->getSubExpr()->getType()->isArrayType())
4177 return getPrimaryDecl(ICE->getSubExpr());
4178 }
4179 return 0;
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004180 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004181 case Stmt::UnaryOperatorClass: {
4182 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00004183
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004184 switch(UO->getOpcode()) {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004185 case UnaryOperator::Real:
4186 case UnaryOperator::Imag:
4187 case UnaryOperator::Extension:
4188 return getPrimaryDecl(UO->getSubExpr());
4189 default:
4190 return 0;
4191 }
4192 }
Chris Lattner4b009652007-07-25 00:24:17 +00004193 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004194 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00004195 case Stmt::ImplicitCastExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004196 // If the result of an implicit cast is an l-value, we care about
4197 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner48d7f382008-04-02 04:24:33 +00004198 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00004199 default:
4200 return 0;
4201 }
4202}
4203
4204/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00004205/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00004206/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00004207/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00004208/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00004209/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00004210/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00004211QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman93ecce22009-04-20 08:23:18 +00004212 // Make sure to ignore parentheses in subsequent checks
4213 op = op->IgnoreParens();
4214
Douglas Gregore6be68a2008-12-17 22:52:20 +00004215 if (op->isTypeDependent())
4216 return Context.DependentTy;
4217
Steve Naroff9c6c3592008-01-13 17:10:08 +00004218 if (getLangOptions().C99) {
4219 // Implement C99-only parts of addressof rules.
4220 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
4221 if (uOp->getOpcode() == UnaryOperator::Deref)
4222 // Per C99 6.5.3.2, the address of a deref always returns a valid result
4223 // (assuming the deref expression is valid).
4224 return uOp->getSubExpr()->getType();
4225 }
4226 // Technically, there should be a check for array subscript
4227 // expressions here, but the result of one is always an lvalue anyway.
4228 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00004229 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00004230 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00004231
Chris Lattner4b009652007-07-25 00:24:17 +00004232 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004233 // The operand must be either an l-value or a function designator
Eli Friedmane730abe2009-04-28 17:59:09 +00004234 if (!op->getType()->isFunctionType()) {
Chris Lattnera3249072007-11-16 17:46:48 +00004235 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00004236 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
4237 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004238 return QualType();
4239 }
Eli Friedman93ecce22009-04-20 08:23:18 +00004240 } else if (op->isBitField()) { // C99 6.5.3.2p1
4241 // The operand cannot be a bit-field
4242 Diag(OpLoc, diag::err_typecheck_address_of)
4243 << "bit-field" << op->getSourceRange();
Douglas Gregor82d44772008-12-20 23:49:58 +00004244 return QualType();
Nate Begemana9187ab2009-02-15 22:45:20 +00004245 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
4246 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman93ecce22009-04-20 08:23:18 +00004247 // The operand cannot be an element of a vector
Chris Lattner77d52da2008-11-20 06:06:08 +00004248 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00004249 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004250 return QualType();
4251 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00004252 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00004253 // with the register storage-class specifier.
4254 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
4255 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004256 Diag(OpLoc, diag::err_typecheck_address_of)
4257 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004258 return QualType();
4259 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00004260 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00004261 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00004262 } else if (isa<FieldDecl>(dcl)) {
4263 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00004264 // Could be a pointer to member, though, if there is an explicit
4265 // scope qualifier for the class.
4266 if (isa<QualifiedDeclRefExpr>(op)) {
4267 DeclContext *Ctx = dcl->getDeclContext();
4268 if (Ctx && Ctx->isRecord())
4269 return Context.getMemberPointerType(op->getType(),
4270 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
4271 }
Nuno Lopesdf239522008-12-16 22:58:26 +00004272 } else if (isa<FunctionDecl>(dcl)) {
4273 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00004274 // As above.
4275 if (isa<QualifiedDeclRefExpr>(op)) {
4276 DeclContext *Ctx = dcl->getDeclContext();
4277 if (Ctx && Ctx->isRecord())
4278 return Context.getMemberPointerType(op->getType(),
4279 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
4280 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00004281 }
Nuno Lopesdf239522008-12-16 22:58:26 +00004282 else
Chris Lattner4b009652007-07-25 00:24:17 +00004283 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00004284 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00004285
Chris Lattner4b009652007-07-25 00:24:17 +00004286 // If the operand has type "type", the result has type "pointer to type".
4287 return Context.getPointerType(op->getType());
4288}
4289
Chris Lattnerda5c0872008-11-23 09:13:29 +00004290QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004291 if (Op->isTypeDependent())
4292 return Context.DependentTy;
4293
Chris Lattnerda5c0872008-11-23 09:13:29 +00004294 UsualUnaryConversions(Op);
4295 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004296
Chris Lattnerda5c0872008-11-23 09:13:29 +00004297 // Note that per both C89 and C99, this is always legal, even if ptype is an
4298 // incomplete type or void. It would be possible to warn about dereferencing
4299 // a void pointer, but it's completely well-defined, and such a warning is
4300 // unlikely to catch any mistakes.
4301 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00004302 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004303
Chris Lattner77d52da2008-11-20 06:06:08 +00004304 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00004305 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004306 return QualType();
4307}
4308
4309static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
4310 tok::TokenKind Kind) {
4311 BinaryOperator::Opcode Opc;
4312 switch (Kind) {
4313 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00004314 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
4315 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00004316 case tok::star: Opc = BinaryOperator::Mul; break;
4317 case tok::slash: Opc = BinaryOperator::Div; break;
4318 case tok::percent: Opc = BinaryOperator::Rem; break;
4319 case tok::plus: Opc = BinaryOperator::Add; break;
4320 case tok::minus: Opc = BinaryOperator::Sub; break;
4321 case tok::lessless: Opc = BinaryOperator::Shl; break;
4322 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
4323 case tok::lessequal: Opc = BinaryOperator::LE; break;
4324 case tok::less: Opc = BinaryOperator::LT; break;
4325 case tok::greaterequal: Opc = BinaryOperator::GE; break;
4326 case tok::greater: Opc = BinaryOperator::GT; break;
4327 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
4328 case tok::equalequal: Opc = BinaryOperator::EQ; break;
4329 case tok::amp: Opc = BinaryOperator::And; break;
4330 case tok::caret: Opc = BinaryOperator::Xor; break;
4331 case tok::pipe: Opc = BinaryOperator::Or; break;
4332 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
4333 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
4334 case tok::equal: Opc = BinaryOperator::Assign; break;
4335 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
4336 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
4337 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
4338 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
4339 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
4340 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
4341 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
4342 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
4343 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
4344 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
4345 case tok::comma: Opc = BinaryOperator::Comma; break;
4346 }
4347 return Opc;
4348}
4349
4350static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
4351 tok::TokenKind Kind) {
4352 UnaryOperator::Opcode Opc;
4353 switch (Kind) {
4354 default: assert(0 && "Unknown unary op!");
4355 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
4356 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
4357 case tok::amp: Opc = UnaryOperator::AddrOf; break;
4358 case tok::star: Opc = UnaryOperator::Deref; break;
4359 case tok::plus: Opc = UnaryOperator::Plus; break;
4360 case tok::minus: Opc = UnaryOperator::Minus; break;
4361 case tok::tilde: Opc = UnaryOperator::Not; break;
4362 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00004363 case tok::kw___real: Opc = UnaryOperator::Real; break;
4364 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
4365 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
4366 }
4367 return Opc;
4368}
4369
Douglas Gregord7f915e2008-11-06 23:29:22 +00004370/// CreateBuiltinBinOp - Creates a new built-in binary operation with
4371/// operator @p Opc at location @c TokLoc. This routine only supports
4372/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004373Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
4374 unsigned Op,
4375 Expr *lhs, Expr *rhs) {
Eli Friedman3cd92882009-03-28 01:22:36 +00004376 QualType ResultTy; // Result type of the binary operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00004377 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman3cd92882009-03-28 01:22:36 +00004378 // The following two variables are used for compound assignment operators
4379 QualType CompLHSTy; // Type of LHS after promotions for computation
4380 QualType CompResultTy; // Type of computation result
Douglas Gregord7f915e2008-11-06 23:29:22 +00004381
4382 switch (Opc) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00004383 case BinaryOperator::Assign:
4384 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
4385 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00004386 case BinaryOperator::PtrMemD:
4387 case BinaryOperator::PtrMemI:
4388 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
4389 Opc == BinaryOperator::PtrMemI);
4390 break;
4391 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00004392 case BinaryOperator::Div:
4393 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
4394 break;
4395 case BinaryOperator::Rem:
4396 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
4397 break;
4398 case BinaryOperator::Add:
4399 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
4400 break;
4401 case BinaryOperator::Sub:
4402 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
4403 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00004404 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00004405 case BinaryOperator::Shr:
4406 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
4407 break;
4408 case BinaryOperator::LE:
4409 case BinaryOperator::LT:
4410 case BinaryOperator::GE:
4411 case BinaryOperator::GT:
Douglas Gregor1f12c352009-04-06 18:45:53 +00004412 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004413 break;
4414 case BinaryOperator::EQ:
4415 case BinaryOperator::NE:
Douglas Gregor1f12c352009-04-06 18:45:53 +00004416 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004417 break;
4418 case BinaryOperator::And:
4419 case BinaryOperator::Xor:
4420 case BinaryOperator::Or:
4421 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
4422 break;
4423 case BinaryOperator::LAnd:
4424 case BinaryOperator::LOr:
4425 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
4426 break;
4427 case BinaryOperator::MulAssign:
4428 case BinaryOperator::DivAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004429 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
4430 CompLHSTy = CompResultTy;
4431 if (!CompResultTy.isNull())
4432 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004433 break;
4434 case BinaryOperator::RemAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004435 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
4436 CompLHSTy = CompResultTy;
4437 if (!CompResultTy.isNull())
4438 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004439 break;
4440 case BinaryOperator::AddAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004441 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
4442 if (!CompResultTy.isNull())
4443 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004444 break;
4445 case BinaryOperator::SubAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004446 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
4447 if (!CompResultTy.isNull())
4448 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004449 break;
4450 case BinaryOperator::ShlAssign:
4451 case BinaryOperator::ShrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004452 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
4453 CompLHSTy = CompResultTy;
4454 if (!CompResultTy.isNull())
4455 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004456 break;
4457 case BinaryOperator::AndAssign:
4458 case BinaryOperator::XorAssign:
4459 case BinaryOperator::OrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004460 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
4461 CompLHSTy = CompResultTy;
4462 if (!CompResultTy.isNull())
4463 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004464 break;
4465 case BinaryOperator::Comma:
4466 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
4467 break;
4468 }
4469 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004470 return ExprError();
Eli Friedman3cd92882009-03-28 01:22:36 +00004471 if (CompResultTy.isNull())
Steve Naroff774e4152009-01-21 00:14:39 +00004472 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
4473 else
4474 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman3cd92882009-03-28 01:22:36 +00004475 CompLHSTy, CompResultTy,
4476 OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00004477}
4478
Chris Lattner4b009652007-07-25 00:24:17 +00004479// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004480Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
4481 tok::TokenKind Kind,
4482 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00004483 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00004484 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Chris Lattner4b009652007-07-25 00:24:17 +00004485
Steve Naroff87d58b42007-09-16 03:34:24 +00004486 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
4487 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004488
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004489 if (getLangOptions().CPlusPlus &&
4490 (lhs->getType()->isOverloadableType() ||
4491 rhs->getType()->isOverloadableType())) {
4492 // Find all of the overloaded operators visible from this
4493 // point. We perform both an operator-name lookup from the local
4494 // scope and an argument-dependent lookup based on the types of
4495 // the arguments.
Douglas Gregor3fc092f2009-03-13 00:33:25 +00004496 FunctionSet Functions;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004497 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
4498 if (OverOp != OO_None) {
4499 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
4500 Functions);
4501 Expr *Args[2] = { lhs, rhs };
4502 DeclarationName OpName
4503 = Context.DeclarationNames.getCXXOperatorName(OverOp);
4504 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregor70d26122008-11-12 17:17:38 +00004505 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004506
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004507 // Build the (potentially-overloaded, potentially-dependent)
4508 // binary operation.
4509 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004510 }
4511
Douglas Gregord7f915e2008-11-06 23:29:22 +00004512 // Build a built-in binary operation.
4513 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00004514}
4515
Douglas Gregorc78182d2009-03-13 23:49:33 +00004516Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
4517 unsigned OpcIn,
4518 ExprArg InputArg) {
4519 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004520
Douglas Gregorc78182d2009-03-13 23:49:33 +00004521 // FIXME: Input is modified below, but InputArg is not updated
4522 // appropriately.
4523 Expr *Input = (Expr *)InputArg.get();
Chris Lattner4b009652007-07-25 00:24:17 +00004524 QualType resultType;
4525 switch (Opc) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00004526 case UnaryOperator::PostInc:
4527 case UnaryOperator::PostDec:
4528 case UnaryOperator::OffsetOf:
4529 assert(false && "Invalid unary operator");
4530 break;
4531
Chris Lattner4b009652007-07-25 00:24:17 +00004532 case UnaryOperator::PreInc:
4533 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004534 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4535 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00004536 break;
Mike Stump9afab102009-02-19 03:04:26 +00004537 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00004538 resultType = CheckAddressOfOperand(Input, OpLoc);
4539 break;
Mike Stump9afab102009-02-19 03:04:26 +00004540 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00004541 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00004542 resultType = CheckIndirectionOperand(Input, OpLoc);
4543 break;
4544 case UnaryOperator::Plus:
4545 case UnaryOperator::Minus:
4546 UsualUnaryConversions(Input);
4547 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004548 if (resultType->isDependentType())
4549 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004550 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4551 break;
4552 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4553 resultType->isEnumeralType())
4554 break;
4555 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4556 Opc == UnaryOperator::Plus &&
4557 resultType->isPointerType())
4558 break;
4559
Sebastian Redl8b769972009-01-19 00:08:26 +00004560 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4561 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004562 case UnaryOperator::Not: // bitwise complement
4563 UsualUnaryConversions(Input);
4564 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004565 if (resultType->isDependentType())
4566 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00004567 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4568 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4569 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00004570 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004571 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004572 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00004573 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4574 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004575 break;
4576 case UnaryOperator::LNot: // logical negation
4577 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4578 DefaultFunctionArrayConversion(Input);
4579 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004580 if (resultType->isDependentType())
4581 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004582 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004583 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4584 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004585 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004586 // In C++, it's bool. C++ 5.3.1p8
4587 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004588 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004589 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004590 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00004591 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00004592 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004593 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004594 resultType = Input->getType();
4595 break;
4596 }
4597 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004598 return ExprError();
Douglas Gregorc78182d2009-03-13 23:49:33 +00004599
4600 InputArg.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004601 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004602}
4603
Douglas Gregorc78182d2009-03-13 23:49:33 +00004604// Unary Operators. 'Tok' is the token for the operator.
4605Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4606 tok::TokenKind Op, ExprArg input) {
4607 Expr *Input = (Expr*)input.get();
4608 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
4609
4610 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
4611 // Find all of the overloaded operators visible from this
4612 // point. We perform both an operator-name lookup from the local
4613 // scope and an argument-dependent lookup based on the types of
4614 // the arguments.
4615 FunctionSet Functions;
4616 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
4617 if (OverOp != OO_None) {
4618 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
4619 Functions);
4620 DeclarationName OpName
4621 = Context.DeclarationNames.getCXXOperatorName(OverOp);
4622 ArgumentDependentLookup(OpName, &Input, 1, Functions);
4623 }
4624
4625 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
4626 }
4627
4628 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
4629}
4630
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004631/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004632Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
4633 SourceLocation LabLoc,
4634 IdentifierInfo *LabelII) {
Chris Lattner4b009652007-07-25 00:24:17 +00004635 // Look up the record for this label identifier.
Chris Lattner2616d8c2009-04-18 20:01:55 +00004636 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00004637
Daniel Dunbar879788d2008-08-04 16:51:22 +00004638 // If we haven't seen this label yet, create a forward reference. It
4639 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffb88d81c2009-03-13 15:38:40 +00004640 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004641 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004642
Chris Lattner4b009652007-07-25 00:24:17 +00004643 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004644 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4645 Context.getPointerType(Context.VoidTy)));
Chris Lattner4b009652007-07-25 00:24:17 +00004646}
4647
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004648Sema::OwningExprResult
4649Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
4650 SourceLocation RPLoc) { // "({..})"
4651 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner4b009652007-07-25 00:24:17 +00004652 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4653 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4654
Eli Friedmanbc941e12009-01-24 23:09:00 +00004655 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattneraa257592009-04-25 19:11:05 +00004656 if (isFileScope)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004657 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmanbc941e12009-01-24 23:09:00 +00004658
Chris Lattner4b009652007-07-25 00:24:17 +00004659 // FIXME: there are a variety of strange constraints to enforce here, for
4660 // example, it is not possible to goto into a stmt expression apparently.
4661 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00004662
Chris Lattner4b009652007-07-25 00:24:17 +00004663 // If there are sub stmts in the compound stmt, take the type of the last one
4664 // as the type of the stmtexpr.
4665 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00004666
Chris Lattner200964f2008-07-26 19:51:01 +00004667 if (!Compound->body_empty()) {
4668 Stmt *LastStmt = Compound->body_back();
4669 // If LastStmt is a label, skip down through into the body.
4670 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4671 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00004672
Chris Lattner200964f2008-07-26 19:51:01 +00004673 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004674 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004675 }
Mike Stump9afab102009-02-19 03:04:26 +00004676
Eli Friedman2b128322009-03-23 00:24:07 +00004677 // FIXME: Check that expression type is complete/non-abstract; statement
4678 // expressions are not lvalues.
4679
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004680 substmt.release();
4681 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004682}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004683
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004684Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4685 SourceLocation BuiltinLoc,
4686 SourceLocation TypeLoc,
4687 TypeTy *argty,
4688 OffsetOfComponent *CompPtr,
4689 unsigned NumComponents,
4690 SourceLocation RPLoc) {
4691 // FIXME: This function leaks all expressions in the offset components on
4692 // error.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004693 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4694 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00004695
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004696 bool Dependent = ArgTy->isDependentType();
4697
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004698 // We must have at least one component that refers to the type, and the first
4699 // one is known to be a field designator. Verify that the ArgTy represents
4700 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004701 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004702 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump9afab102009-02-19 03:04:26 +00004703
Eli Friedman2b128322009-03-23 00:24:07 +00004704 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
4705 // with an incomplete type would be illegal.
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00004706
Eli Friedman342d9432009-02-27 06:44:11 +00004707 // Otherwise, create a null pointer as the base, and iteratively process
4708 // the offsetof designators.
4709 QualType ArgTyPtr = Context.getPointerType(ArgTy);
4710 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004711 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman342d9432009-02-27 06:44:11 +00004712 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004713
Chris Lattnerb37522e2007-08-31 21:49:13 +00004714 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4715 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00004716 // FIXME: This diagnostic isn't actually visible because the location is in
4717 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00004718 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004719 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4720 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00004721
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004722 if (!Dependent) {
4723 // FIXME: Dependent case loses a lot of information here. And probably
4724 // leaks like a sieve.
4725 for (unsigned i = 0; i != NumComponents; ++i) {
4726 const OffsetOfComponent &OC = CompPtr[i];
4727 if (OC.isBrackets) {
4728 // Offset of an array sub-field. TODO: Should we allow vector elements?
4729 const ArrayType *AT = Context.getAsArrayType(Res->getType());
4730 if (!AT) {
4731 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004732 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
4733 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004734 }
4735
4736 // FIXME: C++: Verify that operator[] isn't overloaded.
4737
Eli Friedman342d9432009-02-27 06:44:11 +00004738 // Promote the array so it looks more like a normal array subscript
4739 // expression.
4740 DefaultFunctionArrayConversion(Res);
4741
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004742 // C99 6.5.2.1p1
4743 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004744 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004745 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004746 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner7264d212009-04-25 22:50:55 +00004747 diag::err_typecheck_subscript_not_integer)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004748 << Idx->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004749
4750 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4751 OC.LocEnd);
4752 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004753 }
Mike Stump9afab102009-02-19 03:04:26 +00004754
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004755 const RecordType *RC = Res->getType()->getAsRecordType();
4756 if (!RC) {
4757 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004758 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
4759 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004760 }
Chris Lattner2af6a802007-08-30 17:59:59 +00004761
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004762 // Get the decl corresponding to this.
4763 RecordDecl *RD = RC->getDecl();
Anders Carlsson356946e2009-05-01 23:20:30 +00004764 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
4765 if (!CRD->isPOD())
4766 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_non_pod_type)
4767 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
4768 << Res->getType());
4769 }
4770
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004771 FieldDecl *MemberDecl
4772 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4773 LookupMemberName)
4774 .getAsDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004775 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004776 if (!MemberDecl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004777 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
4778 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump9afab102009-02-19 03:04:26 +00004779
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004780 // FIXME: C++: Verify that MemberDecl isn't a static field.
4781 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman35719da2009-04-26 20:50:44 +00004782 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonc154a722009-05-01 19:30:39 +00004783 Res = BuildAnonymousStructUnionMemberReference(
4784 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedman35719da2009-04-26 20:50:44 +00004785 } else {
4786 // MemberDecl->getType() doesn't get the right qualifiers, but it
4787 // doesn't matter here.
4788 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4789 MemberDecl->getType().getNonReferenceType());
4790 }
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004791 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004792 }
Mike Stump9afab102009-02-19 03:04:26 +00004793
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004794 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4795 Context.getSizeType(), BuiltinLoc));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004796}
4797
4798
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004799Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
4800 TypeTy *arg1,TypeTy *arg2,
4801 SourceLocation RPLoc) {
Steve Naroff63bad2d2007-08-01 22:05:33 +00004802 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4803 QualType argT2 = QualType::getFromOpaquePtr(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00004804
Steve Naroff63bad2d2007-08-01 22:05:33 +00004805 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00004806
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004807 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
4808 argT1, argT2, RPLoc));
Steve Naroff63bad2d2007-08-01 22:05:33 +00004809}
4810
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004811Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
4812 ExprArg cond,
4813 ExprArg expr1, ExprArg expr2,
4814 SourceLocation RPLoc) {
4815 Expr *CondExpr = static_cast<Expr*>(cond.get());
4816 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
4817 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump9afab102009-02-19 03:04:26 +00004818
Steve Naroff93c53012007-08-03 21:21:27 +00004819 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4820
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004821 QualType resType;
4822 if (CondExpr->isValueDependent()) {
4823 resType = Context.DependentTy;
4824 } else {
4825 // The conditional expression is required to be a constant expression.
4826 llvm::APSInt condEval(32);
4827 SourceLocation ExpLoc;
4828 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004829 return ExprError(Diag(ExpLoc,
4830 diag::err_typecheck_choose_expr_requires_constant)
4831 << CondExpr->getSourceRange());
Steve Naroff93c53012007-08-03 21:21:27 +00004832
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004833 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4834 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
4835 }
4836
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004837 cond.release(); expr1.release(); expr2.release();
4838 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4839 resType, RPLoc));
Steve Naroff93c53012007-08-03 21:21:27 +00004840}
4841
Steve Naroff52a81c02008-09-03 18:15:37 +00004842//===----------------------------------------------------------------------===//
4843// Clang Extensions.
4844//===----------------------------------------------------------------------===//
4845
4846/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004847void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004848 // Analyze block parameters.
4849 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00004850
Steve Naroff52a81c02008-09-03 18:15:37 +00004851 // Add BSI to CurBlock.
4852 BSI->PrevBlockInfo = CurBlock;
4853 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00004854
Steve Naroff52a81c02008-09-03 18:15:37 +00004855 BSI->ReturnType = 0;
4856 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00004857 BSI->hasBlockDeclRefExprs = false;
Chris Lattnere7765e12009-04-19 05:28:12 +00004858 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
4859 CurFunctionNeedsScopeChecking = false;
Mike Stump9afab102009-02-19 03:04:26 +00004860
Steve Naroff52059382008-10-10 01:28:17 +00004861 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004862 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004863}
4864
Mike Stumpc1fddff2009-02-04 22:31:32 +00004865void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4866 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4867
Mike Stump9e439c92009-04-29 21:40:37 +00004868 ProcessDeclAttributes(CurBlock->TheDecl, ParamInfo);
4869
Mike Stumpc1fddff2009-02-04 22:31:32 +00004870 if (ParamInfo.getNumTypeObjects() == 0
4871 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4872 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4873
Mike Stump458287d2009-04-28 01:10:27 +00004874 if (T->isArrayType()) {
4875 Diag(ParamInfo.getSourceRange().getBegin(),
4876 diag::err_block_returns_array);
4877 return;
4878 }
4879
Mike Stumpc1fddff2009-02-04 22:31:32 +00004880 // The parameter list is optional, if there was none, assume ().
4881 if (!T->isFunctionType())
4882 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4883
4884 CurBlock->hasPrototype = true;
4885 CurBlock->isVariadic = false;
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00004886
4887 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
4888
4889 // Do not allow returning a objc interface by-value.
4890 if (RetTy->isObjCInterfaceType()) {
4891 Diag(ParamInfo.getSourceRange().getBegin(),
4892 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
4893 return;
4894 }
Mike Stumpc1fddff2009-02-04 22:31:32 +00004895 return;
4896 }
4897
Steve Naroff52a81c02008-09-03 18:15:37 +00004898 // Analyze arguments to block.
4899 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4900 "Not a function declarator!");
4901 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00004902
Steve Naroff52059382008-10-10 01:28:17 +00004903 CurBlock->hasPrototype = FTI.hasPrototype;
4904 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00004905
Steve Naroff52a81c02008-09-03 18:15:37 +00004906 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4907 // no arguments, not a function that takes a single void argument.
4908 if (FTI.hasPrototype &&
4909 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner5261d0c2009-03-28 19:18:32 +00004910 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
4911 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004912 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004913 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004914 } else if (FTI.hasPrototype) {
4915 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner5261d0c2009-03-28 19:18:32 +00004916 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff52059382008-10-10 01:28:17 +00004917 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00004918 }
Steve Naroff494cb0f2009-03-13 16:56:44 +00004919 CurBlock->TheDecl->setParams(Context, &CurBlock->Params[0],
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00004920 CurBlock->Params.size());
Mike Stump9afab102009-02-19 03:04:26 +00004921
Steve Naroff52059382008-10-10 01:28:17 +00004922 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4923 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4924 // If this has an identifier, add it to the scope stack.
4925 if ((*AI)->getIdentifier())
4926 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00004927
4928 // Analyze the return type.
4929 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4930 QualType RetTy = T->getAsFunctionType()->getResultType();
4931
4932 // Do not allow returning a objc interface by-value.
4933 if (RetTy->isObjCInterfaceType()) {
4934 Diag(ParamInfo.getSourceRange().getBegin(),
4935 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
4936 } else if (!RetTy->isDependentType())
4937 CurBlock->ReturnType = RetTy.getTypePtr();
Steve Naroff52a81c02008-09-03 18:15:37 +00004938}
4939
4940/// ActOnBlockError - If there is an error parsing a block, this callback
4941/// is invoked to pop the information about the block from the action impl.
4942void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4943 // Ensure that CurBlock is deleted.
4944 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00004945
Chris Lattnere7765e12009-04-19 05:28:12 +00004946 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
4947
Steve Naroff52a81c02008-09-03 18:15:37 +00004948 // Pop off CurBlock, handle nested blocks.
Chris Lattnereb4d4a52009-04-21 22:38:46 +00004949 PopDeclContext();
Steve Naroff52a81c02008-09-03 18:15:37 +00004950 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff52a81c02008-09-03 18:15:37 +00004951 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff52a81c02008-09-03 18:15:37 +00004952}
4953
4954/// ActOnBlockStmtExpr - This is called when the body of a block statement
4955/// literal was successfully completed. ^(int x){...}
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004956Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
4957 StmtArg body, Scope *CurScope) {
Chris Lattnerc14c7f02009-03-27 04:18:06 +00004958 // If blocks are disabled, emit an error.
4959 if (!LangOpts.Blocks)
4960 Diag(CaretLoc, diag::err_blocks_disable);
4961
Steve Naroff52a81c02008-09-03 18:15:37 +00004962 // Ensure that CurBlock is deleted.
4963 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff52a81c02008-09-03 18:15:37 +00004964
Steve Naroff52059382008-10-10 01:28:17 +00004965 PopDeclContext();
4966
Steve Naroff52a81c02008-09-03 18:15:37 +00004967 // Pop off CurBlock, handle nested blocks.
4968 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004969
Steve Naroff52a81c02008-09-03 18:15:37 +00004970 QualType RetTy = Context.VoidTy;
4971 if (BSI->ReturnType)
4972 RetTy = QualType(BSI->ReturnType, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004973
Steve Naroff52a81c02008-09-03 18:15:37 +00004974 llvm::SmallVector<QualType, 8> ArgTypes;
4975 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4976 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00004977
Steve Naroff52a81c02008-09-03 18:15:37 +00004978 QualType BlockTy;
4979 if (!BSI->hasPrototype)
Douglas Gregor4fa58902009-02-26 23:50:07 +00004980 BlockTy = Context.getFunctionNoProtoType(RetTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004981 else
4982 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004983 BSI->isVariadic, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004984
Eli Friedman2b128322009-03-23 00:24:07 +00004985 // FIXME: Check that return/parameter types are complete/non-abstract
4986
Steve Naroff52a81c02008-09-03 18:15:37 +00004987 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00004988
Chris Lattnere7765e12009-04-19 05:28:12 +00004989 // If needed, diagnose invalid gotos and switches in the block.
4990 if (CurFunctionNeedsScopeChecking)
4991 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
4992 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
4993
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00004994 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004995 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
4996 BSI->hasBlockDeclRefExprs));
Steve Naroff52a81c02008-09-03 18:15:37 +00004997}
4998
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004999Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5000 ExprArg expr, TypeTy *type,
5001 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00005002 QualType T = QualType::getFromOpaquePtr(type);
Chris Lattnerda139482009-04-05 15:49:53 +00005003 Expr *E = static_cast<Expr*>(expr.get());
5004 Expr *OrigExpr = E;
5005
Anders Carlsson36760332007-10-15 20:28:48 +00005006 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005007
5008 // Get the va_list type
5009 QualType VaListType = Context.getBuiltinVaListType();
5010 // Deal with implicit array decay; for example, on x86-64,
5011 // va_list is an array, but it's supposed to decay to
5012 // a pointer for va_arg.
5013 if (VaListType->isArrayType())
5014 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00005015 // Make sure the input expression also decays appropriately.
5016 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005017
Chris Lattnercb9469d2009-04-06 17:07:34 +00005018 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005019 return ExprError(Diag(E->getLocStart(),
5020 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerda139482009-04-05 15:49:53 +00005021 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner89a72c52009-04-05 00:59:53 +00005022 }
Mike Stump9afab102009-02-19 03:04:26 +00005023
Eli Friedman2b128322009-03-23 00:24:07 +00005024 // FIXME: Check that type is complete/non-abstract
Anders Carlsson36760332007-10-15 20:28:48 +00005025 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00005026
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005027 expr.release();
5028 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5029 RPLoc));
Anders Carlsson36760332007-10-15 20:28:48 +00005030}
5031
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005032Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregorad4b3792008-11-29 04:51:27 +00005033 // The type of __null will be int or long, depending on the size of
5034 // pointers on the target.
5035 QualType Ty;
5036 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5037 Ty = Context.IntTy;
5038 else
5039 Ty = Context.LongTy;
5040
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005041 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregorad4b3792008-11-29 04:51:27 +00005042}
5043
Chris Lattner005ed752008-01-04 18:04:52 +00005044bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5045 SourceLocation Loc,
5046 QualType DstType, QualType SrcType,
5047 Expr *SrcExpr, const char *Flavor) {
5048 // Decode the result (notice that AST's are still created for extensions).
5049 bool isInvalid = false;
5050 unsigned DiagKind;
5051 switch (ConvTy) {
5052 default: assert(0 && "Unknown conversion type");
5053 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005054 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00005055 DiagKind = diag::ext_typecheck_convert_pointer_int;
5056 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005057 case IntToPointer:
5058 DiagKind = diag::ext_typecheck_convert_int_pointer;
5059 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005060 case IncompatiblePointer:
5061 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5062 break;
Eli Friedman6ca28cb2009-03-22 23:59:44 +00005063 case IncompatiblePointerSign:
5064 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5065 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005066 case FunctionVoidPointer:
5067 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5068 break;
5069 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00005070 // If the qualifiers lost were because we were applying the
5071 // (deprecated) C++ conversion from a string literal to a char*
5072 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
5073 // Ideally, this check would be performed in
5074 // CheckPointerTypesForAssignment. However, that would require a
5075 // bit of refactoring (so that the second argument is an
5076 // expression, rather than a type), which should be done as part
5077 // of a larger effort to fix CheckPointerTypesForAssignment for
5078 // C++ semantics.
5079 if (getLangOptions().CPlusPlus &&
5080 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5081 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00005082 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5083 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005084 case IntToBlockPointer:
5085 DiagKind = diag::err_int_to_block_pointer;
5086 break;
5087 case IncompatibleBlockPointer:
Mike Stumpd331e752009-04-21 22:51:42 +00005088 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005089 break;
Steve Naroff19608432008-10-14 22:18:38 +00005090 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00005091 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00005092 // it can give a more specific diagnostic.
5093 DiagKind = diag::warn_incompatible_qualified_id;
5094 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00005095 case IncompatibleVectors:
5096 DiagKind = diag::warn_incompatible_vectors;
5097 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005098 case Incompatible:
5099 DiagKind = diag::err_typecheck_convert_incompatible;
5100 isInvalid = true;
5101 break;
5102 }
Mike Stump9afab102009-02-19 03:04:26 +00005103
Chris Lattner271d4c22008-11-24 05:29:24 +00005104 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5105 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00005106 return isInvalid;
5107}
Anders Carlssond5201b92008-11-30 19:50:32 +00005108
Chris Lattnereec8ae22009-04-25 21:59:05 +00005109bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmance329412009-04-25 22:26:58 +00005110 llvm::APSInt ICEResult;
5111 if (E->isIntegerConstantExpr(ICEResult, Context)) {
5112 if (Result)
5113 *Result = ICEResult;
5114 return false;
5115 }
5116
Anders Carlssond5201b92008-11-30 19:50:32 +00005117 Expr::EvalResult EvalResult;
5118
Mike Stump9afab102009-02-19 03:04:26 +00005119 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00005120 EvalResult.HasSideEffects) {
5121 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5122
5123 if (EvalResult.Diag) {
5124 // We only show the note if it's not the usual "invalid subexpression"
5125 // or if it's actually in a subexpression.
5126 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5127 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5128 Diag(EvalResult.DiagLoc, EvalResult.Diag);
5129 }
Mike Stump9afab102009-02-19 03:04:26 +00005130
Anders Carlssond5201b92008-11-30 19:50:32 +00005131 return true;
5132 }
5133
Eli Friedmance329412009-04-25 22:26:58 +00005134 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5135 E->getSourceRange();
Anders Carlssond5201b92008-11-30 19:50:32 +00005136
Eli Friedmance329412009-04-25 22:26:58 +00005137 if (EvalResult.Diag &&
5138 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5139 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump9afab102009-02-19 03:04:26 +00005140
Anders Carlssond5201b92008-11-30 19:50:32 +00005141 if (Result)
5142 *Result = EvalResult.Val.getInt();
5143 return false;
5144}