blob: 47b9fbd7bce9d132d5cd775fca6ca92cdf594b79 [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
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000267 // Perform bitfield promotions.
268 QualType LHSBitfieldPromoteTy = isPromotableBitField(lhsExpr, Context);
269 if (!LHSBitfieldPromoteTy.isNull())
270 lhs = LHSBitfieldPromoteTy;
271 QualType RHSBitfieldPromoteTy = isPromotableBitField(rhsExpr, Context);
272 if (!RHSBitfieldPromoteTy.isNull())
273 rhs = RHSBitfieldPromoteTy;
274
Douglas Gregor70d26122008-11-12 17:17:38 +0000275 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman3cd92882009-03-28 01:22:36 +0000276 if (!isCompAssign)
Douglas Gregor70d26122008-11-12 17:17:38 +0000277 ImpCastExprToType(lhsExpr, destType);
Eli Friedman3cd92882009-03-28 01:22:36 +0000278 ImpCastExprToType(rhsExpr, destType);
Douglas Gregor70d26122008-11-12 17:17:38 +0000279 return destType;
280}
281
282QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
283 // Perform the usual unary conversions. We do this early so that
284 // integral promotions to "int" can allow us to exit early, in the
285 // lhs == rhs check. Also, for conversion purposes, we ignore any
286 // qualifiers. For example, "const float" and "float" are
287 // equivalent.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000288 if (lhs->isPromotableIntegerType())
289 lhs = Context.IntTy;
290 else
291 lhs = lhs.getUnqualifiedType();
292 if (rhs->isPromotableIntegerType())
293 rhs = Context.IntTy;
294 else
295 rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000296
Chris Lattner299b8842008-07-25 21:10:04 +0000297 // If both types are identical, no conversion is needed.
298 if (lhs == rhs)
299 return lhs;
300
301 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
302 // The caller can deal with this (e.g. pointer + int).
303 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
304 return lhs;
305
306 // At this point, we have two different arithmetic types.
307
308 // Handle complex types first (C99 6.3.1.8p1).
309 if (lhs->isComplexType() || rhs->isComplexType()) {
310 // if we have an integer operand, the result is the complex type.
311 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
312 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000313 return lhs;
314 }
315 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
316 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000317 return rhs;
318 }
319 // This handles complex/complex, complex/float, or float/complex.
320 // When both operands are complex, the shorter operand is converted to the
321 // type of the longer, and that is the type of the result. This corresponds
322 // to what is done when combining two real floating-point operands.
323 // The fun begins when size promotion occur across type domains.
324 // From H&S 6.3.4: When one operand is complex and the other is a real
325 // floating-point type, the less precise type is converted, within it's
326 // real or complex domain, to the precision of the other type. For example,
327 // when combining a "long double" with a "double _Complex", the
328 // "double _Complex" is promoted to "long double _Complex".
329 int result = Context.getFloatingTypeOrder(lhs, rhs);
330
331 if (result > 0) { // The left side is bigger, convert rhs.
332 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000333 } else if (result < 0) { // The right side is bigger, convert lhs.
334 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000335 }
336 // At this point, lhs and rhs have the same rank/size. Now, make sure the
337 // domains match. This is a requirement for our implementation, C99
338 // does not require this promotion.
339 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
340 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000341 return rhs;
342 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000343 return lhs;
344 }
345 }
346 return lhs; // The domain/size match exactly.
347 }
348 // Now handle "real" floating types (i.e. float, double, long double).
349 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
350 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000351 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000352 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000353 return lhs;
354 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000355 if (rhs->isComplexIntegerType()) {
356 // convert rhs to the complex floating point type.
357 return Context.getComplexType(lhs);
358 }
359 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000360 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000361 return rhs;
362 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000363 if (lhs->isComplexIntegerType()) {
364 // convert lhs to the complex floating point type.
365 return Context.getComplexType(rhs);
366 }
Chris Lattner299b8842008-07-25 21:10:04 +0000367 // We have two real floating types, float/complex combos were handled above.
368 // Convert the smaller operand to the bigger result.
369 int result = Context.getFloatingTypeOrder(lhs, rhs);
Chris Lattner2cb744b2009-02-15 22:43:40 +0000370 if (result > 0) // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000371 return lhs;
Chris Lattner2cb744b2009-02-15 22:43:40 +0000372 assert(result < 0 && "illegal float comparison");
373 return rhs; // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000374 }
375 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
376 // Handle GCC complex int extension.
377 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
378 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
379
380 if (lhsComplexInt && rhsComplexInt) {
381 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
Chris Lattner2cb744b2009-02-15 22:43:40 +0000382 rhsComplexInt->getElementType()) >= 0)
383 return lhs; // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000384 return rhs;
385 } else if (lhsComplexInt && rhs->isIntegerType()) {
386 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000387 return lhs;
388 } else if (rhsComplexInt && lhs->isIntegerType()) {
389 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000390 return rhs;
391 }
392 }
393 // Finally, we have two differing integer types.
394 // The rules for this case are in C99 6.3.1.8
395 int compare = Context.getIntegerTypeOrder(lhs, rhs);
396 bool lhsSigned = lhs->isSignedIntegerType(),
397 rhsSigned = rhs->isSignedIntegerType();
398 QualType destType;
399 if (lhsSigned == rhsSigned) {
400 // Same signedness; use the higher-ranked type
401 destType = compare >= 0 ? lhs : rhs;
402 } else if (compare != (lhsSigned ? 1 : -1)) {
403 // The unsigned type has greater than or equal rank to the
404 // signed type, so use the unsigned type
405 destType = lhsSigned ? rhs : lhs;
406 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
407 // The two types are different widths; if we are here, that
408 // means the signed type is larger than the unsigned type, so
409 // use the signed type.
410 destType = lhsSigned ? lhs : rhs;
411 } else {
412 // The signed type is higher-ranked than the unsigned type,
413 // but isn't actually any bigger (like unsigned int and long
414 // on most 32-bit systems). Use the unsigned type corresponding
415 // to the signed type.
416 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
417 }
Chris Lattner299b8842008-07-25 21:10:04 +0000418 return destType;
419}
420
421//===----------------------------------------------------------------------===//
422// Semantic Analysis for various Expression Types
423//===----------------------------------------------------------------------===//
424
425
Steve Naroff87d58b42007-09-16 03:34:24 +0000426/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000427/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
428/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
429/// multiple tokens. However, the common case is that StringToks points to one
430/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000431///
432Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000433Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000434 assert(NumStringToks && "Must have at least one string!");
435
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000436 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000437 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000438 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000439
440 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
441 for (unsigned i = 0; i != NumStringToks; ++i)
442 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000443
Chris Lattnera6dcce32008-02-11 00:02:17 +0000444 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000445 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000446 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000447
448 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
449 if (getLangOptions().CPlusPlus)
450 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000451
Chris Lattnera6dcce32008-02-11 00:02:17 +0000452 // Get an array type for the string, according to C99 6.4.5. This includes
453 // the nul terminator character as well as the string length for pascal
454 // strings.
455 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattner14032222009-02-26 23:01:51 +0000456 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000457 ArrayType::Normal, 0);
Chris Lattnerc3144742009-02-18 05:49:11 +0000458
Chris Lattner4b009652007-07-25 00:24:17 +0000459 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattneraa491192009-02-18 06:40:38 +0000460 return Owned(StringLiteral::Create(Context, Literal.GetString(),
461 Literal.GetStringLength(),
462 Literal.AnyWide, StrTy,
463 &StringTokLocs[0],
464 StringTokLocs.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000465}
466
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000467/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
468/// CurBlock to VD should cause it to be snapshotted (as we do for auto
469/// variables defined outside the block) or false if this is not needed (e.g.
470/// for values inside the block or for globals).
471///
Chris Lattner0b464252009-04-21 22:26:47 +0000472/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
473/// up-to-date.
474///
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000475static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
476 ValueDecl *VD) {
477 // If the value is defined inside the block, we couldn't snapshot it even if
478 // we wanted to.
479 if (CurBlock->TheDecl == VD->getDeclContext())
480 return false;
481
482 // If this is an enum constant or function, it is constant, don't snapshot.
483 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
484 return false;
485
486 // If this is a reference to an extern, static, or global variable, no need to
487 // snapshot it.
488 // FIXME: What about 'const' variables in C++?
489 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner0b464252009-04-21 22:26:47 +0000490 if (!Var->hasLocalStorage())
491 return false;
492
493 // Blocks that have these can't be constant.
494 CurBlock->hasBlockDeclRefExprs = true;
495
496 // If we have nested blocks, the decl may be declared in an outer block (in
497 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
498 // be defined outside all of the current blocks (in which case the blocks do
499 // all get the bit). Walk the nesting chain.
500 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
501 NextBlock = NextBlock->PrevBlockInfo) {
502 // If we found the defining block for the variable, don't mark the block as
503 // having a reference outside it.
504 if (NextBlock->TheDecl == VD->getDeclContext())
505 break;
506
507 // Otherwise, the DeclRef from the inner block causes the outer one to need
508 // a snapshot as well.
509 NextBlock->hasBlockDeclRefExprs = true;
510 }
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000511
512 return true;
513}
514
515
516
Steve Naroff0acc9c92007-09-15 18:49:24 +0000517/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000518/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000519/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000520/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000521/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000522Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
523 IdentifierInfo &II,
524 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000525 const CXXScopeSpec *SS,
526 bool isAddressOfOperand) {
527 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000528 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000529}
530
Douglas Gregor566782a2009-01-06 05:10:23 +0000531/// BuildDeclRefExpr - Build either a DeclRefExpr or a
532/// QualifiedDeclRefExpr based on whether or not SS is a
533/// nested-name-specifier.
Sebastian Redl0c9da212009-02-03 20:19:35 +0000534DeclRefExpr *
535Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
536 bool TypeDependent, bool ValueDependent,
537 const CXXScopeSpec *SS) {
Douglas Gregor7e508262009-03-19 03:51:16 +0000538 if (SS && !SS->isEmpty()) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000539 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
540 ValueDependent, SS->getRange(),
Douglas Gregor041e9292009-03-26 23:56:24 +0000541 static_cast<NestedNameSpecifier *>(SS->getScopeRep()));
Douglas Gregor7e508262009-03-19 03:51:16 +0000542 } else
Steve Naroff774e4152009-01-21 00:14:39 +0000543 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000544}
545
Douglas Gregor723d3332009-01-07 00:43:41 +0000546/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
547/// variable corresponding to the anonymous union or struct whose type
548/// is Record.
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000549static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
550 RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000551 assert(Record->isAnonymousStructOrUnion() &&
552 "Record must be an anonymous struct or union!");
553
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000554 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000555 // be an O(1) operation rather than a slow walk through DeclContext's
556 // vector (which itself will be eliminated). DeclGroups might make
557 // this even better.
558 DeclContext *Ctx = Record->getDeclContext();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000559 for (DeclContext::decl_iterator D = Ctx->decls_begin(Context),
560 DEnd = Ctx->decls_end(Context);
Douglas Gregor723d3332009-01-07 00:43:41 +0000561 D != DEnd; ++D) {
562 if (*D == Record) {
563 // The object for the anonymous struct/union directly
564 // follows its type in the list of declarations.
565 ++D;
566 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000567 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000568 return *D;
569 }
570 }
571
572 assert(false && "Missing object for anonymous record");
573 return 0;
574}
575
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000576/// \brief Given a field that represents a member of an anonymous
577/// struct/union, build the path from that field's context to the
578/// actual member.
579///
580/// Construct the sequence of field member references we'll have to
581/// perform to get to the field in the anonymous union/struct. The
582/// list of members is built from the field outward, so traverse it
583/// backwards to go from an object in the current context to the field
584/// we found.
585///
586/// \returns The variable from which the field access should begin,
587/// for an anonymous struct/union that is not a member of another
588/// class. Otherwise, returns NULL.
589VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
590 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000591 assert(Field->getDeclContext()->isRecord() &&
592 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
593 && "Field must be stored inside an anonymous struct or union");
594
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000595 Path.push_back(Field);
Douglas Gregor723d3332009-01-07 00:43:41 +0000596 VarDecl *BaseObject = 0;
597 DeclContext *Ctx = Field->getDeclContext();
598 do {
599 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000600 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000601 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000602 Path.push_back(AnonField);
Douglas Gregor723d3332009-01-07 00:43:41 +0000603 else {
604 BaseObject = cast<VarDecl>(AnonObject);
605 break;
606 }
607 Ctx = Ctx->getParent();
608 } while (Ctx->isRecord() &&
609 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000610
611 return BaseObject;
612}
613
614Sema::OwningExprResult
615Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
616 FieldDecl *Field,
617 Expr *BaseObjectExpr,
618 SourceLocation OpLoc) {
619 llvm::SmallVector<FieldDecl *, 4> AnonFields;
620 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
621 AnonFields);
622
Douglas Gregor723d3332009-01-07 00:43:41 +0000623 // Build the expression that refers to the base object, from
624 // which we will build a sequence of member references to each
625 // of the anonymous union objects and, eventually, the field we
626 // found via name lookup.
627 bool BaseObjectIsPointer = false;
628 unsigned ExtraQuals = 0;
629 if (BaseObject) {
630 // BaseObject is an anonymous struct/union variable (and is,
631 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000632 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff774e4152009-01-21 00:14:39 +0000633 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump9afab102009-02-19 03:04:26 +0000634 SourceLocation());
Douglas Gregor723d3332009-01-07 00:43:41 +0000635 ExtraQuals
636 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
637 } else if (BaseObjectExpr) {
638 // The caller provided the base object expression. Determine
639 // whether its a pointer and whether it adds any qualifiers to the
640 // anonymous struct/union fields we're looking into.
641 QualType ObjectType = BaseObjectExpr->getType();
642 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
643 BaseObjectIsPointer = true;
644 ObjectType = ObjectPtr->getPointeeType();
645 }
646 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
647 } else {
648 // We've found a member of an anonymous struct/union that is
649 // inside a non-anonymous struct/union, so in a well-formed
650 // program our base object expression is "this".
651 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
652 if (!MD->isStatic()) {
653 QualType AnonFieldType
654 = Context.getTagDeclType(
655 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
656 QualType ThisType = Context.getTagDeclType(MD->getParent());
657 if ((Context.getCanonicalType(AnonFieldType)
658 == Context.getCanonicalType(ThisType)) ||
659 IsDerivedFrom(ThisType, AnonFieldType)) {
660 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000661 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000662 MD->getThisType(Context));
Douglas Gregor723d3332009-01-07 00:43:41 +0000663 BaseObjectIsPointer = true;
664 }
665 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000666 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
667 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000668 }
669 ExtraQuals = MD->getTypeQualifiers();
670 }
671
672 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000673 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
674 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000675 }
676
677 // Build the implicit member references to the field of the
678 // anonymous struct/union.
679 Expr *Result = BaseObjectExpr;
680 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
681 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
682 FI != FIEnd; ++FI) {
683 QualType MemberType = (*FI)->getType();
684 if (!(*FI)->isMutable()) {
685 unsigned combinedQualifiers
686 = MemberType.getCVRQualifiers() | ExtraQuals;
687 MemberType = MemberType.getQualifiedType(combinedQualifiers);
688 }
Steve Naroff774e4152009-01-21 00:14:39 +0000689 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
690 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000691 BaseObjectIsPointer = false;
692 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregor723d3332009-01-07 00:43:41 +0000693 }
694
Sebastian Redlcd883f72009-01-18 18:53:16 +0000695 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000696}
697
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000698/// ActOnDeclarationNameExpr - The parser has read some kind of name
699/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
700/// performs lookup on that name and returns an expression that refers
701/// to that name. This routine isn't directly called from the parser,
702/// because the parser doesn't know about DeclarationName. Rather,
703/// this routine is called by ActOnIdentifierExpr,
704/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
705/// which form the DeclarationName from the corresponding syntactic
706/// forms.
707///
708/// HasTrailingLParen indicates whether this identifier is used in a
709/// function call context. LookupCtx is only used for a C++
710/// qualified-id (foo::bar) to indicate the class or namespace that
711/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000712///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000713/// isAddressOfOperand means that this expression is the direct operand
714/// of an address-of operator. This matters because this is the only
715/// situation where a qualified name referencing a non-static member may
716/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000717Sema::OwningExprResult
718Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
719 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000720 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000721 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000722 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000723 if (SS && SS->isInvalid())
724 return ExprError();
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000725
726 // C++ [temp.dep.expr]p3:
727 // An id-expression is type-dependent if it contains:
728 // -- a nested-name-specifier that contains a class-name that
729 // names a dependent type.
730 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000731 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
732 Loc, SS->getRange(),
Douglas Gregor041e9292009-03-26 23:56:24 +0000733 static_cast<NestedNameSpecifier *>(SS->getScopeRep())));
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000734 }
735
Douglas Gregor411889e2009-02-13 23:20:09 +0000736 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
737 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000738
Sebastian Redlcd883f72009-01-18 18:53:16 +0000739 if (Lookup.isAmbiguous()) {
740 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
741 SS && SS->isSet() ? SS->getRange()
742 : SourceRange());
743 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000744 }
745
746 NamedDecl *D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000747
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000748 // If this reference is in an Objective-C method, then ivar lookup happens as
749 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000750 IdentifierInfo *II = Name.getAsIdentifierInfo();
751 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000752 // There are two cases to handle here. 1) scoped lookup could have failed,
753 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000754 // found a decl, but that decl is outside the current instance method (i.e.
755 // a global variable). In these two cases, we do a lookup for an ivar with
756 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000757 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000758 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000759 ObjCInterfaceDecl *ClassDeclared;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000760 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(Context, II,
761 ClassDeclared)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000762 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000763 if (DiagnoseUseOfDecl(IV, Loc))
764 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000765
766 // If we're referencing an invalid decl, just return this as a silent
767 // error node. The error diagnostic was already emitted on the decl.
768 if (IV->isInvalidDecl())
769 return ExprError();
770
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000771 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
772 // If a class method attemps to use a free standing ivar, this is
773 // an error.
774 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
775 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
776 << IV->getDeclName());
777 // If a class method uses a global variable, even if an ivar with
778 // same name exists, use the global.
779 if (!IsClsMethod) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000780 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
781 ClassDeclared != IFace)
782 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000783 // FIXME: This should use a new expr for a direct reference, don't turn
784 // this into Self->ivar, just return a BareIVarExpr or something.
785 IdentifierInfo &II = Context.Idents.get("self");
786 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Daniel Dunbarf5254bd2009-04-21 01:19:28 +0000787 return Owned(new (Context)
788 ObjCIvarRefExpr(IV, IV->getType(), Loc,
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000789 SelfExpr.takeAs<Expr>(), true, true));
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000790 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000791 }
792 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000793 else if (getCurMethodDecl()->isInstanceMethod()) {
794 // We should warn if a local variable hides an ivar.
795 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000796 ObjCInterfaceDecl *ClassDeclared;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000797 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(Context, II,
798 ClassDeclared)) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000799 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
800 IFace == ClassDeclared)
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000801 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000802 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000803 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000804 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000805 if (D == 0 && II->isStr("super")) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000806 QualType T;
807
808 if (getCurMethodDecl()->isInstanceMethod())
809 T = Context.getPointerType(Context.getObjCInterfaceType(
810 getCurMethodDecl()->getClassInterface()));
811 else
812 T = Context.getObjCClassType();
Steve Naroff774e4152009-01-21 00:14:39 +0000813 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000814 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000815 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000816
Douglas Gregoraa57e862009-02-18 21:56:37 +0000817 // Determine whether this name might be a candidate for
818 // argument-dependent lookup.
819 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
820 HasTrailingLParen;
821
822 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000823 // We've seen something of the form
824 //
825 // identifier(
826 //
827 // and we did not find any entity by the name
828 // "identifier". However, this identifier is still subject to
829 // argument-dependent lookup, so keep track of the name.
830 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
831 Context.OverloadTy,
832 Loc));
833 }
834
Chris Lattner4b009652007-07-25 00:24:17 +0000835 if (D == 0) {
836 // Otherwise, this could be an implicitly declared function reference (legal
837 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000838 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000839 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000840 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000841 else {
842 // If this name wasn't predeclared and if this is not a function call,
843 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000844 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000845 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
846 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000847 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
848 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000849 return ExprError(Diag(Loc, diag::err_undeclared_use)
850 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000851 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000852 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000853 }
854 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000855
Sebastian Redl0c9da212009-02-03 20:19:35 +0000856 // If this is an expression of the form &Class::member, don't build an
857 // implicit member ref, because we want a pointer to the member in general,
858 // not any specific instance's member.
859 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000860 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor09be81b2009-02-04 17:27:36 +0000861 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000862 QualType DType;
863 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
864 DType = FD->getType().getNonReferenceType();
865 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
866 DType = Method->getType();
867 } else if (isa<OverloadedFunctionDecl>(D)) {
868 DType = Context.OverloadTy;
869 }
870 // Could be an inner type. That's diagnosed below, so ignore it here.
871 if (!DType.isNull()) {
872 // The pointer is type- and value-dependent if it points into something
873 // dependent.
874 bool Dependent = false;
875 for (; DC; DC = DC->getParent()) {
876 // FIXME: could stop early at namespace scope.
877 if (DC->isRecord()) {
878 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
879 if (Context.getTypeDeclType(Record)->isDependentType()) {
880 Dependent = true;
881 break;
882 }
883 }
884 }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000885 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000886 }
887 }
888 }
889
Douglas Gregor723d3332009-01-07 00:43:41 +0000890 // We may have found a field within an anonymous union or struct
891 // (C++ [class.union]).
892 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
893 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
894 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000895
Douglas Gregor3257fb52008-12-22 05:46:06 +0000896 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
897 if (!MD->isStatic()) {
898 // C++ [class.mfct.nonstatic]p2:
899 // [...] if name lookup (3.4.1) resolves the name in the
900 // id-expression to a nonstatic nontype member of class X or of
901 // a base class of X, the id-expression is transformed into a
902 // class member access expression (5.2.5) using (*this) (9.3.2)
903 // as the postfix-expression to the left of the '.' operator.
904 DeclContext *Ctx = 0;
905 QualType MemberType;
906 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
907 Ctx = FD->getDeclContext();
908 MemberType = FD->getType();
909
910 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
911 MemberType = RefType->getPointeeType();
912 else if (!FD->isMutable()) {
913 unsigned combinedQualifiers
914 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
915 MemberType = MemberType.getQualifiedType(combinedQualifiers);
916 }
917 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
918 if (!Method->isStatic()) {
919 Ctx = Method->getParent();
920 MemberType = Method->getType();
921 }
922 } else if (OverloadedFunctionDecl *Ovl
923 = dyn_cast<OverloadedFunctionDecl>(D)) {
924 for (OverloadedFunctionDecl::function_iterator
925 Func = Ovl->function_begin(),
926 FuncEnd = Ovl->function_end();
927 Func != FuncEnd; ++Func) {
928 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
929 if (!DMethod->isStatic()) {
930 Ctx = Ovl->getDeclContext();
931 MemberType = Context.OverloadTy;
932 break;
933 }
934 }
935 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000936
937 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000938 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
939 QualType ThisType = Context.getTagDeclType(MD->getParent());
940 if ((Context.getCanonicalType(CtxType)
941 == Context.getCanonicalType(ThisType)) ||
942 IsDerivedFrom(ThisType, CtxType)) {
943 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000944 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000945 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +0000946 return Owned(new (Context) MemberExpr(This, true, D,
Eli Friedman1653e232009-04-29 17:56:47 +0000947 Loc, MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000948 }
949 }
950 }
951 }
952
Douglas Gregor8acb7272008-12-11 16:49:14 +0000953 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000954 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
955 if (MD->isStatic())
956 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000957 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
958 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000959 }
960
Douglas Gregor3257fb52008-12-22 05:46:06 +0000961 // Any other ways we could have found the field in a well-formed
962 // program would have been turned into implicit member expressions
963 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000964 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
965 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000966 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000967
Chris Lattner4b009652007-07-25 00:24:17 +0000968 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000969 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000970 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000971 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000972 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000973 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000974
Steve Naroffd6163f32008-09-05 22:11:13 +0000975 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000976 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000977 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
978 false, false, SS));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000979 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
980 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
981 false, false, SS));
Steve Naroffd6163f32008-09-05 22:11:13 +0000982 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000983
Douglas Gregoraa57e862009-02-18 21:56:37 +0000984 // Check whether this declaration can be used. Note that we suppress
985 // this check when we're going to perform argument-dependent lookup
986 // on this function name, because this might not be the function
987 // that overload resolution actually selects.
988 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
989 return ExprError();
990
Douglas Gregor48840c72008-12-10 23:01:14 +0000991 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000992 // Warn about constructs like:
993 // if (void *X = foo()) { ... } else { X }.
994 // In the else block, the pointer is always false.
Douglas Gregor48840c72008-12-10 23:01:14 +0000995 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
996 Scope *CheckS = S;
997 while (CheckS) {
998 if (CheckS->isWithinElse() &&
Chris Lattner5261d0c2009-03-28 19:18:32 +0000999 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
Douglas Gregor48840c72008-12-10 23:01:14 +00001000 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001001 ExprError(Diag(Loc, diag::warn_value_always_false)
1002 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +00001003 else
Sebastian Redlcd883f72009-01-18 18:53:16 +00001004 ExprError(Diag(Loc, diag::warn_value_always_zero)
1005 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +00001006 break;
1007 }
1008
1009 // Move up one more control parent to check again.
1010 CheckS = CheckS->getControlParent();
1011 if (CheckS)
1012 CheckS = CheckS->getParent();
1013 }
1014 }
Douglas Gregor1f88aa72009-02-25 16:33:18 +00001015 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(VD)) {
1016 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1017 // C99 DR 316 says that, if a function type comes from a
1018 // function definition (without a prototype), that type is only
1019 // used for checking compatibility. Therefore, when referencing
1020 // the function, we pretend that we don't have the full function
1021 // type.
1022 QualType T = Func->getType();
1023 QualType NoProtoType = T;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001024 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
1025 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
Douglas Gregor1f88aa72009-02-25 16:33:18 +00001026 return Owned(BuildDeclRefExpr(VD, NoProtoType, Loc, false, false, SS));
1027 }
Douglas Gregor48840c72008-12-10 23:01:14 +00001028 }
Steve Naroffd6163f32008-09-05 22:11:13 +00001029
1030 // Only create DeclRefExpr's for valid Decl's.
1031 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001032 return ExprError();
1033
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001034 // If the identifier reference is inside a block, and it refers to a value
1035 // that is outside the block, create a BlockDeclRefExpr instead of a
1036 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1037 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +00001038 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001039 // We do not do this for things like enum constants, global variables, etc,
1040 // as they do not get snapshotted.
1041 //
1042 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001043 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff52059382008-10-10 01:28:17 +00001044 // The BlocksAttr indicates the variable is bound by-reference.
1045 if (VD->getAttr<BlocksAttr>())
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001046 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001047
Steve Naroff52059382008-10-10 01:28:17 +00001048 // Variable will be bound by-copy, make it const within the closure.
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001049 ExprTy.addConst();
1050 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +00001051 }
1052 // If this reference is not in a block or if the referenced variable is
1053 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001054
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001055 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +00001056 bool ValueDependent = false;
1057 if (getLangOptions().CPlusPlus) {
1058 // C++ [temp.dep.expr]p3:
1059 // An id-expression is type-dependent if it contains:
1060 // - an identifier that was declared with a dependent type,
1061 if (VD->getType()->isDependentType())
1062 TypeDependent = true;
1063 // - FIXME: a template-id that is dependent,
1064 // - a conversion-function-id that specifies a dependent type,
1065 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1066 Name.getCXXNameType()->isDependentType())
1067 TypeDependent = true;
1068 // - a nested-name-specifier that contains a class-name that
1069 // names a dependent type.
1070 else if (SS && !SS->isEmpty()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001071 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregora5d84612008-12-10 20:57:37 +00001072 DC; DC = DC->getParent()) {
1073 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +00001074 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +00001075 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1076 if (Context.getTypeDeclType(Record)->isDependentType()) {
1077 TypeDependent = true;
1078 break;
1079 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001080 }
1081 }
1082 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001083
Douglas Gregora5d84612008-12-10 20:57:37 +00001084 // C++ [temp.dep.constexpr]p2:
1085 //
1086 // An identifier is value-dependent if it is:
1087 // - a name declared with a dependent type,
1088 if (TypeDependent)
1089 ValueDependent = true;
1090 // - the name of a non-type template parameter,
1091 else if (isa<NonTypeTemplateParmDecl>(VD))
1092 ValueDependent = true;
1093 // - a constant with integral or enumeration type and is
1094 // initialized with an expression that is value-dependent
1095 // (FIXME!).
1096 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001097
Sebastian Redlcd883f72009-01-18 18:53:16 +00001098 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1099 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +00001100}
1101
Sebastian Redlcd883f72009-01-18 18:53:16 +00001102Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1103 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +00001104 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001105
Chris Lattner4b009652007-07-25 00:24:17 +00001106 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001107 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +00001108 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1109 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1110 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001111 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001112
Chris Lattner7e637512008-01-12 08:14:25 +00001113 // Pre-defined identifiers are of type char[x], where x is the length of the
1114 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001115 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +00001116 if (FunctionDecl *FD = getCurFunctionDecl())
1117 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +00001118 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1119 Length = MD->getSynthesizedMethodSize();
1120 else {
1121 Diag(Loc, diag::ext_predef_outside_function);
1122 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1123 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1124 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001125
1126
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001127 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001128 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001129 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +00001130 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +00001131}
1132
Sebastian Redlcd883f72009-01-18 18:53:16 +00001133Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +00001134 llvm::SmallString<16> CharBuffer;
1135 CharBuffer.resize(Tok.getLength());
1136 const char *ThisTokBegin = &CharBuffer[0];
1137 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001138
Chris Lattner4b009652007-07-25 00:24:17 +00001139 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1140 Tok.getLocation(), PP);
1141 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001142 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001143
1144 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1145
Sebastian Redl75324932009-01-20 22:23:13 +00001146 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1147 Literal.isWide(),
1148 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001149}
1150
Sebastian Redlcd883f72009-01-18 18:53:16 +00001151Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1152 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001153 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1154 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001155 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001156 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001157 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001158 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001159 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001160
Chris Lattner4b009652007-07-25 00:24:17 +00001161 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001162 // Add padding so that NumericLiteralParser can overread by one character.
1163 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001164 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001165
Chris Lattner4b009652007-07-25 00:24:17 +00001166 // Get the spelling of the token, which eliminates trigraphs, etc.
1167 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001168
Chris Lattner4b009652007-07-25 00:24:17 +00001169 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1170 Tok.getLocation(), PP);
1171 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001172 return ExprError();
1173
Chris Lattner1de66eb2007-08-26 03:42:43 +00001174 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001175
Chris Lattner1de66eb2007-08-26 03:42:43 +00001176 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001177 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001178 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001179 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001180 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001181 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001182 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001183 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001184
1185 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1186
Ted Kremenekddedbe22007-11-29 00:56:49 +00001187 // isExact will be set by GetFloatValue().
1188 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +00001189 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
1190 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001191
Chris Lattner1de66eb2007-08-26 03:42:43 +00001192 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001193 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001194 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001195 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001196
Neil Booth7421e9c2007-08-29 22:00:19 +00001197 // long long is a C99 feature.
1198 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001199 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001200 Diag(Tok.getLocation(), diag::ext_longlong);
1201
Chris Lattner4b009652007-07-25 00:24:17 +00001202 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001203 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001204
Chris Lattner4b009652007-07-25 00:24:17 +00001205 if (Literal.GetIntegerValue(ResultVal)) {
1206 // If this value didn't fit into uintmax_t, warn and force to ull.
1207 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001208 Ty = Context.UnsignedLongLongTy;
1209 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001210 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001211 } else {
1212 // If this value fits into a ULL, try to figure out what else it fits into
1213 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001214
Chris Lattner4b009652007-07-25 00:24:17 +00001215 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1216 // be an unsigned int.
1217 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1218
1219 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001220 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001221 if (!Literal.isLong && !Literal.isLongLong) {
1222 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001223 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001224
Chris Lattner4b009652007-07-25 00:24:17 +00001225 // Does it fit in a unsigned int?
1226 if (ResultVal.isIntN(IntSize)) {
1227 // Does it fit in a signed int?
1228 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001229 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001230 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001231 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001232 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001233 }
Chris Lattner4b009652007-07-25 00:24:17 +00001234 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001235
Chris Lattner4b009652007-07-25 00:24:17 +00001236 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001237 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001238 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001239
Chris Lattner4b009652007-07-25 00:24:17 +00001240 // Does it fit in a unsigned long?
1241 if (ResultVal.isIntN(LongSize)) {
1242 // Does it fit in a signed long?
1243 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001244 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001245 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001246 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001247 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001248 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001249 }
1250
Chris Lattner4b009652007-07-25 00:24:17 +00001251 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001252 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001253 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001254
Chris Lattner4b009652007-07-25 00:24:17 +00001255 // Does it fit in a unsigned long long?
1256 if (ResultVal.isIntN(LongLongSize)) {
1257 // Does it fit in a signed long long?
1258 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001259 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001260 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001261 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001262 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001263 }
1264 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001265
Chris Lattner4b009652007-07-25 00:24:17 +00001266 // If we still couldn't decide a type, we probably have something that
1267 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001268 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001269 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001270 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001271 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001272 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001273
Chris Lattnere4068872008-05-09 05:59:00 +00001274 if (ResultVal.getBitWidth() != Width)
1275 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001276 }
Sebastian Redl75324932009-01-20 22:23:13 +00001277 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001278 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001279
Chris Lattner1de66eb2007-08-26 03:42:43 +00001280 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1281 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001282 Res = new (Context) ImaginaryLiteral(Res,
1283 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001284
1285 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001286}
1287
Sebastian Redlcd883f72009-01-18 18:53:16 +00001288Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1289 SourceLocation R, ExprArg Val) {
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001290 Expr *E = Val.takeAs<Expr>();
Chris Lattner48d7f382008-04-02 04:24:33 +00001291 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001292 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001293}
1294
1295/// The UsualUnaryConversions() function is *not* called by this routine.
1296/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001297bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001298 SourceLocation OpLoc,
1299 const SourceRange &ExprRange,
1300 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001301 if (exprType->isDependentType())
1302 return false;
1303
Chris Lattner4b009652007-07-25 00:24:17 +00001304 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001305 if (isa<FunctionType>(exprType)) {
Chris Lattner95933c12009-04-24 00:30:45 +00001306 // alignof(function) is allowed as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001307 if (isSizeof)
1308 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1309 return false;
1310 }
1311
Chris Lattner95933c12009-04-24 00:30:45 +00001312 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001313 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001314 Diag(OpLoc, diag::ext_sizeof_void_type)
1315 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001316 return false;
1317 }
Chris Lattnere1127c42009-04-21 19:55:16 +00001318
Chris Lattner95933c12009-04-24 00:30:45 +00001319 if (RequireCompleteType(OpLoc, exprType,
1320 isSizeof ? diag::err_sizeof_incomplete_type :
1321 diag::err_alignof_incomplete_type,
1322 ExprRange))
1323 return true;
1324
1325 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianbf2b0952009-04-24 17:34:33 +00001326 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner95933c12009-04-24 00:30:45 +00001327 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnerf3ce8572009-04-24 22:30:50 +00001328 << exprType << isSizeof << ExprRange;
1329 return true;
Chris Lattnere1127c42009-04-21 19:55:16 +00001330 }
1331
Chris Lattner95933c12009-04-24 00:30:45 +00001332 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001333}
1334
Chris Lattner8d9f7962009-01-24 20:17:12 +00001335bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1336 const SourceRange &ExprRange) {
1337 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001338
Chris Lattner8d9f7962009-01-24 20:17:12 +00001339 // alignof decl is always ok.
1340 if (isa<DeclRefExpr>(E))
1341 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001342
1343 // Cannot know anything else if the expression is dependent.
1344 if (E->isTypeDependent())
1345 return false;
1346
Chris Lattner8d9f7962009-01-24 20:17:12 +00001347 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1348 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1349 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001350 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001351 return true;
1352 }
1353 // Other fields are ok.
1354 return false;
1355 }
1356 }
1357 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1358}
1359
Douglas Gregor396f1142009-03-13 21:01:28 +00001360/// \brief Build a sizeof or alignof expression given a type operand.
1361Action::OwningExprResult
1362Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1363 bool isSizeOf, SourceRange R) {
1364 if (T.isNull())
1365 return ExprError();
1366
1367 if (!T->isDependentType() &&
1368 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1369 return ExprError();
1370
1371 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1372 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1373 Context.getSizeType(), OpLoc,
1374 R.getEnd()));
1375}
1376
1377/// \brief Build a sizeof or alignof expression given an expression
1378/// operand.
1379Action::OwningExprResult
1380Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1381 bool isSizeOf, SourceRange R) {
1382 // Verify that the operand is valid.
1383 bool isInvalid = false;
1384 if (E->isTypeDependent()) {
1385 // Delay type-checking for type-dependent expressions.
1386 } else if (!isSizeOf) {
1387 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
1388 } else if (E->isBitField()) { // C99 6.5.3.4p1.
1389 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1390 isInvalid = true;
1391 } else {
1392 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1393 }
1394
1395 if (isInvalid)
1396 return ExprError();
1397
1398 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1399 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1400 Context.getSizeType(), OpLoc,
1401 R.getEnd()));
1402}
1403
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001404/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1405/// the same for @c alignof and @c __alignof
1406/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001407Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001408Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1409 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001410 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001411 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001412
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001413 if (isType) {
Douglas Gregor396f1142009-03-13 21:01:28 +00001414 QualType ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1415 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1416 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001417
Douglas Gregor396f1142009-03-13 21:01:28 +00001418 // Get the end location.
1419 Expr *ArgEx = (Expr *)TyOrEx;
1420 Action::OwningExprResult Result
1421 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1422
1423 if (Result.isInvalid())
1424 DeleteExpr(ArgEx);
1425
1426 return move(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001427}
1428
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001429QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001430 if (V->isTypeDependent())
1431 return Context.DependentTy;
Chris Lattner03931a72007-08-24 21:16:53 +00001432
Chris Lattnera16e42d2007-08-26 05:39:26 +00001433 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001434 if (const ComplexType *CT = V->getType()->getAsComplexType())
1435 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001436
1437 // Otherwise they pass through real integer and floating point types here.
1438 if (V->getType()->isArithmeticType())
1439 return V->getType();
1440
1441 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001442 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1443 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001444 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001445}
1446
1447
Chris Lattner4b009652007-07-25 00:24:17 +00001448
Sebastian Redl8b769972009-01-19 00:08:26 +00001449Action::OwningExprResult
1450Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1451 tok::TokenKind Kind, ExprArg Input) {
1452 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001453
Chris Lattner4b009652007-07-25 00:24:17 +00001454 UnaryOperator::Opcode Opc;
1455 switch (Kind) {
1456 default: assert(0 && "Unknown unary op!");
1457 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1458 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1459 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001460
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001461 if (getLangOptions().CPlusPlus &&
1462 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1463 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001464 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001465 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1466
1467 // C++ [over.inc]p1:
1468 //
1469 // [...] If the function is a member function with one
1470 // parameter (which shall be of type int) or a non-member
1471 // function with two parameters (the second of which shall be
1472 // of type int), it defines the postfix increment operator ++
1473 // for objects of that type. When the postfix increment is
1474 // called as a result of using the ++ operator, the int
1475 // argument will have value zero.
1476 Expr *Args[2] = {
1477 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001478 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1479 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001480 };
1481
1482 // Build the candidate set for overloading
1483 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001484 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001485
1486 // Perform overload resolution.
1487 OverloadCandidateSet::iterator Best;
1488 switch (BestViableFunction(CandidateSet, Best)) {
1489 case OR_Success: {
1490 // We found a built-in operator or an overloaded operator.
1491 FunctionDecl *FnDecl = Best->Function;
1492
1493 if (FnDecl) {
1494 // We matched an overloaded operator. Build a call to that
1495 // operator.
1496
1497 // Convert the arguments.
1498 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1499 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001500 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001501 } else {
1502 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001503 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001504 FnDecl->getParamDecl(0)->getType(),
1505 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001506 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001507 }
1508
1509 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001510 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001511 = FnDecl->getType()->getAsFunctionType()->getResultType();
1512 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001513
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001514 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001515 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001516 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001517 UsualUnaryConversions(FnExpr);
1518
Sebastian Redl8b769972009-01-19 00:08:26 +00001519 Input.release();
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001520 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1521 Args, 2, ResultTy,
1522 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001523 } else {
1524 // We matched a built-in operator. Convert the arguments, then
1525 // break out so that we will build the appropriate built-in
1526 // operator node.
1527 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1528 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001529 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001530
1531 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001532 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001533 }
1534
1535 case OR_No_Viable_Function:
1536 // No viable function; fall through to handling this as a
1537 // built-in operator, which will produce an error message for us.
1538 break;
1539
1540 case OR_Ambiguous:
1541 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1542 << UnaryOperator::getOpcodeStr(Opc)
1543 << Arg->getSourceRange();
1544 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001545 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001546
1547 case OR_Deleted:
1548 Diag(OpLoc, diag::err_ovl_deleted_oper)
1549 << Best->Function->isDeleted()
1550 << UnaryOperator::getOpcodeStr(Opc)
1551 << Arg->getSourceRange();
1552 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1553 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001554 }
1555
1556 // Either we found no viable overloaded operator or we matched a
1557 // built-in operator. In either case, fall through to trying to
1558 // build a built-in operation.
1559 }
1560
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001561 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1562 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001563 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001564 return ExprError();
1565 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001566 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001567}
1568
Sebastian Redl8b769972009-01-19 00:08:26 +00001569Action::OwningExprResult
1570Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1571 ExprArg Idx, SourceLocation RLoc) {
1572 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1573 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001574
Douglas Gregor80723c52008-11-19 17:17:41 +00001575 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001576 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001577 LHSExp->getType()->isEnumeralType() ||
1578 RHSExp->getType()->isRecordType() ||
1579 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001580 // Add the appropriate overloaded operators (C++ [over.match.oper])
1581 // to the candidate set.
1582 OverloadCandidateSet CandidateSet;
1583 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001584 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1585 SourceRange(LLoc, RLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001586
Douglas Gregor80723c52008-11-19 17:17:41 +00001587 // Perform overload resolution.
1588 OverloadCandidateSet::iterator Best;
1589 switch (BestViableFunction(CandidateSet, Best)) {
1590 case OR_Success: {
1591 // We found a built-in operator or an overloaded operator.
1592 FunctionDecl *FnDecl = Best->Function;
1593
1594 if (FnDecl) {
1595 // We matched an overloaded operator. Build a call to that
1596 // operator.
1597
1598 // Convert the arguments.
1599 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1600 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1601 PerformCopyInitialization(RHSExp,
1602 FnDecl->getParamDecl(0)->getType(),
1603 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001604 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001605 } else {
1606 // Convert the arguments.
1607 if (PerformCopyInitialization(LHSExp,
1608 FnDecl->getParamDecl(0)->getType(),
1609 "passing") ||
1610 PerformCopyInitialization(RHSExp,
1611 FnDecl->getParamDecl(1)->getType(),
1612 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001613 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001614 }
1615
1616 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001617 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001618 = FnDecl->getType()->getAsFunctionType()->getResultType();
1619 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001620
Douglas Gregor80723c52008-11-19 17:17:41 +00001621 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001622 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1623 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001624 UsualUnaryConversions(FnExpr);
1625
Sebastian Redl8b769972009-01-19 00:08:26 +00001626 Base.release();
1627 Idx.release();
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001628 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1629 FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001630 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001631 } else {
1632 // We matched a built-in operator. Convert the arguments, then
1633 // break out so that we will build the appropriate built-in
1634 // operator node.
1635 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1636 "passing") ||
1637 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1638 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001639 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001640
1641 break;
1642 }
1643 }
1644
1645 case OR_No_Viable_Function:
1646 // No viable function; fall through to handling this as a
1647 // built-in operator, which will produce an error message for us.
1648 break;
1649
1650 case OR_Ambiguous:
1651 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1652 << "[]"
1653 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1654 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001655 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001656
1657 case OR_Deleted:
1658 Diag(LLoc, diag::err_ovl_deleted_oper)
1659 << Best->Function->isDeleted()
1660 << "[]"
1661 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1662 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1663 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001664 }
1665
1666 // Either we found no viable overloaded operator or we matched a
1667 // built-in operator. In either case, fall through to trying to
1668 // build a built-in operation.
1669 }
1670
Chris Lattner4b009652007-07-25 00:24:17 +00001671 // Perform default conversions.
1672 DefaultFunctionArrayConversion(LHSExp);
1673 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001674
Chris Lattner4b009652007-07-25 00:24:17 +00001675 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1676
1677 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001678 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001679 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001680 // and index from the expression types.
1681 Expr *BaseExpr, *IndexExpr;
1682 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001683 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1684 BaseExpr = LHSExp;
1685 IndexExpr = RHSExp;
1686 ResultType = Context.DependentTy;
1687 } else if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001688 BaseExpr = LHSExp;
1689 IndexExpr = RHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001690 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001691 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001692 // Handle the uncommon case of "123[Ptr]".
1693 BaseExpr = RHSExp;
1694 IndexExpr = LHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001695 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001696 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1697 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001698 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001699
Chris Lattner4b009652007-07-25 00:24:17 +00001700 // FIXME: need to deal with const...
1701 ResultType = VTy->getElementType();
Eli Friedmand4614072009-04-25 23:46:54 +00001702 } else if (LHSTy->isArrayType()) {
1703 // If we see an array that wasn't promoted by
1704 // DefaultFunctionArrayConversion, it must be an array that
1705 // wasn't promoted because of the C90 rule that doesn't
1706 // allow promoting non-lvalue arrays. Warn, then
1707 // force the promotion here.
1708 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1709 LHSExp->getSourceRange();
1710 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1711 LHSTy = LHSExp->getType();
1712
1713 BaseExpr = LHSExp;
1714 IndexExpr = RHSExp;
1715 ResultType = LHSTy->getAsPointerType()->getPointeeType();
1716 } else if (RHSTy->isArrayType()) {
1717 // Same as previous, except for 123[f().a] case
1718 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1719 RHSExp->getSourceRange();
1720 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1721 RHSTy = RHSExp->getType();
1722
1723 BaseExpr = RHSExp;
1724 IndexExpr = LHSExp;
1725 ResultType = RHSTy->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001726 } else {
Chris Lattner7264d212009-04-25 22:50:55 +00001727 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1728 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00001729 }
Chris Lattner4b009652007-07-25 00:24:17 +00001730 // C99 6.5.2.1p1
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001731 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner7264d212009-04-25 22:50:55 +00001732 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1733 << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001734
Douglas Gregor05e28f62009-03-24 19:52:54 +00001735 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1736 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1737 // type. Note that Functions are not objects, and that (in C99 parlance)
1738 // incomplete types are not object types.
1739 if (ResultType->isFunctionType()) {
1740 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1741 << ResultType << BaseExpr->getSourceRange();
1742 return ExprError();
1743 }
Chris Lattner95933c12009-04-24 00:30:45 +00001744
Douglas Gregor05e28f62009-03-24 19:52:54 +00001745 if (!ResultType->isDependentType() &&
Chris Lattner95933c12009-04-24 00:30:45 +00001746 RequireCompleteType(LLoc, ResultType, diag::err_subscript_incomplete_type,
Douglas Gregor05e28f62009-03-24 19:52:54 +00001747 BaseExpr->getSourceRange()))
1748 return ExprError();
Chris Lattner95933c12009-04-24 00:30:45 +00001749
1750 // Diagnose bad cases where we step over interface counts.
1751 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1752 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1753 << ResultType << BaseExpr->getSourceRange();
1754 return ExprError();
1755 }
1756
Sebastian Redl8b769972009-01-19 00:08:26 +00001757 Base.release();
1758 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001759 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001760 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001761}
1762
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001763QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001764CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001765 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001766 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001767
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001768 // The vector accessor can't exceed the number of elements.
1769 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001770
Mike Stump9afab102009-02-19 03:04:26 +00001771 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001772 // special names that indicate a subset of exactly half the elements are
1773 // to be selected.
1774 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001775
Nate Begeman1486b502009-01-18 01:47:54 +00001776 // This flag determines whether or not CompName has an 's' char prefix,
1777 // indicating that it is a string of hex values to be used as vector indices.
1778 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001779
1780 // Check that we've found one of the special components, or that the component
1781 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001782 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001783 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1784 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001785 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001786 do
1787 compStr++;
1788 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001789 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001790 do
1791 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001792 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001793 }
Nate Begeman1486b502009-01-18 01:47:54 +00001794
Mike Stump9afab102009-02-19 03:04:26 +00001795 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001796 // We didn't get to the end of the string. This means the component names
1797 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001798 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1799 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001800 return QualType();
1801 }
Mike Stump9afab102009-02-19 03:04:26 +00001802
Nate Begeman1486b502009-01-18 01:47:54 +00001803 // Ensure no component accessor exceeds the width of the vector type it
1804 // operates on.
1805 if (!HalvingSwizzle) {
1806 compStr = CompName.getName();
1807
1808 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001809 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001810
1811 while (*compStr) {
1812 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1813 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1814 << baseType << SourceRange(CompLoc);
1815 return QualType();
1816 }
1817 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001818 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001819
Nate Begeman1486b502009-01-18 01:47:54 +00001820 // If this is a halving swizzle, verify that the base type has an even
1821 // number of elements.
1822 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001823 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001824 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001825 return QualType();
1826 }
Mike Stump9afab102009-02-19 03:04:26 +00001827
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001828 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001829 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001830 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001831 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001832 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001833 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1834 : CompName.getLength();
1835 if (HexSwizzle)
1836 CompSize--;
1837
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001838 if (CompSize == 1)
1839 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001840
Nate Begemanaf6ed502008-04-18 23:10:10 +00001841 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001842 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001843 // diagostics look bad. We want extended vector types to appear built-in.
1844 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1845 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1846 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001847 }
1848 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001849}
1850
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001851static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
1852 IdentifierInfo &Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001853 const Selector &Sel,
1854 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001855
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001856 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Context, &Member))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001857 return PD;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001858 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Context, Sel))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001859 return OMD;
1860
1861 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1862 E = PDecl->protocol_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001863 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
1864 Context))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001865 return D;
1866 }
1867 return 0;
1868}
1869
1870static Decl *FindGetterNameDecl(const ObjCQualifiedIdType *QIdTy,
1871 IdentifierInfo &Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001872 const Selector &Sel,
1873 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001874 // Check protocols on qualified interfaces.
1875 Decl *GDecl = 0;
1876 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1877 E = QIdTy->qual_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001878 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Context, &Member)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001879 GDecl = PD;
1880 break;
1881 }
1882 // Also must look for a getter name which uses property syntax.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001883 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Context, Sel)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001884 GDecl = OMD;
1885 break;
1886 }
1887 }
1888 if (!GDecl) {
1889 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1890 E = QIdTy->qual_end(); I != E; ++I) {
1891 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001892 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001893 if (GDecl)
1894 return GDecl;
1895 }
1896 }
1897 return GDecl;
1898}
Chris Lattner2cb744b2009-02-15 22:43:40 +00001899
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001900/// FindMethodInNestedImplementations - Look up a method in current and
1901/// all base class implementations.
1902///
1903ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
1904 const ObjCInterfaceDecl *IFace,
1905 const Selector &Sel) {
1906 ObjCMethodDecl *Method = 0;
Douglas Gregorafd5eb32009-04-24 00:11:27 +00001907 if (ObjCImplementationDecl *ImpDecl
1908 = LookupObjCImplementation(IFace->getIdentifier()))
Douglas Gregorcd19b572009-04-23 01:02:12 +00001909 Method = ImpDecl->getInstanceMethod(Context, Sel);
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001910
1911 if (!Method && IFace->getSuperClass())
1912 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
1913 return Method;
1914}
1915
Sebastian Redl8b769972009-01-19 00:08:26 +00001916Action::OwningExprResult
1917Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1918 tok::TokenKind OpKind, SourceLocation MemberLoc,
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00001919 IdentifierInfo &Member,
Chris Lattner5261d0c2009-03-28 19:18:32 +00001920 DeclPtrTy ObjCImpDecl) {
Anders Carlssonc154a722009-05-01 19:30:39 +00001921 Expr *BaseExpr = Base.takeAs<Expr>();
Steve Naroff2cb66382007-07-26 03:11:44 +00001922 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001923
1924 // Perform default conversions.
1925 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001926
Steve Naroff2cb66382007-07-26 03:11:44 +00001927 QualType BaseType = BaseExpr->getType();
1928 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001929
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001930 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1931 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001932 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001933 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001934 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001935 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001936 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1937 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001938 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001939 return ExprError(Diag(MemberLoc,
1940 diag::err_typecheck_member_reference_arrow)
1941 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001942 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001943
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001944 // Handle field access to simple records. This also handles access to fields
1945 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001946 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001947 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorc84d8932009-03-09 16:13:40 +00001948 if (RequireCompleteType(OpLoc, BaseType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001949 diag::err_typecheck_incomplete_tag,
1950 BaseExpr->getSourceRange()))
1951 return ExprError();
1952
Steve Naroff2cb66382007-07-26 03:11:44 +00001953 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001954 // FIXME: Qualified name lookup for C++ is a bit more complicated
1955 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001956 LookupResult Result
Mike Stump9afab102009-02-19 03:04:26 +00001957 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001958 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001959
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001960 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001961 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1962 << &Member << BaseExpr->getSourceRange());
Chris Lattner84ad8332009-03-31 08:18:48 +00001963 if (Result.isAmbiguous()) {
Sebastian Redl8b769972009-01-19 00:08:26 +00001964 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1965 MemberLoc, BaseExpr->getSourceRange());
1966 return ExprError();
Chris Lattner84ad8332009-03-31 08:18:48 +00001967 }
1968
1969 NamedDecl *MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001970
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001971 // If the decl being referenced had an error, return an error for this
1972 // sub-expr without emitting another error, in order to avoid cascading
1973 // error cases.
1974 if (MemberDecl->isInvalidDecl())
1975 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001976
Douglas Gregoraa57e862009-02-18 21:56:37 +00001977 // Check the use of this field
1978 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1979 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001980
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001981 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001982 // We may have found a field within an anonymous union or struct
1983 // (C++ [class.union]).
1984 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001985 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001986 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001987
Douglas Gregor82d44772008-12-20 23:49:58 +00001988 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1989 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001990 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001991 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1992 MemberType = Ref->getPointeeType();
1993 else {
1994 unsigned combinedQualifiers =
1995 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001996 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001997 combinedQualifiers &= ~QualType::Const;
1998 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1999 }
Eli Friedman76b49832008-02-06 22:48:16 +00002000
Steve Naroff774e4152009-01-21 00:14:39 +00002001 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
2002 MemberLoc, MemberType));
Chris Lattner84ad8332009-03-31 08:18:48 +00002003 }
2004
2005 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00002006 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Chris Lattner84ad8332009-03-31 08:18:48 +00002007 Var, MemberLoc,
2008 Var->getType().getNonReferenceType()));
2009 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00002010 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Chris Lattner84ad8332009-03-31 08:18:48 +00002011 MemberFn, MemberLoc,
2012 MemberFn->getType()));
2013 if (OverloadedFunctionDecl *Ovl
2014 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00002015 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Chris Lattner84ad8332009-03-31 08:18:48 +00002016 MemberLoc, Context.OverloadTy));
2017 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00002018 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
2019 Enum, MemberLoc, Enum->getType()));
Chris Lattner84ad8332009-03-31 08:18:48 +00002020 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00002021 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2022 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00002023
Douglas Gregor82d44772008-12-20 23:49:58 +00002024 // We found a declaration kind that we didn't expect. This is a
2025 // generic error message that tells the user that she can't refer
2026 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00002027 return ExprError(Diag(MemberLoc,
2028 diag::err_typecheck_member_reference_unknown)
2029 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00002030 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002031
Chris Lattnere9d71612008-07-21 04:59:05 +00002032 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2033 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002034 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002035 ObjCInterfaceDecl *ClassDeclared;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002036 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(Context,
2037 &Member,
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002038 ClassDeclared)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002039 // If the decl being referenced had an error, return an error for this
2040 // sub-expr without emitting another error, in order to avoid cascading
2041 // error cases.
2042 if (IV->isInvalidDecl())
2043 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00002044
2045 // Check whether we can reference this field.
2046 if (DiagnoseUseOfDecl(IV, MemberLoc))
2047 return ExprError();
Steve Naroff8c56ee02009-03-26 16:01:08 +00002048 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2049 IV->getAccessControl() != ObjCIvarDecl::Package) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002050 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2051 if (ObjCMethodDecl *MD = getCurMethodDecl())
2052 ClassOfMethodDecl = MD->getClassInterface();
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00002053 else if (ObjCImpDecl && getCurFunctionDecl()) {
2054 // Case of a c-function declared inside an objc implementation.
2055 // FIXME: For a c-style function nested inside an objc implementation
2056 // class, there is no implementation context available, so we pass down
2057 // the context as argument to this routine. Ideally, this context need
2058 // be passed down in the AST node and somehow calculated from the AST
2059 // for a function decl.
Chris Lattner5261d0c2009-03-28 19:18:32 +00002060 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00002061 if (ObjCImplementationDecl *IMPD =
2062 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2063 ClassOfMethodDecl = IMPD->getClassInterface();
2064 else if (ObjCCategoryImplDecl* CatImplClass =
2065 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2066 ClassOfMethodDecl = CatImplClass->getClassInterface();
Steve Narofff9606572009-03-04 18:34:24 +00002067 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002068
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00002069 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002070 if (ClassDeclared != IFTy->getDecl() ||
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00002071 ClassOfMethodDecl != ClassDeclared)
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002072 Diag(MemberLoc, diag::error_private_ivar_access) << IV->getDeclName();
2073 }
2074 // @protected
2075 else if (!IFTy->getDecl()->isSuperClassOf(ClassOfMethodDecl))
2076 Diag(MemberLoc, diag::error_protected_ivar_access) << IV->getDeclName();
2077 }
Mike Stump9afab102009-02-19 03:04:26 +00002078
Daniel Dunbarf5254bd2009-04-21 01:19:28 +00002079 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +00002080 MemberLoc, BaseExpr,
Daniel Dunbarf5254bd2009-04-21 01:19:28 +00002081 OpKind == tok::arrow));
Fariborz Jahanian09772392008-12-13 22:20:28 +00002082 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002083 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
2084 << IFTy->getDecl()->getDeclName() << &Member
2085 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00002086 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002087
Chris Lattnere9d71612008-07-21 04:59:05 +00002088 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2089 // pointer to a (potentially qualified) interface type.
2090 const PointerType *PTy;
2091 const ObjCInterfaceType *IFTy;
2092 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
2093 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
2094 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00002095
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002096 // Search for a declared property first.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002097 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Context,
2098 &Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002099 // Check whether we can reference this property.
2100 if (DiagnoseUseOfDecl(PD, MemberLoc))
2101 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00002102
Steve Naroff774e4152009-01-21 00:14:39 +00002103 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002104 MemberLoc, BaseExpr));
2105 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002106
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002107 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00002108 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
2109 E = IFTy->qual_end(); I != E; ++I)
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002110 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Context,
2111 &Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002112 // Check whether we can reference this property.
2113 if (DiagnoseUseOfDecl(PD, MemberLoc))
2114 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00002115
Steve Naroff774e4152009-01-21 00:14:39 +00002116 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002117 MemberLoc, BaseExpr));
2118 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002119
2120 // If that failed, look for an "implicit" property by seeing if the nullary
2121 // selector is implemented.
2122
2123 // FIXME: The logic for looking up nullary and unary selectors should be
2124 // shared with the code in ActOnInstanceMessage.
2125
2126 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002127 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Context, Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002128
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002129 // If this reference is in an @implementation, check for 'private' methods.
2130 if (!Getter)
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002131 Getter = FindMethodInNestedImplementations(IFace, Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002132
Steve Naroff04151f32008-10-22 19:16:27 +00002133 // Look through local category implementations associated with the class.
2134 if (!Getter) {
2135 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
2136 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
Douglas Gregorcd19b572009-04-23 01:02:12 +00002137 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Context, Sel);
Steve Naroff04151f32008-10-22 19:16:27 +00002138 }
2139 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002140 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002141 // Check if we can reference this property.
2142 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2143 return ExprError();
Steve Naroffdede0c92009-03-11 13:48:17 +00002144 }
2145 // If we found a getter then this may be a valid dot-reference, we
2146 // will look for the matching setter, in case it is needed.
2147 Selector SetterSel =
2148 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2149 PP.getSelectorTable(), &Member);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002150 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(Context, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002151 if (!Setter) {
2152 // If this reference is in an @implementation, also check for 'private'
2153 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002154 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002155 }
2156 // Look through local category implementations associated with the class.
2157 if (!Setter) {
2158 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
2159 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
Douglas Gregorcd19b572009-04-23 01:02:12 +00002160 Setter = ObjCCategoryImpls[i]->getInstanceMethod(Context, SetterSel);
Fariborz Jahanianc05da422008-11-22 20:25:50 +00002161 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002162 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002163
Steve Naroffdede0c92009-03-11 13:48:17 +00002164 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2165 return ExprError();
2166
2167 if (Getter || Setter) {
2168 QualType PType;
2169
2170 if (Getter)
2171 PType = Getter->getResultType();
2172 else {
2173 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2174 E = Setter->param_end(); PI != E; ++PI)
2175 PType = (*PI)->getType();
2176 }
2177 // FIXME: we must check that the setter has property type.
2178 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2179 Setter, MemberLoc, BaseExpr));
2180 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002181 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2182 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00002183 }
Steve Naroffd1d44402008-10-20 22:53:06 +00002184 // Handle properties on qualified "id" protocols.
2185 const ObjCQualifiedIdType *QIdTy;
2186 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
2187 // Check protocols on qualified interfaces.
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002188 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002189 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002190 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002191 // Check the use of this declaration
2192 if (DiagnoseUseOfDecl(PD, MemberLoc))
2193 return ExprError();
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002194
Steve Naroff774e4152009-01-21 00:14:39 +00002195 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002196 MemberLoc, BaseExpr));
2197 }
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002198 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002199 // Check the use of this method.
2200 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2201 return ExprError();
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002202
Mike Stump9afab102009-02-19 03:04:26 +00002203 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002204 OMD->getResultType(),
2205 OMD, OpLoc, MemberLoc,
2206 NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00002207 }
2208 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002209
2210 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2211 << &Member << BaseType);
Mike Stump9afab102009-02-19 03:04:26 +00002212 }
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002213 // Handle properties on ObjC 'Class' types.
2214 if (OpKind == tok::period && (BaseType == Context.getObjCClassType())) {
2215 // Also must look for a getter name which uses property syntax.
2216 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2217 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002218 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2219 ObjCMethodDecl *Getter;
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002220 // FIXME: need to also look locally in the implementation.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002221 if ((Getter = IFace->lookupClassMethod(Context, Sel))) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002222 // Check the use of this method.
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002223 if (DiagnoseUseOfDecl(Getter, MemberLoc))
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002224 return ExprError();
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002225 }
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002226 // If we found a getter then this may be a valid dot-reference, we
2227 // will look for the matching setter, in case it is needed.
2228 Selector SetterSel =
2229 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2230 PP.getSelectorTable(), &Member);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002231 ObjCMethodDecl *Setter = IFace->lookupClassMethod(Context, SetterSel);
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002232 if (!Setter) {
2233 // If this reference is in an @implementation, also check for 'private'
2234 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002235 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002236 }
2237 // Look through local category implementations associated with the class.
2238 if (!Setter) {
2239 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
2240 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
Douglas Gregorcd19b572009-04-23 01:02:12 +00002241 Setter = ObjCCategoryImpls[i]->getClassMethod(Context, SetterSel);
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002242 }
2243 }
2244
2245 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2246 return ExprError();
2247
2248 if (Getter || Setter) {
2249 QualType PType;
2250
2251 if (Getter)
2252 PType = Getter->getResultType();
2253 else {
2254 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2255 E = Setter->param_end(); PI != E; ++PI)
2256 PType = (*PI)->getType();
2257 }
2258 // FIXME: we must check that the setter has property type.
2259 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2260 Setter, MemberLoc, BaseExpr));
2261 }
2262 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2263 << &Member << BaseType);
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002264 }
2265 }
2266
Chris Lattnera57cf472008-07-21 04:28:12 +00002267 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00002268 if (BaseType->isExtVectorType()) {
Chris Lattnera57cf472008-07-21 04:28:12 +00002269 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2270 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00002271 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002272 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
Steve Naroff774e4152009-01-21 00:14:39 +00002273 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00002274 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002275
Douglas Gregor762da552009-03-27 06:00:30 +00002276 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2277 << BaseType << BaseExpr->getSourceRange();
2278
2279 // If the user is trying to apply -> or . to a function or function
2280 // pointer, it's probably because they forgot parentheses to call
2281 // the function. Suggest the addition of those parentheses.
2282 if (BaseType == Context.OverloadTy ||
2283 BaseType->isFunctionType() ||
2284 (BaseType->isPointerType() &&
2285 BaseType->getAsPointerType()->isFunctionType())) {
2286 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2287 Diag(Loc, diag::note_member_reference_needs_call)
2288 << CodeModificationHint::CreateInsertion(Loc, "()");
2289 }
2290
2291 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00002292}
2293
Douglas Gregor3257fb52008-12-22 05:46:06 +00002294/// ConvertArgumentsForCall - Converts the arguments specified in
2295/// Args/NumArgs to the parameter types of the function FDecl with
2296/// function prototype Proto. Call is the call expression itself, and
2297/// Fn is the function expression. For a C++ member function, this
2298/// routine does not attempt to convert the object argument. Returns
2299/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00002300bool
2301Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002302 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002303 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002304 Expr **Args, unsigned NumArgs,
2305 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00002306 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00002307 // assignment, to the types of the corresponding parameter, ...
2308 unsigned NumArgsInProto = Proto->getNumArgs();
2309 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002310 bool Invalid = false;
2311
Douglas Gregor3257fb52008-12-22 05:46:06 +00002312 // If too few arguments are available (and we don't have default
2313 // arguments for the remaining parameters), don't make the call.
2314 if (NumArgs < NumArgsInProto) {
2315 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2316 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2317 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2318 // Use default arguments for missing arguments
2319 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00002320 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002321 }
2322
2323 // If too many are passed and not variadic, error on the extras and drop
2324 // them.
2325 if (NumArgs > NumArgsInProto) {
2326 if (!Proto->isVariadic()) {
2327 Diag(Args[NumArgsInProto]->getLocStart(),
2328 diag::err_typecheck_call_too_many_args)
2329 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2330 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2331 Args[NumArgs-1]->getLocEnd());
2332 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002333 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002334 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002335 }
2336 NumArgsToCheck = NumArgsInProto;
2337 }
Mike Stump9afab102009-02-19 03:04:26 +00002338
Douglas Gregor3257fb52008-12-22 05:46:06 +00002339 // Continue to check argument types (even if we have too few/many args).
2340 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2341 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00002342
Douglas Gregor3257fb52008-12-22 05:46:06 +00002343 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002344 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002345 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002346
Eli Friedman83dec9e2009-03-22 22:00:50 +00002347 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2348 ProtoArgType,
2349 diag::err_call_incomplete_argument,
2350 Arg->getSourceRange()))
2351 return true;
2352
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002353 // Pass the argument.
2354 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2355 return true;
Mike Stump9afab102009-02-19 03:04:26 +00002356 } else
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002357 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00002358 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002359 QualType ArgType = Arg->getType();
Mike Stump9afab102009-02-19 03:04:26 +00002360
Douglas Gregor3257fb52008-12-22 05:46:06 +00002361 Call->setArg(i, Arg);
2362 }
Mike Stump9afab102009-02-19 03:04:26 +00002363
Douglas Gregor3257fb52008-12-22 05:46:06 +00002364 // If this is a variadic call, handle args passed through "...".
2365 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002366 VariadicCallType CallType = VariadicFunction;
2367 if (Fn->getType()->isBlockPointerType())
2368 CallType = VariadicBlock; // Block
2369 else if (isa<MemberExpr>(Fn))
2370 CallType = VariadicMethod;
2371
Douglas Gregor3257fb52008-12-22 05:46:06 +00002372 // Promote the arguments (C99 6.5.2.2p7).
2373 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2374 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00002375 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002376 Call->setArg(i, Arg);
2377 }
2378 }
2379
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002380 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002381}
2382
Steve Naroff87d58b42007-09-16 03:34:24 +00002383/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002384/// This provides the location of the left/right parens and a list of comma
2385/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002386Action::OwningExprResult
2387Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2388 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002389 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002390 unsigned NumArgs = args.size();
Anders Carlssonc154a722009-05-01 19:30:39 +00002391 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl8b769972009-01-19 00:08:26 +00002392 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002393 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002394 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002395 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002396
Douglas Gregor3257fb52008-12-22 05:46:06 +00002397 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002398 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002399 // in which case we won't do any semantic analysis now.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002400 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
2401 bool Dependent = false;
2402 if (Fn->isTypeDependent())
2403 Dependent = true;
2404 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2405 Dependent = true;
2406
2407 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002408 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002409 Context.DependentTy, RParenLoc));
2410
2411 // Determine whether this is a call to an object (C++ [over.call.object]).
2412 if (Fn->getType()->isRecordType())
2413 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2414 CommaLocs, RParenLoc));
2415
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002416 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002417 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
2418 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
2419 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00002420 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2421 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002422 }
2423
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002424 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00002425 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002426 Expr *FnExpr = Fn;
2427 bool ADL = true;
2428 while (true) {
2429 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2430 FnExpr = IcExpr->getSubExpr();
2431 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002432 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002433 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002434 ADL = false;
2435 FnExpr = PExpr->getSubExpr();
2436 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002437 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002438 == UnaryOperator::AddrOf) {
2439 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002440 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
2441 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2442 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2443 break;
Mike Stump9afab102009-02-19 03:04:26 +00002444 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002445 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2446 UnqualifiedName = DepName->getName();
2447 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002448 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002449 // Any kind of name that does not refer to a declaration (or
2450 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2451 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002452 break;
2453 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002454 }
Mike Stump9afab102009-02-19 03:04:26 +00002455
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002456 OverloadedFunctionDecl *Ovl = 0;
2457 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002458 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002459 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
2460 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002461
Douglas Gregorfcb19192009-02-11 23:02:49 +00002462 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002463 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002464 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002465 ADL = false;
2466
Douglas Gregorfcb19192009-02-11 23:02:49 +00002467 // We don't perform ADL in C.
2468 if (!getLangOptions().CPlusPlus)
2469 ADL = false;
2470
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002471 if (Ovl || ADL) {
Mike Stump9afab102009-02-19 03:04:26 +00002472 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2473 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002474 NumArgs, CommaLocs, RParenLoc, ADL);
2475 if (!FDecl)
2476 return ExprError();
2477
2478 // Update Fn to refer to the actual function selected.
2479 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002480 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002481 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Douglas Gregor1e589cc2009-03-26 23:50:42 +00002482 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2483 QDRExpr->getLocation(),
2484 false, false,
2485 QDRExpr->getQualifierRange(),
2486 QDRExpr->getQualifier());
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002487 else
Mike Stump9afab102009-02-19 03:04:26 +00002488 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002489 Fn->getSourceRange().getBegin());
2490 Fn->Destroy(Context);
2491 Fn = NewFn;
2492 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002493 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002494
2495 // Promote the function operand.
2496 UsualUnaryConversions(Fn);
2497
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002498 // Make the call expr early, before semantic checks. This guarantees cleanup
2499 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002500 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2501 Args, NumArgs,
2502 Context.BoolTy,
2503 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002504
Steve Naroffd6163f32008-09-05 22:11:13 +00002505 const FunctionType *FuncT;
2506 if (!Fn->getType()->isBlockPointerType()) {
2507 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2508 // have type pointer to function".
2509 const PointerType *PT = Fn->getType()->getAsPointerType();
2510 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002511 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2512 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002513 FuncT = PT->getPointeeType()->getAsFunctionType();
2514 } else { // This is a block call.
2515 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2516 getAsFunctionType();
2517 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002518 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002519 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2520 << Fn->getType() << Fn->getSourceRange());
2521
Eli Friedman83dec9e2009-03-22 22:00:50 +00002522 // Check for a valid return type
2523 if (!FuncT->getResultType()->isVoidType() &&
2524 RequireCompleteType(Fn->getSourceRange().getBegin(),
2525 FuncT->getResultType(),
2526 diag::err_call_incomplete_return,
2527 TheCall->getSourceRange()))
2528 return ExprError();
2529
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002530 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002531 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002532
Douglas Gregor4fa58902009-02-26 23:50:07 +00002533 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002534 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002535 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002536 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002537 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002538 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002539
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002540 if (FDecl) {
2541 // Check if we have too few/too many template arguments, based
2542 // on our knowledge of the function definition.
2543 const FunctionDecl *Def = 0;
Douglas Gregore3241e92009-04-18 00:02:19 +00002544 if (FDecl->getBody(Context, Def) && NumArgs != Def->param_size())
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002545 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2546 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2547 }
2548
Steve Naroffdb65e052007-08-28 23:30:39 +00002549 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002550 for (unsigned i = 0; i != NumArgs; i++) {
2551 Expr *Arg = Args[i];
2552 DefaultArgumentPromotion(Arg);
Eli Friedman83dec9e2009-03-22 22:00:50 +00002553 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2554 Arg->getType(),
2555 diag::err_call_incomplete_argument,
2556 Arg->getSourceRange()))
2557 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002558 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002559 }
Chris Lattner4b009652007-07-25 00:24:17 +00002560 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002561
Douglas Gregor3257fb52008-12-22 05:46:06 +00002562 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2563 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002564 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2565 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002566
Chris Lattner2e64c072007-08-10 20:18:51 +00002567 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00002568 if (FDecl)
2569 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002570
Sebastian Redl8b769972009-01-19 00:08:26 +00002571 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002572}
2573
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002574Action::OwningExprResult
2575Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2576 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002577 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002578 QualType literalType = QualType::getFromOpaquePtr(Ty);
2579 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002580 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002581 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002582
Eli Friedman8c2173d2008-05-20 05:22:08 +00002583 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002584 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002585 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2586 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregorc84d8932009-03-09 16:13:40 +00002587 } else if (RequireCompleteType(LParenLoc, literalType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002588 diag::err_typecheck_decl_incomplete_type,
2589 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002590 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002591
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002592 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002593 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002594 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002595
Chris Lattnere5cb5862008-12-04 23:50:19 +00002596 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002597 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002598 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002599 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002600 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002601 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002602 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002603 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002604}
2605
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002606Action::OwningExprResult
2607Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002608 SourceLocation RBraceLoc) {
2609 unsigned NumInit = initlist.size();
2610 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002611
Steve Naroff0acc9c92007-09-15 18:49:24 +00002612 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002613 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002614
Mike Stump9afab102009-02-19 03:04:26 +00002615 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002616 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002617 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002618 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002619}
2620
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002621/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002622bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002623 UsualUnaryConversions(castExpr);
2624
2625 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2626 // type needs to be scalar.
2627 if (castType->isVoidType()) {
2628 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002629 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2630 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002631 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002632 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2633 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2634 (castType->isStructureType() || castType->isUnionType())) {
2635 // GCC struct/union extension: allow cast to self.
Eli Friedman2b128322009-03-23 00:24:07 +00002636 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002637 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2638 << castType << castExpr->getSourceRange();
2639 } else if (castType->isUnionType()) {
2640 // GCC cast to union extension
2641 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2642 RecordDecl::field_iterator Field, FieldEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002643 for (Field = RD->field_begin(Context), FieldEnd = RD->field_end(Context);
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002644 Field != FieldEnd; ++Field) {
2645 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2646 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2647 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2648 << castExpr->getSourceRange();
2649 break;
2650 }
2651 }
2652 if (Field == FieldEnd)
2653 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2654 << castExpr->getType() << castExpr->getSourceRange();
2655 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002656 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002657 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002658 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002659 }
Mike Stump9afab102009-02-19 03:04:26 +00002660 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002661 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002662 return Diag(castExpr->getLocStart(),
2663 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002664 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002665 } else if (castExpr->getType()->isVectorType()) {
2666 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2667 return true;
2668 } else if (castType->isVectorType()) {
2669 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2670 return true;
Steve Naroffff6c8022009-03-04 15:11:40 +00002671 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroff49fd7ad2009-04-08 23:52:26 +00002672 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Eli Friedman970e56c2009-05-01 02:23:58 +00002673 } else if (!castType->isArithmeticType()) {
2674 QualType castExprType = castExpr->getType();
2675 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
2676 return Diag(castExpr->getLocStart(),
2677 diag::err_cast_pointer_from_non_pointer_int)
2678 << castExprType << castExpr->getSourceRange();
2679 } else if (!castExpr->getType()->isArithmeticType()) {
2680 if (!castType->isIntegralType() && castType->isArithmeticType())
2681 return Diag(castExpr->getLocStart(),
2682 diag::err_cast_pointer_to_non_pointer_int)
2683 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002684 }
2685 return false;
2686}
2687
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002688bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002689 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00002690
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002691 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002692 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002693 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00002694 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002695 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002696 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002697 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002698 } else
2699 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002700 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002701 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00002702
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002703 return false;
2704}
2705
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002706Action::OwningExprResult
2707Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2708 SourceLocation RParenLoc, ExprArg Op) {
2709 assert((Ty != 0) && (Op.get() != 0) &&
2710 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002711
Anders Carlssonc154a722009-05-01 19:30:39 +00002712 Expr *castExpr = Op.takeAs<Expr>();
Chris Lattner4b009652007-07-25 00:24:17 +00002713 QualType castType = QualType::getFromOpaquePtr(Ty);
2714
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002715 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002716 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002717 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Mike Stump9afab102009-02-19 03:04:26 +00002718 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002719}
2720
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00002721/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
2722/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00002723/// C99 6.5.15
2724QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2725 SourceLocation QuestionLoc) {
Sebastian Redlbd261962009-04-16 17:51:27 +00002726 // C++ is sufficiently different to merit its own checker.
2727 if (getLangOptions().CPlusPlus)
2728 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
2729
Chris Lattnere2897262009-02-18 04:28:32 +00002730 UsualUnaryConversions(Cond);
2731 UsualUnaryConversions(LHS);
2732 UsualUnaryConversions(RHS);
2733 QualType CondTy = Cond->getType();
2734 QualType LHSTy = LHS->getType();
2735 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002736
2737 // first, check the condition.
Sebastian Redlbd261962009-04-16 17:51:27 +00002738 if (!CondTy->isScalarType()) { // C99 6.5.15p2
2739 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2740 << CondTy;
2741 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002742 }
Mike Stump9afab102009-02-19 03:04:26 +00002743
Chris Lattner992ae932008-01-06 22:42:25 +00002744 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002745
Chris Lattner992ae932008-01-06 22:42:25 +00002746 // If both operands have arithmetic type, do the usual arithmetic conversions
2747 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00002748 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2749 UsualArithmeticConversions(LHS, RHS);
2750 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002751 }
Mike Stump9afab102009-02-19 03:04:26 +00002752
Chris Lattner992ae932008-01-06 22:42:25 +00002753 // If both operands are the same structure or union type, the result is that
2754 // type.
Chris Lattnere2897262009-02-18 04:28:32 +00002755 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
2756 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002757 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00002758 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00002759 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00002760 return LHSTy.getUnqualifiedType();
Eli Friedman2b128322009-03-23 00:24:07 +00002761 // FIXME: Type of conditional expression must be complete in C mode.
Chris Lattner4b009652007-07-25 00:24:17 +00002762 }
Mike Stump9afab102009-02-19 03:04:26 +00002763
Chris Lattner992ae932008-01-06 22:42:25 +00002764 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002765 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00002766 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2767 if (!LHSTy->isVoidType())
2768 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2769 << RHS->getSourceRange();
2770 if (!RHSTy->isVoidType())
2771 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2772 << LHS->getSourceRange();
2773 ImpCastExprToType(LHS, Context.VoidTy);
2774 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00002775 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002776 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002777 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2778 // the type of the other operand."
Chris Lattnere2897262009-02-18 04:28:32 +00002779 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2780 Context.isObjCObjectPointerType(LHSTy)) &&
2781 RHS->isNullPointerConstant(Context)) {
2782 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2783 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002784 }
Chris Lattnere2897262009-02-18 04:28:32 +00002785 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2786 Context.isObjCObjectPointerType(RHSTy)) &&
2787 LHS->isNullPointerConstant(Context)) {
2788 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2789 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002790 }
Mike Stump9afab102009-02-19 03:04:26 +00002791
Chris Lattner0ac51632008-01-06 22:50:31 +00002792 // Handle the case where both operands are pointers before we handle null
2793 // pointer constants in case both operands are null pointer constants.
Chris Lattnere2897262009-02-18 04:28:32 +00002794 if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6
2795 if (const PointerType *RHSPT = RHSTy->getAsPointerType()) {
Chris Lattner71225142007-07-31 21:27:01 +00002796 // get the "pointed to" types
2797 QualType lhptee = LHSPT->getPointeeType();
2798 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002799
Chris Lattner71225142007-07-31 21:27:01 +00002800 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2801 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002802 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002803 // Figure out necessary qualifiers (C99 6.5.15p6)
2804 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002805 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002806 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2807 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002808 return destType;
2809 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002810 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002811 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002812 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002813 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2814 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002815 return destType;
2816 }
Chris Lattner4b009652007-07-25 00:24:17 +00002817
Chris Lattner9c039b52009-02-18 04:38:20 +00002818 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
Chris Lattner676c86a2009-02-19 04:44:58 +00002819 // Two identical pointer types are always compatible.
Chris Lattner9c039b52009-02-18 04:38:20 +00002820 return LHSTy;
2821 }
Mike Stump9afab102009-02-19 03:04:26 +00002822
Chris Lattnere2897262009-02-18 04:28:32 +00002823 QualType compositeType = LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002824
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002825 // If either type is an Objective-C object type then check
2826 // compatibility according to Objective-C.
Mike Stump9afab102009-02-19 03:04:26 +00002827 if (Context.isObjCObjectPointerType(LHSTy) ||
Chris Lattnere2897262009-02-18 04:28:32 +00002828 Context.isObjCObjectPointerType(RHSTy)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002829 // If both operands are interfaces and either operand can be
2830 // assigned to the other, use that type as the composite
2831 // type. This allows
2832 // xxx ? (A*) a : (B*) b
2833 // where B is a subclass of A.
2834 //
2835 // Additionally, as for assignment, if either type is 'id'
2836 // allow silent coercion. Finally, if the types are
2837 // incompatible then make sure to use 'id' as the composite
2838 // type so the result is acceptable for sending messages to.
2839
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002840 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
Mike Stump9afab102009-02-19 03:04:26 +00002841 // It could return the composite type.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002842 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2843 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2844 if (LHSIface && RHSIface &&
2845 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002846 compositeType = LHSTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002847 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002848 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002849 compositeType = RHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002850 } else if (Context.isObjCIdStructType(lhptee) ||
2851 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002852 compositeType = Context.getObjCIdType();
2853 } else {
Chris Lattnere2897262009-02-18 04:28:32 +00002854 Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
Mike Stump9afab102009-02-19 03:04:26 +00002855 << LHSTy << RHSTy
Chris Lattnere2897262009-02-18 04:28:32 +00002856 << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002857 QualType incompatTy = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002858 ImpCastExprToType(LHS, incompatTy);
2859 ImpCastExprToType(RHS, incompatTy);
Mike Stump9afab102009-02-19 03:04:26 +00002860 return incompatTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002861 }
Mike Stump9afab102009-02-19 03:04:26 +00002862 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002863 rhptee.getUnqualifiedType())) {
Chris Lattnere2897262009-02-18 04:28:32 +00002864 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2865 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002866 // In this situation, we assume void* type. No especially good
2867 // reason, but this is what gcc does, and we do have to pick
2868 // to get a consistent AST.
2869 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Chris Lattnere2897262009-02-18 04:28:32 +00002870 ImpCastExprToType(LHS, incompatTy);
2871 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002872 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002873 }
2874 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002875 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2876 // differently qualified versions of compatible types, the result type is
2877 // a pointer to an appropriately qualified version of the *composite*
2878 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002879 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002880 // FIXME: Need to add qualifiers
Chris Lattnere2897262009-02-18 04:28:32 +00002881 ImpCastExprToType(LHS, compositeType);
2882 ImpCastExprToType(RHS, compositeType);
Eli Friedmane38150e2008-05-16 20:37:07 +00002883 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002884 }
Chris Lattner4b009652007-07-25 00:24:17 +00002885 }
Mike Stump9afab102009-02-19 03:04:26 +00002886
Steve Naroff6ba22682009-04-08 17:05:15 +00002887 // GCC compatibility: soften pointer/integer mismatch.
2888 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
2889 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
2890 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
2891 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
2892 return RHSTy;
2893 }
2894 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
2895 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
2896 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
2897 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
2898 return LHSTy;
2899 }
2900
Chris Lattner9c039b52009-02-18 04:38:20 +00002901 // Selection between block pointer types is ok as long as they are the same.
2902 if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() &&
2903 Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))
2904 return LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002905
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002906 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2907 // evaluates to "struct objc_object *" (and is handled above when comparing
Mike Stump9afab102009-02-19 03:04:26 +00002908 // id with statically typed objects).
2909 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002910 // GCC allows qualified id and any Objective-C type to devolve to
2911 // id. Currently localizing to here until clear this should be
2912 // part of ObjCQualifiedIdTypesAreCompatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002913 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
Mike Stump9afab102009-02-19 03:04:26 +00002914 (LHSTy->isObjCQualifiedIdType() &&
Chris Lattnere2897262009-02-18 04:28:32 +00002915 Context.isObjCObjectPointerType(RHSTy)) ||
2916 (RHSTy->isObjCQualifiedIdType() &&
2917 Context.isObjCObjectPointerType(LHSTy))) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002918 // FIXME: This is not the correct composite type. This only
2919 // happens to work because id can more or less be used anywhere,
2920 // however this may change the type of method sends.
2921 // FIXME: gcc adds some type-checking of the arguments and emits
2922 // (confusing) incompatible comparison warnings in some
2923 // cases. Investigate.
2924 QualType compositeType = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002925 ImpCastExprToType(LHS, compositeType);
2926 ImpCastExprToType(RHS, compositeType);
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002927 return compositeType;
2928 }
2929 }
2930
Chris Lattner992ae932008-01-06 22:42:25 +00002931 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002932 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2933 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002934 return QualType();
2935}
2936
Steve Naroff87d58b42007-09-16 03:34:24 +00002937/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002938/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002939Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2940 SourceLocation ColonLoc,
2941 ExprArg Cond, ExprArg LHS,
2942 ExprArg RHS) {
2943 Expr *CondExpr = (Expr *) Cond.get();
2944 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002945
2946 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2947 // was the condition.
2948 bool isLHSNull = LHSExpr == 0;
2949 if (isLHSNull)
2950 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002951
2952 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002953 RHSExpr, QuestionLoc);
2954 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002955 return ExprError();
2956
2957 Cond.release();
2958 LHS.release();
2959 RHS.release();
Mike Stump9afab102009-02-19 03:04:26 +00002960 return Owned(new (Context) ConditionalOperator(CondExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00002961 isLHSNull ? 0 : LHSExpr,
2962 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002963}
2964
Chris Lattner4b009652007-07-25 00:24:17 +00002965
2966// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00002967// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00002968// routine is it effectively iqnores the qualifiers on the top level pointee.
2969// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2970// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00002971Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002972Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2973 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00002974
Chris Lattner4b009652007-07-25 00:24:17 +00002975 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002976 lhptee = lhsType->getAsPointerType()->getPointeeType();
2977 rhptee = rhsType->getAsPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002978
Chris Lattner4b009652007-07-25 00:24:17 +00002979 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002980 lhptee = Context.getCanonicalType(lhptee);
2981 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002982
Chris Lattner005ed752008-01-04 18:04:52 +00002983 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00002984
2985 // C99 6.5.16.1p1: This following citation is common to constraints
2986 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2987 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00002988 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002989 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002990 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002991
Mike Stump9afab102009-02-19 03:04:26 +00002992 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2993 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00002994 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002995 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002996 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002997 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00002998
Chris Lattner4ca3d772008-01-03 22:56:36 +00002999 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003000 assert(rhptee->isFunctionType());
3001 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003002 }
Mike Stump9afab102009-02-19 03:04:26 +00003003
Chris Lattner4ca3d772008-01-03 22:56:36 +00003004 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003005 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003006 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003007
3008 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003009 assert(lhptee->isFunctionType());
3010 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003011 }
Mike Stump9afab102009-02-19 03:04:26 +00003012 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00003013 // unqualified versions of compatible types, ...
Eli Friedman6ca28cb2009-03-22 23:59:44 +00003014 lhptee = lhptee.getUnqualifiedType();
3015 rhptee = rhptee.getUnqualifiedType();
3016 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3017 // Check if the pointee types are compatible ignoring the sign.
3018 // We explicitly check for char so that we catch "char" vs
3019 // "unsigned char" on systems where "char" is unsigned.
3020 if (lhptee->isCharType()) {
3021 lhptee = Context.UnsignedCharTy;
3022 } else if (lhptee->isSignedIntegerType()) {
3023 lhptee = Context.getCorrespondingUnsignedType(lhptee);
3024 }
3025 if (rhptee->isCharType()) {
3026 rhptee = Context.UnsignedCharTy;
3027 } else if (rhptee->isSignedIntegerType()) {
3028 rhptee = Context.getCorrespondingUnsignedType(rhptee);
3029 }
3030 if (lhptee == rhptee) {
3031 // Types are compatible ignoring the sign. Qualifier incompatibility
3032 // takes priority over sign incompatibility because the sign
3033 // warning can be disabled.
3034 if (ConvTy != Compatible)
3035 return ConvTy;
3036 return IncompatiblePointerSign;
3037 }
3038 // General pointer incompatibility takes priority over qualifiers.
3039 return IncompatiblePointer;
3040 }
Chris Lattner005ed752008-01-04 18:04:52 +00003041 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003042}
3043
Steve Naroff3454b6c2008-09-04 15:10:53 +00003044/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3045/// block pointer types are compatible or whether a block and normal pointer
3046/// are compatible. It is more restrict than comparing two function pointer
3047// types.
Mike Stump9afab102009-02-19 03:04:26 +00003048Sema::AssignConvertType
3049Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00003050 QualType rhsType) {
3051 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003052
Steve Naroff3454b6c2008-09-04 15:10:53 +00003053 // get the "pointed to" type (ignoring qualifiers at the top level)
3054 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003055 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
3056
Steve Naroff3454b6c2008-09-04 15:10:53 +00003057 // make sure we operate on the canonical type
3058 lhptee = Context.getCanonicalType(lhptee);
3059 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00003060
Steve Naroff3454b6c2008-09-04 15:10:53 +00003061 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003062
Steve Naroff3454b6c2008-09-04 15:10:53 +00003063 // For blocks we enforce that qualifiers are identical.
3064 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3065 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00003066
Steve Naroff3454b6c2008-09-04 15:10:53 +00003067 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00003068 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003069 return ConvTy;
3070}
3071
Mike Stump9afab102009-02-19 03:04:26 +00003072/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3073/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00003074/// pointers. Here are some objectionable examples that GCC considers warnings:
3075///
3076/// int a, *pint;
3077/// short *pshort;
3078/// struct foo *pfoo;
3079///
3080/// pint = pshort; // warning: assignment from incompatible pointer type
3081/// a = pint; // warning: assignment makes integer from pointer without a cast
3082/// pint = a; // warning: assignment makes pointer from integer without a cast
3083/// pint = pfoo; // warning: assignment from incompatible pointer type
3084///
3085/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00003086/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00003087///
Chris Lattner005ed752008-01-04 18:04:52 +00003088Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003089Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00003090 // Get canonical types. We're not formatting these types, just comparing
3091 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003092 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3093 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00003094
3095 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00003096 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00003097
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003098 // If the left-hand side is a reference type, then we are in a
3099 // (rare!) case where we've allowed the use of references in C,
3100 // e.g., as a parameter type in a built-in function. In this case,
3101 // just make sure that the type referenced is compatible with the
3102 // right-hand side type. The caller is responsible for adjusting
3103 // lhsType so that the resulting expression does not have reference
3104 // type.
3105 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
3106 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00003107 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003108 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003109 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003110
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003111 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
3112 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003113 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00003114 // Relax integer conversions like we do for pointers below.
3115 if (rhsType->isIntegerType())
3116 return IntToPointer;
3117 if (lhsType->isIntegerType())
3118 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00003119 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003120 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003121
Nate Begemanc5f0f652008-07-14 18:02:46 +00003122 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00003123 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00003124 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
3125 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003126 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003127
Nate Begemanc5f0f652008-07-14 18:02:46 +00003128 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00003129 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00003130 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003131 if (getLangOptions().LaxVectorConversions &&
3132 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003133 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00003134 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003135 }
3136 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00003137 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003138
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003139 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00003140 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003141
Chris Lattner390564e2008-04-07 06:49:41 +00003142 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003143 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003144 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003145
Chris Lattner390564e2008-04-07 06:49:41 +00003146 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003147 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003148
Steve Naroffa982c712008-09-29 18:10:17 +00003149 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00003150 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003151 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00003152
3153 // Treat block pointers as objects.
3154 if (getLangOptions().ObjC1 &&
3155 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
3156 return Compatible;
3157 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003158 return Incompatible;
3159 }
3160
3161 if (isa<BlockPointerType>(lhsType)) {
3162 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00003163 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00003164
Steve Naroffa982c712008-09-29 18:10:17 +00003165 // Treat block pointers as objects.
3166 if (getLangOptions().ObjC1 &&
3167 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
3168 return Compatible;
3169
Steve Naroff3454b6c2008-09-04 15:10:53 +00003170 if (rhsType->isBlockPointerType())
3171 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003172
Steve Naroff3454b6c2008-09-04 15:10:53 +00003173 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
3174 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003175 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003176 }
Chris Lattner1853da22008-01-04 23:18:45 +00003177 return Incompatible;
3178 }
3179
Chris Lattner390564e2008-04-07 06:49:41 +00003180 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003181 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00003182 if (lhsType == Context.BoolTy)
3183 return Compatible;
3184
3185 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003186 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00003187
Mike Stump9afab102009-02-19 03:04:26 +00003188 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003189 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003190
3191 if (isa<BlockPointerType>(lhsType) &&
Steve Naroff3454b6c2008-09-04 15:10:53 +00003192 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003193 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003194 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003195 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003196
Chris Lattner1853da22008-01-04 23:18:45 +00003197 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00003198 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003199 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00003200 }
3201 return Incompatible;
3202}
3203
Douglas Gregor144b06c2009-04-29 22:16:16 +00003204/// \brief Constructs a transparent union from an expression that is
3205/// used to initialize the transparent union.
3206static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3207 QualType UnionType, FieldDecl *Field) {
3208 // Build an initializer list that designates the appropriate member
3209 // of the transparent union.
3210 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3211 &E, 1,
3212 SourceLocation());
3213 Initializer->setType(UnionType);
3214 Initializer->setInitializedFieldInUnion(Field);
3215
3216 // Build a compound literal constructing a value of the transparent
3217 // union type from this initializer list.
3218 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3219 false);
3220}
3221
3222Sema::AssignConvertType
3223Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3224 QualType FromType = rExpr->getType();
3225
3226 // If the ArgType is a Union type, we want to handle a potential
3227 // transparent_union GCC extension.
3228 const RecordType *UT = ArgType->getAsUnionType();
3229 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
3230 return Incompatible;
3231
3232 // The field to initialize within the transparent union.
3233 RecordDecl *UD = UT->getDecl();
3234 FieldDecl *InitField = 0;
3235 // It's compatible if the expression matches any of the fields.
3236 for (RecordDecl::field_iterator it = UD->field_begin(Context),
3237 itend = UD->field_end(Context);
3238 it != itend; ++it) {
3239 if (it->getType()->isPointerType()) {
3240 // If the transparent union contains a pointer type, we allow:
3241 // 1) void pointer
3242 // 2) null pointer constant
3243 if (FromType->isPointerType())
3244 if (FromType->getAsPointerType()->getPointeeType()->isVoidType()) {
3245 ImpCastExprToType(rExpr, it->getType());
3246 InitField = *it;
3247 break;
3248 }
3249
3250 if (rExpr->isNullPointerConstant(Context)) {
3251 ImpCastExprToType(rExpr, it->getType());
3252 InitField = *it;
3253 break;
3254 }
3255 }
3256
3257 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3258 == Compatible) {
3259 InitField = *it;
3260 break;
3261 }
3262 }
3263
3264 if (!InitField)
3265 return Incompatible;
3266
3267 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3268 return Compatible;
3269}
3270
Chris Lattner005ed752008-01-04 18:04:52 +00003271Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003272Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003273 if (getLangOptions().CPlusPlus) {
3274 if (!lhsType->isRecordType()) {
3275 // C++ 5.17p3: If the left operand is not of class type, the
3276 // expression is implicitly converted (C++ 4) to the
3277 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00003278 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3279 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003280 return Incompatible;
Chris Lattner79e9a422009-04-12 09:02:39 +00003281 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003282 }
3283
3284 // FIXME: Currently, we fall through and treat C++ classes like C
3285 // structures.
3286 }
3287
Steve Naroffcdee22d2007-11-27 17:58:44 +00003288 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3289 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00003290 if ((lhsType->isPointerType() ||
3291 lhsType->isObjCQualifiedIdType() ||
Mike Stump9afab102009-02-19 03:04:26 +00003292 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00003293 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003294 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00003295 return Compatible;
3296 }
Mike Stump9afab102009-02-19 03:04:26 +00003297
Chris Lattner5f505bf2007-10-16 02:55:40 +00003298 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00003299 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00003300 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00003301 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00003302 //
Mike Stump9afab102009-02-19 03:04:26 +00003303 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00003304 if (!lhsType->isReferenceType())
3305 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00003306
Chris Lattner005ed752008-01-04 18:04:52 +00003307 Sema::AssignConvertType result =
3308 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00003309
Steve Naroff0f32f432007-08-24 22:33:52 +00003310 // C99 6.5.16.1p2: The value of the right operand is converted to the
3311 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003312 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3313 // so that we can use references in built-in functions even in C.
3314 // The getNonReferenceType() call makes sure that the resulting expression
3315 // does not have reference type.
Douglas Gregor144b06c2009-04-29 22:16:16 +00003316 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003317 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00003318 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00003319}
3320
Chris Lattner005ed752008-01-04 18:04:52 +00003321Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003322Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
3323 return CheckAssignmentConstraints(lhsType, rhsType);
3324}
3325
Chris Lattner1eafdea2008-11-18 01:30:42 +00003326QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003327 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003328 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003329 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00003330 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003331}
3332
Mike Stump9afab102009-02-19 03:04:26 +00003333inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00003334 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00003335 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00003336 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003337 QualType lhsType =
3338 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3339 QualType rhsType =
3340 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00003341
Nate Begemanc5f0f652008-07-14 18:02:46 +00003342 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00003343 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00003344 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00003345
Nate Begemanc5f0f652008-07-14 18:02:46 +00003346 // Handle the case of a vector & extvector type of the same size and element
3347 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00003348 if (getLangOptions().LaxVectorConversions) {
3349 // FIXME: Should we warn here?
3350 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003351 if (const VectorType *RV = rhsType->getAsVectorType())
3352 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00003353 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003354 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00003355 }
3356 }
3357 }
Mike Stump9afab102009-02-19 03:04:26 +00003358
Nate Begemanc5f0f652008-07-14 18:02:46 +00003359 // If the lhs is an extended vector and the rhs is a scalar of the same type
3360 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00003361 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003362 QualType eltType = V->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00003363
3364 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00003365 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
3366 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003367 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00003368 return lhsType;
3369 }
3370 }
3371
Nate Begemanc5f0f652008-07-14 18:02:46 +00003372 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00003373 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00003374 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003375 QualType eltType = V->getElementType();
3376
Mike Stump9afab102009-02-19 03:04:26 +00003377 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00003378 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
3379 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003380 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00003381 return rhsType;
3382 }
3383 }
3384
Chris Lattner4b009652007-07-25 00:24:17 +00003385 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00003386 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003387 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003388 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003389 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00003390}
3391
Chris Lattner4b009652007-07-25 00:24:17 +00003392inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003393 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003394{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00003395 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003396 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003397
Steve Naroff8f708362007-08-24 19:07:16 +00003398 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003399
Chris Lattner4b009652007-07-25 00:24:17 +00003400 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00003401 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003402 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003403}
3404
3405inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003406 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003407{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00003408 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3409 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3410 return CheckVectorOperands(Loc, lex, rex);
3411 return InvalidOperands(Loc, lex, rex);
3412 }
Chris Lattner4b009652007-07-25 00:24:17 +00003413
Steve Naroff8f708362007-08-24 19:07:16 +00003414 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003415
Chris Lattner4b009652007-07-25 00:24:17 +00003416 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003417 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003418 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003419}
3420
3421inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Eli Friedman3cd92882009-03-28 01:22:36 +00003422 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
Chris Lattner4b009652007-07-25 00:24:17 +00003423{
Eli Friedman3cd92882009-03-28 01:22:36 +00003424 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3425 QualType compType = CheckVectorOperands(Loc, lex, rex);
3426 if (CompLHSTy) *CompLHSTy = compType;
3427 return compType;
3428 }
Chris Lattner4b009652007-07-25 00:24:17 +00003429
Eli Friedman3cd92882009-03-28 01:22:36 +00003430 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003431
Chris Lattner4b009652007-07-25 00:24:17 +00003432 // handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00003433 if (lex->getType()->isArithmeticType() &&
3434 rex->getType()->isArithmeticType()) {
3435 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00003436 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00003437 }
Chris Lattner4b009652007-07-25 00:24:17 +00003438
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003439 // Put any potential pointer into PExp
3440 Expr* PExp = lex, *IExp = rex;
3441 if (IExp->getType()->isPointerType())
3442 std::swap(PExp, IExp);
3443
Chris Lattner184f92d2009-04-24 23:50:08 +00003444 if (const PointerType *PTy = PExp->getType()->getAsPointerType()) {
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003445 if (IExp->getType()->isIntegerType()) {
Chris Lattner184f92d2009-04-24 23:50:08 +00003446 QualType PointeeTy = PTy->getPointeeType();
3447 // Check for arithmetic on pointers to incomplete types.
3448 if (PointeeTy->isVoidType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00003449 if (getLangOptions().CPlusPlus) {
3450 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner8ba580c2008-11-19 05:08:23 +00003451 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003452 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003453 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003454
3455 // GNU extension: arithmetic on pointer to void
3456 Diag(Loc, diag::ext_gnu_void_ptr)
3457 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner184f92d2009-04-24 23:50:08 +00003458 } else if (PointeeTy->isFunctionType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00003459 if (getLangOptions().CPlusPlus) {
3460 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3461 << lex->getType() << lex->getSourceRange();
3462 return QualType();
3463 }
3464
3465 // GNU extension: arithmetic on pointer to function
3466 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3467 << lex->getType() << lex->getSourceRange();
3468 } else if (!PTy->isDependentType() &&
Chris Lattner184f92d2009-04-24 23:50:08 +00003469 RequireCompleteType(Loc, PointeeTy,
Douglas Gregor05e28f62009-03-24 19:52:54 +00003470 diag::err_typecheck_arithmetic_incomplete_type,
Chris Lattner184f92d2009-04-24 23:50:08 +00003471 PExp->getSourceRange(), SourceRange(),
3472 PExp->getType()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00003473 return QualType();
3474
Chris Lattner184f92d2009-04-24 23:50:08 +00003475 // Diagnose bad cases where we step over interface counts.
3476 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
3477 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
3478 << PointeeTy << PExp->getSourceRange();
3479 return QualType();
3480 }
3481
Eli Friedman3cd92882009-03-28 01:22:36 +00003482 if (CompLHSTy) {
3483 QualType LHSTy = lex->getType();
3484 if (LHSTy->isPromotableIntegerType())
3485 LHSTy = Context.IntTy;
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00003486 else {
3487 QualType T = isPromotableBitField(lex, Context);
3488 if (!T.isNull())
3489 LHSTy = T;
3490 }
3491
Eli Friedman3cd92882009-03-28 01:22:36 +00003492 *CompLHSTy = LHSTy;
3493 }
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003494 return PExp->getType();
3495 }
3496 }
3497
Chris Lattner1eafdea2008-11-18 01:30:42 +00003498 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003499}
3500
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003501// C99 6.5.6
3502QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman3cd92882009-03-28 01:22:36 +00003503 SourceLocation Loc, QualType* CompLHSTy) {
3504 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3505 QualType compType = CheckVectorOperands(Loc, lex, rex);
3506 if (CompLHSTy) *CompLHSTy = compType;
3507 return compType;
3508 }
Mike Stump9afab102009-02-19 03:04:26 +00003509
Eli Friedman3cd92882009-03-28 01:22:36 +00003510 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump9afab102009-02-19 03:04:26 +00003511
Chris Lattnerf6da2912007-12-09 21:53:25 +00003512 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00003513
Chris Lattnerf6da2912007-12-09 21:53:25 +00003514 // Handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00003515 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) {
3516 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00003517 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00003518 }
Mike Stump9afab102009-02-19 03:04:26 +00003519
Chris Lattnerf6da2912007-12-09 21:53:25 +00003520 // Either ptr - int or ptr - ptr.
3521 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00003522 QualType lpointee = LHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003523
Douglas Gregor05e28f62009-03-24 19:52:54 +00003524 // The LHS must be an completely-defined object type.
Douglas Gregorb3193242009-01-23 00:36:41 +00003525
Douglas Gregor05e28f62009-03-24 19:52:54 +00003526 bool ComplainAboutVoid = false;
3527 Expr *ComplainAboutFunc = 0;
3528 if (lpointee->isVoidType()) {
3529 if (getLangOptions().CPlusPlus) {
3530 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3531 << lex->getSourceRange() << rex->getSourceRange();
3532 return QualType();
3533 }
3534
3535 // GNU C extension: arithmetic on pointer to void
3536 ComplainAboutVoid = true;
3537 } else if (lpointee->isFunctionType()) {
3538 if (getLangOptions().CPlusPlus) {
3539 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003540 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003541 return QualType();
3542 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003543
3544 // GNU C extension: arithmetic on pointer to function
3545 ComplainAboutFunc = lex;
3546 } else if (!lpointee->isDependentType() &&
3547 RequireCompleteType(Loc, lpointee,
3548 diag::err_typecheck_sub_ptr_object,
3549 lex->getSourceRange(),
3550 SourceRange(),
3551 lex->getType()))
3552 return QualType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003553
Chris Lattner184f92d2009-04-24 23:50:08 +00003554 // Diagnose bad cases where we step over interface counts.
3555 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
3556 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
3557 << lpointee << lex->getSourceRange();
3558 return QualType();
3559 }
3560
Chris Lattnerf6da2912007-12-09 21:53:25 +00003561 // The result type of a pointer-int computation is the pointer type.
Douglas Gregor05e28f62009-03-24 19:52:54 +00003562 if (rex->getType()->isIntegerType()) {
3563 if (ComplainAboutVoid)
3564 Diag(Loc, diag::ext_gnu_void_ptr)
3565 << lex->getSourceRange() << rex->getSourceRange();
3566 if (ComplainAboutFunc)
3567 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3568 << ComplainAboutFunc->getType()
3569 << ComplainAboutFunc->getSourceRange();
3570
Eli Friedman3cd92882009-03-28 01:22:36 +00003571 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003572 return lex->getType();
Douglas Gregor05e28f62009-03-24 19:52:54 +00003573 }
Mike Stump9afab102009-02-19 03:04:26 +00003574
Chris Lattnerf6da2912007-12-09 21:53:25 +00003575 // Handle pointer-pointer subtractions.
3576 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00003577 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003578
Douglas Gregor05e28f62009-03-24 19:52:54 +00003579 // RHS must be a completely-type object type.
3580 // Handle the GNU void* extension.
3581 if (rpointee->isVoidType()) {
3582 if (getLangOptions().CPlusPlus) {
3583 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3584 << lex->getSourceRange() << rex->getSourceRange();
3585 return QualType();
3586 }
Mike Stump9afab102009-02-19 03:04:26 +00003587
Douglas Gregor05e28f62009-03-24 19:52:54 +00003588 ComplainAboutVoid = true;
3589 } else if (rpointee->isFunctionType()) {
3590 if (getLangOptions().CPlusPlus) {
3591 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003592 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003593 return QualType();
3594 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003595
3596 // GNU extension: arithmetic on pointer to function
3597 if (!ComplainAboutFunc)
3598 ComplainAboutFunc = rex;
3599 } else if (!rpointee->isDependentType() &&
3600 RequireCompleteType(Loc, rpointee,
3601 diag::err_typecheck_sub_ptr_object,
3602 rex->getSourceRange(),
3603 SourceRange(),
3604 rex->getType()))
3605 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00003606
Chris Lattnerf6da2912007-12-09 21:53:25 +00003607 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00003608 if (!Context.typesAreCompatible(
Mike Stump9afab102009-02-19 03:04:26 +00003609 Context.getCanonicalType(lpointee).getUnqualifiedType(),
Eli Friedman583c31e2008-09-02 05:09:35 +00003610 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003611 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003612 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003613 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003614 return QualType();
3615 }
Mike Stump9afab102009-02-19 03:04:26 +00003616
Douglas Gregor05e28f62009-03-24 19:52:54 +00003617 if (ComplainAboutVoid)
3618 Diag(Loc, diag::ext_gnu_void_ptr)
3619 << lex->getSourceRange() << rex->getSourceRange();
3620 if (ComplainAboutFunc)
3621 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3622 << ComplainAboutFunc->getType()
3623 << ComplainAboutFunc->getSourceRange();
Eli Friedman3cd92882009-03-28 01:22:36 +00003624
3625 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003626 return Context.getPointerDiffType();
3627 }
3628 }
Mike Stump9afab102009-02-19 03:04:26 +00003629
Chris Lattner1eafdea2008-11-18 01:30:42 +00003630 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003631}
3632
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003633// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00003634QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003635 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00003636 // C99 6.5.7p2: Each of the operands shall have integer type.
3637 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003638 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003639
Chris Lattner2c8bff72007-12-12 05:47:28 +00003640 // Shifts don't perform usual arithmetic conversions, they just do integer
3641 // promotions on each operand. C99 6.5.7p3
Eli Friedman3cd92882009-03-28 01:22:36 +00003642 QualType LHSTy;
3643 if (lex->getType()->isPromotableIntegerType())
3644 LHSTy = Context.IntTy;
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00003645 else {
3646 LHSTy = isPromotableBitField(lex, Context);
3647 if (LHSTy.isNull())
3648 LHSTy = lex->getType();
3649 }
Chris Lattnerbb19bc42007-12-13 07:28:16 +00003650 if (!isCompAssign)
Eli Friedman3cd92882009-03-28 01:22:36 +00003651 ImpCastExprToType(lex, LHSTy);
3652
Chris Lattner2c8bff72007-12-12 05:47:28 +00003653 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003654
Chris Lattner2c8bff72007-12-12 05:47:28 +00003655 // "The type of the result is that of the promoted left operand."
Eli Friedman3cd92882009-03-28 01:22:36 +00003656 return LHSTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003657}
3658
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003659// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00003660QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor1f12c352009-04-06 18:45:53 +00003661 unsigned OpaqueOpc, bool isRelational) {
3662 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
3663
Nate Begemanc5f0f652008-07-14 18:02:46 +00003664 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003665 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00003666
Chris Lattner254f3bc2007-08-26 01:18:55 +00003667 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00003668 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3669 UsualArithmeticConversions(lex, rex);
3670 else {
3671 UsualUnaryConversions(lex);
3672 UsualUnaryConversions(rex);
3673 }
Chris Lattner4b009652007-07-25 00:24:17 +00003674 QualType lType = lex->getType();
3675 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003676
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003677 if (!lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00003678 // For non-floating point types, check for self-comparisons of the form
3679 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3680 // often indicate logic errors in the program.
Ted Kremenek264b5cb2009-03-20 19:57:37 +00003681 // NOTE: Don't warn about comparisons of enum constants. These can arise
3682 // from macro expansions, and are usually quite deliberate.
Chris Lattner4e479f92009-03-08 19:39:53 +00003683 Expr *LHSStripped = lex->IgnoreParens();
3684 Expr *RHSStripped = rex->IgnoreParens();
3685 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
3686 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekf042dc62009-03-20 18:35:45 +00003687 if (DRL->getDecl() == DRR->getDecl() &&
3688 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump9afab102009-02-19 03:04:26 +00003689 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner4e479f92009-03-08 19:39:53 +00003690
3691 if (isa<CastExpr>(LHSStripped))
3692 LHSStripped = LHSStripped->IgnoreParenCasts();
3693 if (isa<CastExpr>(RHSStripped))
3694 RHSStripped = RHSStripped->IgnoreParenCasts();
3695
3696 // Warn about comparisons against a string constant (unless the other
3697 // operand is null), the user probably wants strcmp.
Douglas Gregor1f12c352009-04-06 18:45:53 +00003698 Expr *literalString = 0;
3699 Expr *literalStringStripped = 0;
Chris Lattner4e479f92009-03-08 19:39:53 +00003700 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00003701 !RHSStripped->isNullPointerConstant(Context)) {
3702 literalString = lex;
3703 literalStringStripped = LHSStripped;
3704 }
Chris Lattner4e479f92009-03-08 19:39:53 +00003705 else if ((isa<StringLiteral>(RHSStripped) ||
3706 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00003707 !LHSStripped->isNullPointerConstant(Context)) {
3708 literalString = rex;
3709 literalStringStripped = RHSStripped;
3710 }
3711
3712 if (literalString) {
3713 std::string resultComparison;
3714 switch (Opc) {
3715 case BinaryOperator::LT: resultComparison = ") < 0"; break;
3716 case BinaryOperator::GT: resultComparison = ") > 0"; break;
3717 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
3718 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
3719 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
3720 case BinaryOperator::NE: resultComparison = ") != 0"; break;
3721 default: assert(false && "Invalid comparison operator");
3722 }
3723 Diag(Loc, diag::warn_stringcompare)
3724 << isa<ObjCEncodeExpr>(literalStringStripped)
3725 << literalString->getSourceRange()
Douglas Gregor3faaa812009-04-01 23:51:29 +00003726 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
3727 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
3728 "strcmp(")
3729 << CodeModificationHint::CreateInsertion(
3730 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor1f12c352009-04-06 18:45:53 +00003731 resultComparison);
3732 }
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003733 }
Mike Stump9afab102009-02-19 03:04:26 +00003734
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003735 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner4e479f92009-03-08 19:39:53 +00003736 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003737
Chris Lattner254f3bc2007-08-26 01:18:55 +00003738 if (isRelational) {
3739 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003740 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003741 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00003742 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00003743 if (lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00003744 assert(rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003745 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00003746 }
Mike Stump9afab102009-02-19 03:04:26 +00003747
Chris Lattner254f3bc2007-08-26 01:18:55 +00003748 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003749 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003750 }
Mike Stump9afab102009-02-19 03:04:26 +00003751
Chris Lattner22be8422007-08-26 01:10:14 +00003752 bool LHSIsNull = lex->isNullPointerConstant(Context);
3753 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00003754
Chris Lattner254f3bc2007-08-26 01:18:55 +00003755 // All of the following pointer related warnings are GCC extensions, except
3756 // when handling null pointer constants. One day, we can consider making them
3757 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00003758 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003759 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003760 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00003761 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003762 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00003763
Steve Naroff3b435622007-11-13 14:57:38 +00003764 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003765 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3766 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00003767 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00003768 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003769 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003770 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003771 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003772 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003773 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003774 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003775 // Handle block pointer types.
3776 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3777 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3778 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003779
Steve Naroff3454b6c2008-09-04 15:10:53 +00003780 if (!LHSIsNull && !RHSIsNull &&
3781 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003782 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003783 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003784 }
3785 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003786 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003787 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003788 // Allow block pointers to be compared with null pointer constants.
3789 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3790 (lType->isPointerType() && rType->isBlockPointerType())) {
3791 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003792 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003793 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003794 }
3795 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003796 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003797 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003798
Steve Naroff936c4362008-06-03 14:04:54 +00003799 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003800 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003801 const PointerType *LPT = lType->getAsPointerType();
3802 const PointerType *RPT = rType->getAsPointerType();
Mike Stump9afab102009-02-19 03:04:26 +00003803 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003804 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003805 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003806 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003807
Steve Naroff030fcda2008-11-17 19:49:16 +00003808 if (!LPtrToVoid && !RPtrToVoid &&
3809 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003810 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003811 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003812 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003813 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003814 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003815 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003816 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003817 }
Steve Naroff936c4362008-06-03 14:04:54 +00003818 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3819 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003820 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003821 } else {
3822 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003823 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003824 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003825 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003826 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003827 }
Steve Naroff936c4362008-06-03 14:04:54 +00003828 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003829 }
Mike Stump9afab102009-02-19 03:04:26 +00003830 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
Steve Naroff936c4362008-06-03 14:04:54 +00003831 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003832 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003833 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003834 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003835 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003836 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003837 }
Mike Stump9afab102009-02-19 03:04:26 +00003838 if (lType->isIntegerType() &&
Steve Naroff936c4362008-06-03 14:04:54 +00003839 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003840 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003841 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003842 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003843 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003844 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003845 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003846 // Handle block pointers.
3847 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3848 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003849 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003850 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003851 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003852 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003853 }
3854 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3855 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003856 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003857 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003858 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003859 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003860 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003861 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003862}
3863
Nate Begemanc5f0f652008-07-14 18:02:46 +00003864/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00003865/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003866/// like a scalar comparison, a vector comparison produces a vector of integer
3867/// types.
3868QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003869 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003870 bool isRelational) {
3871 // Check to make sure we're operating on vectors of the same type and width,
3872 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003873 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003874 if (vType.isNull())
3875 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00003876
Nate Begemanc5f0f652008-07-14 18:02:46 +00003877 QualType lType = lex->getType();
3878 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003879
Nate Begemanc5f0f652008-07-14 18:02:46 +00003880 // For non-floating point types, check for self-comparisons of the form
3881 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3882 // often indicate logic errors in the program.
3883 if (!lType->isFloatingType()) {
3884 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3885 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3886 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003887 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003888 }
Mike Stump9afab102009-02-19 03:04:26 +00003889
Nate Begemanc5f0f652008-07-14 18:02:46 +00003890 // Check for comparisons of floating point operands using != and ==.
3891 if (!isRelational && lType->isFloatingType()) {
3892 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003893 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003894 }
Mike Stump9afab102009-02-19 03:04:26 +00003895
Chris Lattner10687e32009-03-31 07:46:52 +00003896 // FIXME: Vector compare support in the LLVM backend is not fully reliable,
3897 // just reject all vector comparisons for now.
3898 if (1) {
3899 Diag(Loc, diag::err_typecheck_vector_comparison)
3900 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3901 return QualType();
3902 }
3903
Nate Begemanc5f0f652008-07-14 18:02:46 +00003904 // Return the type for the comparison, which is the same as vector type for
3905 // integer vectors, or an integer type of identical size and number of
3906 // elements for floating point vectors.
3907 if (lType->isIntegerType())
3908 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00003909
Nate Begemanc5f0f652008-07-14 18:02:46 +00003910 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003911 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003912 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003913 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner10687e32009-03-31 07:46:52 +00003914 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begemand6d2f772009-01-18 03:20:47 +00003915 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3916
Mike Stump9afab102009-02-19 03:04:26 +00003917 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00003918 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003919 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3920}
3921
Chris Lattner4b009652007-07-25 00:24:17 +00003922inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003923 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003924{
3925 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003926 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003927
Steve Naroff8f708362007-08-24 19:07:16 +00003928 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003929
Chris Lattner4b009652007-07-25 00:24:17 +00003930 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003931 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003932 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003933}
3934
3935inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00003936 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003937{
3938 UsualUnaryConversions(lex);
3939 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003940
Eli Friedmanbea3f842008-05-13 20:16:47 +00003941 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003942 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003943 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003944}
3945
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003946/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3947/// is a read-only property; return true if so. A readonly property expression
3948/// depends on various declarations and thus must be treated specially.
3949///
Mike Stump9afab102009-02-19 03:04:26 +00003950static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003951{
3952 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3953 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3954 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3955 QualType BaseType = PropExpr->getBase()->getType();
3956 if (const PointerType *PTy = BaseType->getAsPointerType())
Mike Stump9afab102009-02-19 03:04:26 +00003957 if (const ObjCInterfaceType *IFTy =
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003958 PTy->getPointeeType()->getAsObjCInterfaceType())
3959 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3960 if (S.isPropertyReadonly(PDecl, IFace))
3961 return true;
3962 }
3963 }
3964 return false;
3965}
3966
Chris Lattner4c2642c2008-11-18 01:22:49 +00003967/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3968/// emit an error and return true. If so, return false.
3969static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00003970 SourceLocation OrigLoc = Loc;
3971 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
3972 &Loc);
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003973 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3974 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003975 if (IsLV == Expr::MLV_Valid)
3976 return false;
Mike Stump9afab102009-02-19 03:04:26 +00003977
Chris Lattner4c2642c2008-11-18 01:22:49 +00003978 unsigned Diag = 0;
3979 bool NeedType = false;
3980 switch (IsLV) { // C99 6.5.16p2
3981 default: assert(0 && "Unknown result from isModifiableLvalue!");
3982 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00003983 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003984 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3985 NeedType = true;
3986 break;
Mike Stump9afab102009-02-19 03:04:26 +00003987 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003988 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3989 NeedType = true;
3990 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003991 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003992 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3993 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003994 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003995 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3996 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003997 case Expr::MLV_IncompleteType:
3998 case Expr::MLV_IncompleteVoidType:
Douglas Gregorc84d8932009-03-09 16:13:40 +00003999 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004000 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
4001 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00004002 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004003 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4004 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00004005 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004006 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4007 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00004008 case Expr::MLV_ReadonlyProperty:
4009 Diag = diag::error_readonly_property_assignment;
4010 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00004011 case Expr::MLV_NoSetterProperty:
4012 Diag = diag::error_nosetter_property_assignment;
4013 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004014 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00004015
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004016 SourceRange Assign;
4017 if (Loc != OrigLoc)
4018 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner4c2642c2008-11-18 01:22:49 +00004019 if (NeedType)
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004020 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004021 else
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004022 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004023 return true;
4024}
4025
4026
4027
4028// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00004029QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4030 SourceLocation Loc,
4031 QualType CompoundType) {
4032 // Verify that LHS is a modifiable lvalue, and emit error if not.
4033 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00004034 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00004035
4036 QualType LHSType = LHS->getType();
4037 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00004038
Chris Lattner005ed752008-01-04 18:04:52 +00004039 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004040 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00004041 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004042 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004043 // Special case of NSObject attributes on c-style pointer types.
4044 if (ConvTy == IncompatiblePointer &&
4045 ((Context.isObjCNSObjectType(LHSType) &&
4046 Context.isObjCObjectPointerType(RHSType)) ||
4047 (Context.isObjCNSObjectType(RHSType) &&
4048 Context.isObjCObjectPointerType(LHSType))))
4049 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00004050
Chris Lattner34c85082008-08-21 18:04:13 +00004051 // If the RHS is a unary plus or minus, check to see if they = and + are
4052 // right next to each other. If so, the user may have typo'd "x =+ 4"
4053 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004054 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00004055 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4056 RHSCheck = ICE->getSubExpr();
4057 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4058 if ((UO->getOpcode() == UnaryOperator::Plus ||
4059 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00004060 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00004061 // Only if the two operators are exactly adjacent.
Chris Lattner55a17242009-03-08 06:51:10 +00004062 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4063 // And there is a space or other character before the subexpr of the
4064 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnerf1e5d4a2009-03-09 07:11:10 +00004065 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4066 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004067 Diag(Loc, diag::warn_not_compound_assign)
4068 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4069 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner55a17242009-03-08 06:51:10 +00004070 }
Chris Lattner34c85082008-08-21 18:04:13 +00004071 }
4072 } else {
4073 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00004074 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00004075 }
Chris Lattner005ed752008-01-04 18:04:52 +00004076
Chris Lattner1eafdea2008-11-18 01:30:42 +00004077 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4078 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00004079 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004080
Chris Lattner4b009652007-07-25 00:24:17 +00004081 // C99 6.5.16p3: The type of an assignment expression is the type of the
4082 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00004083 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00004084 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4085 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004086 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004087 // operand.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004088 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00004089}
4090
Chris Lattner1eafdea2008-11-18 01:30:42 +00004091// C99 6.5.17
4092QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00004093 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004094 DefaultFunctionArrayConversion(RHS);
Eli Friedman2b128322009-03-23 00:24:07 +00004095
4096 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4097 // incomplete in C++).
4098
Chris Lattner1eafdea2008-11-18 01:30:42 +00004099 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00004100}
4101
4102/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4103/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004104QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4105 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004106 if (Op->isTypeDependent())
4107 return Context.DependentTy;
4108
Chris Lattnere65182c2008-11-21 07:05:48 +00004109 QualType ResType = Op->getType();
4110 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004111
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004112 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4113 // Decrement of bool is not allowed.
4114 if (!isInc) {
4115 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4116 return QualType();
4117 }
4118 // Increment of bool sets it to true, but is deprecated.
4119 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4120 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00004121 // OK!
4122 } else if (const PointerType *PT = ResType->getAsPointerType()) {
4123 // C99 6.5.2.4p2, 6.5.6p2
Douglas Gregorcde3a2d2009-03-24 20:13:58 +00004124 if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004125 if (getLangOptions().CPlusPlus) {
4126 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4127 << Op->getSourceRange();
4128 return QualType();
4129 }
4130
4131 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00004132 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004133 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004134 if (getLangOptions().CPlusPlus) {
4135 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4136 << Op->getType() << Op->getSourceRange();
4137 return QualType();
4138 }
4139
4140 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004141 << ResType << Op->getSourceRange();
Douglas Gregorcde3a2d2009-03-24 20:13:58 +00004142 } else if (RequireCompleteType(OpLoc, PT->getPointeeType(),
4143 diag::err_typecheck_arithmetic_incomplete_type,
4144 Op->getSourceRange(), SourceRange(),
4145 ResType))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004146 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00004147 } else if (ResType->isComplexType()) {
4148 // C99 does not support ++/-- on complex types, we allow as an extension.
4149 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004150 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004151 } else {
4152 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004153 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004154 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00004155 }
Mike Stump9afab102009-02-19 03:04:26 +00004156 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00004157 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00004158 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00004159 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00004160 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00004161}
4162
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004163/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00004164/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004165/// where the declaration is needed for type checking. We only need to
4166/// handle cases when the expression references a function designator
4167/// or is an lvalue. Here are some examples:
4168/// - &(x) => x
4169/// - &*****f => f for f a function designator.
4170/// - &s.xx => s
4171/// - &s.zz[1].yy -> s, if zz is an array
4172/// - *(x + 1) -> x, if x is an array
4173/// - &"123"[2] -> 0
4174/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00004175static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00004176 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00004177 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00004178 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004179 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00004180 case Stmt::MemberExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004181 // If this is an arrow operator, the address is an offset from
4182 // the base's value, so the object the base refers to is
4183 // irrelevant.
Chris Lattner48d7f382008-04-02 04:24:33 +00004184 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00004185 return 0;
Eli Friedman93ecce22009-04-20 08:23:18 +00004186 // Otherwise, the expression refers to a part of the base
Chris Lattner48d7f382008-04-02 04:24:33 +00004187 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004188 case Stmt::ArraySubscriptExprClass: {
Eli Friedman93ecce22009-04-20 08:23:18 +00004189 // FIXME: This code shouldn't be necessary! We should catch the
4190 // implicit promotion of register arrays earlier.
4191 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4192 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4193 if (ICE->getSubExpr()->getType()->isArrayType())
4194 return getPrimaryDecl(ICE->getSubExpr());
4195 }
4196 return 0;
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004197 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004198 case Stmt::UnaryOperatorClass: {
4199 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00004200
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004201 switch(UO->getOpcode()) {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004202 case UnaryOperator::Real:
4203 case UnaryOperator::Imag:
4204 case UnaryOperator::Extension:
4205 return getPrimaryDecl(UO->getSubExpr());
4206 default:
4207 return 0;
4208 }
4209 }
Chris Lattner4b009652007-07-25 00:24:17 +00004210 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004211 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00004212 case Stmt::ImplicitCastExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004213 // If the result of an implicit cast is an l-value, we care about
4214 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner48d7f382008-04-02 04:24:33 +00004215 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00004216 default:
4217 return 0;
4218 }
4219}
4220
4221/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00004222/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00004223/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00004224/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00004225/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00004226/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00004227/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00004228QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman93ecce22009-04-20 08:23:18 +00004229 // Make sure to ignore parentheses in subsequent checks
4230 op = op->IgnoreParens();
4231
Douglas Gregore6be68a2008-12-17 22:52:20 +00004232 if (op->isTypeDependent())
4233 return Context.DependentTy;
4234
Steve Naroff9c6c3592008-01-13 17:10:08 +00004235 if (getLangOptions().C99) {
4236 // Implement C99-only parts of addressof rules.
4237 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
4238 if (uOp->getOpcode() == UnaryOperator::Deref)
4239 // Per C99 6.5.3.2, the address of a deref always returns a valid result
4240 // (assuming the deref expression is valid).
4241 return uOp->getSubExpr()->getType();
4242 }
4243 // Technically, there should be a check for array subscript
4244 // expressions here, but the result of one is always an lvalue anyway.
4245 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00004246 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00004247 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00004248
Chris Lattner4b009652007-07-25 00:24:17 +00004249 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004250 // The operand must be either an l-value or a function designator
Eli Friedmane730abe2009-04-28 17:59:09 +00004251 if (!op->getType()->isFunctionType()) {
Chris Lattnera3249072007-11-16 17:46:48 +00004252 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00004253 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
4254 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004255 return QualType();
4256 }
Eli Friedman93ecce22009-04-20 08:23:18 +00004257 } else if (op->isBitField()) { // C99 6.5.3.2p1
4258 // The operand cannot be a bit-field
4259 Diag(OpLoc, diag::err_typecheck_address_of)
4260 << "bit-field" << op->getSourceRange();
Douglas Gregor82d44772008-12-20 23:49:58 +00004261 return QualType();
Nate Begemana9187ab2009-02-15 22:45:20 +00004262 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
4263 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman93ecce22009-04-20 08:23:18 +00004264 // The operand cannot be an element of a vector
Chris Lattner77d52da2008-11-20 06:06:08 +00004265 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00004266 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004267 return QualType();
4268 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00004269 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00004270 // with the register storage-class specifier.
4271 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
4272 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004273 Diag(OpLoc, diag::err_typecheck_address_of)
4274 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004275 return QualType();
4276 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00004277 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00004278 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00004279 } else if (isa<FieldDecl>(dcl)) {
4280 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00004281 // Could be a pointer to member, though, if there is an explicit
4282 // scope qualifier for the class.
4283 if (isa<QualifiedDeclRefExpr>(op)) {
4284 DeclContext *Ctx = dcl->getDeclContext();
4285 if (Ctx && Ctx->isRecord())
4286 return Context.getMemberPointerType(op->getType(),
4287 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
4288 }
Nuno Lopesdf239522008-12-16 22:58:26 +00004289 } else if (isa<FunctionDecl>(dcl)) {
4290 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00004291 // As above.
4292 if (isa<QualifiedDeclRefExpr>(op)) {
4293 DeclContext *Ctx = dcl->getDeclContext();
4294 if (Ctx && Ctx->isRecord())
4295 return Context.getMemberPointerType(op->getType(),
4296 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
4297 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00004298 }
Nuno Lopesdf239522008-12-16 22:58:26 +00004299 else
Chris Lattner4b009652007-07-25 00:24:17 +00004300 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00004301 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00004302
Chris Lattner4b009652007-07-25 00:24:17 +00004303 // If the operand has type "type", the result has type "pointer to type".
4304 return Context.getPointerType(op->getType());
4305}
4306
Chris Lattnerda5c0872008-11-23 09:13:29 +00004307QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004308 if (Op->isTypeDependent())
4309 return Context.DependentTy;
4310
Chris Lattnerda5c0872008-11-23 09:13:29 +00004311 UsualUnaryConversions(Op);
4312 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004313
Chris Lattnerda5c0872008-11-23 09:13:29 +00004314 // Note that per both C89 and C99, this is always legal, even if ptype is an
4315 // incomplete type or void. It would be possible to warn about dereferencing
4316 // a void pointer, but it's completely well-defined, and such a warning is
4317 // unlikely to catch any mistakes.
4318 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00004319 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004320
Chris Lattner77d52da2008-11-20 06:06:08 +00004321 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00004322 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004323 return QualType();
4324}
4325
4326static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
4327 tok::TokenKind Kind) {
4328 BinaryOperator::Opcode Opc;
4329 switch (Kind) {
4330 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00004331 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
4332 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00004333 case tok::star: Opc = BinaryOperator::Mul; break;
4334 case tok::slash: Opc = BinaryOperator::Div; break;
4335 case tok::percent: Opc = BinaryOperator::Rem; break;
4336 case tok::plus: Opc = BinaryOperator::Add; break;
4337 case tok::minus: Opc = BinaryOperator::Sub; break;
4338 case tok::lessless: Opc = BinaryOperator::Shl; break;
4339 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
4340 case tok::lessequal: Opc = BinaryOperator::LE; break;
4341 case tok::less: Opc = BinaryOperator::LT; break;
4342 case tok::greaterequal: Opc = BinaryOperator::GE; break;
4343 case tok::greater: Opc = BinaryOperator::GT; break;
4344 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
4345 case tok::equalequal: Opc = BinaryOperator::EQ; break;
4346 case tok::amp: Opc = BinaryOperator::And; break;
4347 case tok::caret: Opc = BinaryOperator::Xor; break;
4348 case tok::pipe: Opc = BinaryOperator::Or; break;
4349 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
4350 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
4351 case tok::equal: Opc = BinaryOperator::Assign; break;
4352 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
4353 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
4354 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
4355 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
4356 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
4357 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
4358 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
4359 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
4360 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
4361 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
4362 case tok::comma: Opc = BinaryOperator::Comma; break;
4363 }
4364 return Opc;
4365}
4366
4367static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
4368 tok::TokenKind Kind) {
4369 UnaryOperator::Opcode Opc;
4370 switch (Kind) {
4371 default: assert(0 && "Unknown unary op!");
4372 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
4373 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
4374 case tok::amp: Opc = UnaryOperator::AddrOf; break;
4375 case tok::star: Opc = UnaryOperator::Deref; break;
4376 case tok::plus: Opc = UnaryOperator::Plus; break;
4377 case tok::minus: Opc = UnaryOperator::Minus; break;
4378 case tok::tilde: Opc = UnaryOperator::Not; break;
4379 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00004380 case tok::kw___real: Opc = UnaryOperator::Real; break;
4381 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
4382 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
4383 }
4384 return Opc;
4385}
4386
Douglas Gregord7f915e2008-11-06 23:29:22 +00004387/// CreateBuiltinBinOp - Creates a new built-in binary operation with
4388/// operator @p Opc at location @c TokLoc. This routine only supports
4389/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004390Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
4391 unsigned Op,
4392 Expr *lhs, Expr *rhs) {
Eli Friedman3cd92882009-03-28 01:22:36 +00004393 QualType ResultTy; // Result type of the binary operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00004394 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman3cd92882009-03-28 01:22:36 +00004395 // The following two variables are used for compound assignment operators
4396 QualType CompLHSTy; // Type of LHS after promotions for computation
4397 QualType CompResultTy; // Type of computation result
Douglas Gregord7f915e2008-11-06 23:29:22 +00004398
4399 switch (Opc) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00004400 case BinaryOperator::Assign:
4401 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
4402 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00004403 case BinaryOperator::PtrMemD:
4404 case BinaryOperator::PtrMemI:
4405 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
4406 Opc == BinaryOperator::PtrMemI);
4407 break;
4408 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00004409 case BinaryOperator::Div:
4410 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
4411 break;
4412 case BinaryOperator::Rem:
4413 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
4414 break;
4415 case BinaryOperator::Add:
4416 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
4417 break;
4418 case BinaryOperator::Sub:
4419 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
4420 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00004421 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00004422 case BinaryOperator::Shr:
4423 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
4424 break;
4425 case BinaryOperator::LE:
4426 case BinaryOperator::LT:
4427 case BinaryOperator::GE:
4428 case BinaryOperator::GT:
Douglas Gregor1f12c352009-04-06 18:45:53 +00004429 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004430 break;
4431 case BinaryOperator::EQ:
4432 case BinaryOperator::NE:
Douglas Gregor1f12c352009-04-06 18:45:53 +00004433 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004434 break;
4435 case BinaryOperator::And:
4436 case BinaryOperator::Xor:
4437 case BinaryOperator::Or:
4438 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
4439 break;
4440 case BinaryOperator::LAnd:
4441 case BinaryOperator::LOr:
4442 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
4443 break;
4444 case BinaryOperator::MulAssign:
4445 case BinaryOperator::DivAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004446 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
4447 CompLHSTy = CompResultTy;
4448 if (!CompResultTy.isNull())
4449 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004450 break;
4451 case BinaryOperator::RemAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004452 CompResultTy = CheckRemainderOperands(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::AddAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004458 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
4459 if (!CompResultTy.isNull())
4460 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004461 break;
4462 case BinaryOperator::SubAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004463 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
4464 if (!CompResultTy.isNull())
4465 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004466 break;
4467 case BinaryOperator::ShlAssign:
4468 case BinaryOperator::ShrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004469 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
4470 CompLHSTy = CompResultTy;
4471 if (!CompResultTy.isNull())
4472 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004473 break;
4474 case BinaryOperator::AndAssign:
4475 case BinaryOperator::XorAssign:
4476 case BinaryOperator::OrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004477 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
4478 CompLHSTy = CompResultTy;
4479 if (!CompResultTy.isNull())
4480 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004481 break;
4482 case BinaryOperator::Comma:
4483 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
4484 break;
4485 }
4486 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004487 return ExprError();
Eli Friedman3cd92882009-03-28 01:22:36 +00004488 if (CompResultTy.isNull())
Steve Naroff774e4152009-01-21 00:14:39 +00004489 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
4490 else
4491 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman3cd92882009-03-28 01:22:36 +00004492 CompLHSTy, CompResultTy,
4493 OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00004494}
4495
Chris Lattner4b009652007-07-25 00:24:17 +00004496// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004497Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
4498 tok::TokenKind Kind,
4499 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00004500 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00004501 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Chris Lattner4b009652007-07-25 00:24:17 +00004502
Steve Naroff87d58b42007-09-16 03:34:24 +00004503 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
4504 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004505
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004506 if (getLangOptions().CPlusPlus &&
4507 (lhs->getType()->isOverloadableType() ||
4508 rhs->getType()->isOverloadableType())) {
4509 // Find all of the overloaded operators visible from this
4510 // point. We perform both an operator-name lookup from the local
4511 // scope and an argument-dependent lookup based on the types of
4512 // the arguments.
Douglas Gregor3fc092f2009-03-13 00:33:25 +00004513 FunctionSet Functions;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004514 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
4515 if (OverOp != OO_None) {
4516 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
4517 Functions);
4518 Expr *Args[2] = { lhs, rhs };
4519 DeclarationName OpName
4520 = Context.DeclarationNames.getCXXOperatorName(OverOp);
4521 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregor70d26122008-11-12 17:17:38 +00004522 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004523
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004524 // Build the (potentially-overloaded, potentially-dependent)
4525 // binary operation.
4526 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004527 }
4528
Douglas Gregord7f915e2008-11-06 23:29:22 +00004529 // Build a built-in binary operation.
4530 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00004531}
4532
Douglas Gregorc78182d2009-03-13 23:49:33 +00004533Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
4534 unsigned OpcIn,
4535 ExprArg InputArg) {
4536 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004537
Douglas Gregorc78182d2009-03-13 23:49:33 +00004538 // FIXME: Input is modified below, but InputArg is not updated
4539 // appropriately.
4540 Expr *Input = (Expr *)InputArg.get();
Chris Lattner4b009652007-07-25 00:24:17 +00004541 QualType resultType;
4542 switch (Opc) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00004543 case UnaryOperator::PostInc:
4544 case UnaryOperator::PostDec:
4545 case UnaryOperator::OffsetOf:
4546 assert(false && "Invalid unary operator");
4547 break;
4548
Chris Lattner4b009652007-07-25 00:24:17 +00004549 case UnaryOperator::PreInc:
4550 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004551 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4552 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00004553 break;
Mike Stump9afab102009-02-19 03:04:26 +00004554 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00004555 resultType = CheckAddressOfOperand(Input, OpLoc);
4556 break;
Mike Stump9afab102009-02-19 03:04:26 +00004557 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00004558 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00004559 resultType = CheckIndirectionOperand(Input, OpLoc);
4560 break;
4561 case UnaryOperator::Plus:
4562 case UnaryOperator::Minus:
4563 UsualUnaryConversions(Input);
4564 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004565 if (resultType->isDependentType())
4566 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004567 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4568 break;
4569 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4570 resultType->isEnumeralType())
4571 break;
4572 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4573 Opc == UnaryOperator::Plus &&
4574 resultType->isPointerType())
4575 break;
4576
Sebastian Redl8b769972009-01-19 00:08:26 +00004577 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4578 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004579 case UnaryOperator::Not: // bitwise complement
4580 UsualUnaryConversions(Input);
4581 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004582 if (resultType->isDependentType())
4583 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00004584 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4585 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4586 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00004587 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004588 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004589 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00004590 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4591 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004592 break;
4593 case UnaryOperator::LNot: // logical negation
4594 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4595 DefaultFunctionArrayConversion(Input);
4596 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004597 if (resultType->isDependentType())
4598 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004599 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004600 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4601 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004602 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004603 // In C++, it's bool. C++ 5.3.1p8
4604 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004605 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004606 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004607 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00004608 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00004609 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004610 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004611 resultType = Input->getType();
4612 break;
4613 }
4614 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004615 return ExprError();
Douglas Gregorc78182d2009-03-13 23:49:33 +00004616
4617 InputArg.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004618 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004619}
4620
Douglas Gregorc78182d2009-03-13 23:49:33 +00004621// Unary Operators. 'Tok' is the token for the operator.
4622Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4623 tok::TokenKind Op, ExprArg input) {
4624 Expr *Input = (Expr*)input.get();
4625 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
4626
4627 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
4628 // Find all of the overloaded operators visible from this
4629 // point. We perform both an operator-name lookup from the local
4630 // scope and an argument-dependent lookup based on the types of
4631 // the arguments.
4632 FunctionSet Functions;
4633 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
4634 if (OverOp != OO_None) {
4635 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
4636 Functions);
4637 DeclarationName OpName
4638 = Context.DeclarationNames.getCXXOperatorName(OverOp);
4639 ArgumentDependentLookup(OpName, &Input, 1, Functions);
4640 }
4641
4642 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
4643 }
4644
4645 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
4646}
4647
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004648/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004649Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
4650 SourceLocation LabLoc,
4651 IdentifierInfo *LabelII) {
Chris Lattner4b009652007-07-25 00:24:17 +00004652 // Look up the record for this label identifier.
Chris Lattner2616d8c2009-04-18 20:01:55 +00004653 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00004654
Daniel Dunbar879788d2008-08-04 16:51:22 +00004655 // If we haven't seen this label yet, create a forward reference. It
4656 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffb88d81c2009-03-13 15:38:40 +00004657 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004658 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004659
Chris Lattner4b009652007-07-25 00:24:17 +00004660 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004661 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4662 Context.getPointerType(Context.VoidTy)));
Chris Lattner4b009652007-07-25 00:24:17 +00004663}
4664
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004665Sema::OwningExprResult
4666Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
4667 SourceLocation RPLoc) { // "({..})"
4668 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner4b009652007-07-25 00:24:17 +00004669 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4670 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4671
Eli Friedmanbc941e12009-01-24 23:09:00 +00004672 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattneraa257592009-04-25 19:11:05 +00004673 if (isFileScope)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004674 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmanbc941e12009-01-24 23:09:00 +00004675
Chris Lattner4b009652007-07-25 00:24:17 +00004676 // FIXME: there are a variety of strange constraints to enforce here, for
4677 // example, it is not possible to goto into a stmt expression apparently.
4678 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00004679
Chris Lattner4b009652007-07-25 00:24:17 +00004680 // If there are sub stmts in the compound stmt, take the type of the last one
4681 // as the type of the stmtexpr.
4682 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00004683
Chris Lattner200964f2008-07-26 19:51:01 +00004684 if (!Compound->body_empty()) {
4685 Stmt *LastStmt = Compound->body_back();
4686 // If LastStmt is a label, skip down through into the body.
4687 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4688 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00004689
Chris Lattner200964f2008-07-26 19:51:01 +00004690 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004691 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004692 }
Mike Stump9afab102009-02-19 03:04:26 +00004693
Eli Friedman2b128322009-03-23 00:24:07 +00004694 // FIXME: Check that expression type is complete/non-abstract; statement
4695 // expressions are not lvalues.
4696
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004697 substmt.release();
4698 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004699}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004700
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004701Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4702 SourceLocation BuiltinLoc,
4703 SourceLocation TypeLoc,
4704 TypeTy *argty,
4705 OffsetOfComponent *CompPtr,
4706 unsigned NumComponents,
4707 SourceLocation RPLoc) {
4708 // FIXME: This function leaks all expressions in the offset components on
4709 // error.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004710 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4711 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00004712
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004713 bool Dependent = ArgTy->isDependentType();
4714
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004715 // We must have at least one component that refers to the type, and the first
4716 // one is known to be a field designator. Verify that the ArgTy represents
4717 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004718 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004719 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump9afab102009-02-19 03:04:26 +00004720
Eli Friedman2b128322009-03-23 00:24:07 +00004721 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
4722 // with an incomplete type would be illegal.
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00004723
Eli Friedman342d9432009-02-27 06:44:11 +00004724 // Otherwise, create a null pointer as the base, and iteratively process
4725 // the offsetof designators.
4726 QualType ArgTyPtr = Context.getPointerType(ArgTy);
4727 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004728 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman342d9432009-02-27 06:44:11 +00004729 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004730
Chris Lattnerb37522e2007-08-31 21:49:13 +00004731 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4732 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00004733 // FIXME: This diagnostic isn't actually visible because the location is in
4734 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00004735 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004736 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4737 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00004738
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004739 if (!Dependent) {
4740 // FIXME: Dependent case loses a lot of information here. And probably
4741 // leaks like a sieve.
4742 for (unsigned i = 0; i != NumComponents; ++i) {
4743 const OffsetOfComponent &OC = CompPtr[i];
4744 if (OC.isBrackets) {
4745 // Offset of an array sub-field. TODO: Should we allow vector elements?
4746 const ArrayType *AT = Context.getAsArrayType(Res->getType());
4747 if (!AT) {
4748 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004749 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
4750 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004751 }
4752
4753 // FIXME: C++: Verify that operator[] isn't overloaded.
4754
Eli Friedman342d9432009-02-27 06:44:11 +00004755 // Promote the array so it looks more like a normal array subscript
4756 // expression.
4757 DefaultFunctionArrayConversion(Res);
4758
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004759 // C99 6.5.2.1p1
4760 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004761 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004762 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004763 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner7264d212009-04-25 22:50:55 +00004764 diag::err_typecheck_subscript_not_integer)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004765 << Idx->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004766
4767 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4768 OC.LocEnd);
4769 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004770 }
Mike Stump9afab102009-02-19 03:04:26 +00004771
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004772 const RecordType *RC = Res->getType()->getAsRecordType();
4773 if (!RC) {
4774 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004775 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
4776 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004777 }
Chris Lattner2af6a802007-08-30 17:59:59 +00004778
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004779 // Get the decl corresponding to this.
4780 RecordDecl *RD = RC->getDecl();
Anders Carlsson356946e2009-05-01 23:20:30 +00004781 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
4782 if (!CRD->isPOD())
4783 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_non_pod_type)
4784 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
4785 << Res->getType());
4786 }
4787
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004788 FieldDecl *MemberDecl
4789 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4790 LookupMemberName)
4791 .getAsDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004792 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004793 if (!MemberDecl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004794 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
4795 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump9afab102009-02-19 03:04:26 +00004796
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004797 // FIXME: C++: Verify that MemberDecl isn't a static field.
4798 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman35719da2009-04-26 20:50:44 +00004799 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonc154a722009-05-01 19:30:39 +00004800 Res = BuildAnonymousStructUnionMemberReference(
4801 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedman35719da2009-04-26 20:50:44 +00004802 } else {
4803 // MemberDecl->getType() doesn't get the right qualifiers, but it
4804 // doesn't matter here.
4805 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4806 MemberDecl->getType().getNonReferenceType());
4807 }
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004808 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004809 }
Mike Stump9afab102009-02-19 03:04:26 +00004810
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004811 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4812 Context.getSizeType(), BuiltinLoc));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004813}
4814
4815
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004816Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
4817 TypeTy *arg1,TypeTy *arg2,
4818 SourceLocation RPLoc) {
Steve Naroff63bad2d2007-08-01 22:05:33 +00004819 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4820 QualType argT2 = QualType::getFromOpaquePtr(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00004821
Steve Naroff63bad2d2007-08-01 22:05:33 +00004822 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00004823
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004824 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
4825 argT1, argT2, RPLoc));
Steve Naroff63bad2d2007-08-01 22:05:33 +00004826}
4827
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004828Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
4829 ExprArg cond,
4830 ExprArg expr1, ExprArg expr2,
4831 SourceLocation RPLoc) {
4832 Expr *CondExpr = static_cast<Expr*>(cond.get());
4833 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
4834 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump9afab102009-02-19 03:04:26 +00004835
Steve Naroff93c53012007-08-03 21:21:27 +00004836 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4837
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004838 QualType resType;
4839 if (CondExpr->isValueDependent()) {
4840 resType = Context.DependentTy;
4841 } else {
4842 // The conditional expression is required to be a constant expression.
4843 llvm::APSInt condEval(32);
4844 SourceLocation ExpLoc;
4845 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004846 return ExprError(Diag(ExpLoc,
4847 diag::err_typecheck_choose_expr_requires_constant)
4848 << CondExpr->getSourceRange());
Steve Naroff93c53012007-08-03 21:21:27 +00004849
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004850 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4851 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
4852 }
4853
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004854 cond.release(); expr1.release(); expr2.release();
4855 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4856 resType, RPLoc));
Steve Naroff93c53012007-08-03 21:21:27 +00004857}
4858
Steve Naroff52a81c02008-09-03 18:15:37 +00004859//===----------------------------------------------------------------------===//
4860// Clang Extensions.
4861//===----------------------------------------------------------------------===//
4862
4863/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004864void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004865 // Analyze block parameters.
4866 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00004867
Steve Naroff52a81c02008-09-03 18:15:37 +00004868 // Add BSI to CurBlock.
4869 BSI->PrevBlockInfo = CurBlock;
4870 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00004871
Steve Naroff52a81c02008-09-03 18:15:37 +00004872 BSI->ReturnType = 0;
4873 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00004874 BSI->hasBlockDeclRefExprs = false;
Chris Lattnere7765e12009-04-19 05:28:12 +00004875 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
4876 CurFunctionNeedsScopeChecking = false;
Mike Stump9afab102009-02-19 03:04:26 +00004877
Steve Naroff52059382008-10-10 01:28:17 +00004878 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004879 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004880}
4881
Mike Stumpc1fddff2009-02-04 22:31:32 +00004882void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4883 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4884
Mike Stump9e439c92009-04-29 21:40:37 +00004885 ProcessDeclAttributes(CurBlock->TheDecl, ParamInfo);
4886
Mike Stumpc1fddff2009-02-04 22:31:32 +00004887 if (ParamInfo.getNumTypeObjects() == 0
4888 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4889 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4890
Mike Stump458287d2009-04-28 01:10:27 +00004891 if (T->isArrayType()) {
4892 Diag(ParamInfo.getSourceRange().getBegin(),
4893 diag::err_block_returns_array);
4894 return;
4895 }
4896
Mike Stumpc1fddff2009-02-04 22:31:32 +00004897 // The parameter list is optional, if there was none, assume ().
4898 if (!T->isFunctionType())
4899 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4900
4901 CurBlock->hasPrototype = true;
4902 CurBlock->isVariadic = false;
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00004903
4904 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
4905
4906 // Do not allow returning a objc interface by-value.
4907 if (RetTy->isObjCInterfaceType()) {
4908 Diag(ParamInfo.getSourceRange().getBegin(),
4909 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
4910 return;
4911 }
Mike Stumpc1fddff2009-02-04 22:31:32 +00004912 return;
4913 }
4914
Steve Naroff52a81c02008-09-03 18:15:37 +00004915 // Analyze arguments to block.
4916 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4917 "Not a function declarator!");
4918 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00004919
Steve Naroff52059382008-10-10 01:28:17 +00004920 CurBlock->hasPrototype = FTI.hasPrototype;
4921 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00004922
Steve Naroff52a81c02008-09-03 18:15:37 +00004923 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4924 // no arguments, not a function that takes a single void argument.
4925 if (FTI.hasPrototype &&
4926 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner5261d0c2009-03-28 19:18:32 +00004927 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
4928 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004929 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004930 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004931 } else if (FTI.hasPrototype) {
4932 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner5261d0c2009-03-28 19:18:32 +00004933 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff52059382008-10-10 01:28:17 +00004934 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00004935 }
Steve Naroff494cb0f2009-03-13 16:56:44 +00004936 CurBlock->TheDecl->setParams(Context, &CurBlock->Params[0],
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00004937 CurBlock->Params.size());
Mike Stump9afab102009-02-19 03:04:26 +00004938
Steve Naroff52059382008-10-10 01:28:17 +00004939 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4940 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4941 // If this has an identifier, add it to the scope stack.
4942 if ((*AI)->getIdentifier())
4943 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00004944
4945 // Analyze the return type.
4946 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4947 QualType RetTy = T->getAsFunctionType()->getResultType();
4948
4949 // Do not allow returning a objc interface by-value.
4950 if (RetTy->isObjCInterfaceType()) {
4951 Diag(ParamInfo.getSourceRange().getBegin(),
4952 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
4953 } else if (!RetTy->isDependentType())
4954 CurBlock->ReturnType = RetTy.getTypePtr();
Steve Naroff52a81c02008-09-03 18:15:37 +00004955}
4956
4957/// ActOnBlockError - If there is an error parsing a block, this callback
4958/// is invoked to pop the information about the block from the action impl.
4959void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4960 // Ensure that CurBlock is deleted.
4961 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00004962
Chris Lattnere7765e12009-04-19 05:28:12 +00004963 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
4964
Steve Naroff52a81c02008-09-03 18:15:37 +00004965 // Pop off CurBlock, handle nested blocks.
Chris Lattnereb4d4a52009-04-21 22:38:46 +00004966 PopDeclContext();
Steve Naroff52a81c02008-09-03 18:15:37 +00004967 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff52a81c02008-09-03 18:15:37 +00004968 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff52a81c02008-09-03 18:15:37 +00004969}
4970
4971/// ActOnBlockStmtExpr - This is called when the body of a block statement
4972/// literal was successfully completed. ^(int x){...}
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004973Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
4974 StmtArg body, Scope *CurScope) {
Chris Lattnerc14c7f02009-03-27 04:18:06 +00004975 // If blocks are disabled, emit an error.
4976 if (!LangOpts.Blocks)
4977 Diag(CaretLoc, diag::err_blocks_disable);
4978
Steve Naroff52a81c02008-09-03 18:15:37 +00004979 // Ensure that CurBlock is deleted.
4980 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff52a81c02008-09-03 18:15:37 +00004981
Steve Naroff52059382008-10-10 01:28:17 +00004982 PopDeclContext();
4983
Steve Naroff52a81c02008-09-03 18:15:37 +00004984 // Pop off CurBlock, handle nested blocks.
4985 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004986
Steve Naroff52a81c02008-09-03 18:15:37 +00004987 QualType RetTy = Context.VoidTy;
4988 if (BSI->ReturnType)
4989 RetTy = QualType(BSI->ReturnType, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004990
Steve Naroff52a81c02008-09-03 18:15:37 +00004991 llvm::SmallVector<QualType, 8> ArgTypes;
4992 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4993 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00004994
Steve Naroff52a81c02008-09-03 18:15:37 +00004995 QualType BlockTy;
4996 if (!BSI->hasPrototype)
Douglas Gregor4fa58902009-02-26 23:50:07 +00004997 BlockTy = Context.getFunctionNoProtoType(RetTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004998 else
4999 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00005000 BSI->isVariadic, 0);
Mike Stump9afab102009-02-19 03:04:26 +00005001
Eli Friedman2b128322009-03-23 00:24:07 +00005002 // FIXME: Check that return/parameter types are complete/non-abstract
5003
Steve Naroff52a81c02008-09-03 18:15:37 +00005004 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00005005
Chris Lattnere7765e12009-04-19 05:28:12 +00005006 // If needed, diagnose invalid gotos and switches in the block.
5007 if (CurFunctionNeedsScopeChecking)
5008 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5009 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5010
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005011 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005012 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5013 BSI->hasBlockDeclRefExprs));
Steve Naroff52a81c02008-09-03 18:15:37 +00005014}
5015
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005016Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5017 ExprArg expr, TypeTy *type,
5018 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00005019 QualType T = QualType::getFromOpaquePtr(type);
Chris Lattnerda139482009-04-05 15:49:53 +00005020 Expr *E = static_cast<Expr*>(expr.get());
5021 Expr *OrigExpr = E;
5022
Anders Carlsson36760332007-10-15 20:28:48 +00005023 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005024
5025 // Get the va_list type
5026 QualType VaListType = Context.getBuiltinVaListType();
5027 // Deal with implicit array decay; for example, on x86-64,
5028 // va_list is an array, but it's supposed to decay to
5029 // a pointer for va_arg.
5030 if (VaListType->isArrayType())
5031 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00005032 // Make sure the input expression also decays appropriately.
5033 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005034
Chris Lattnercb9469d2009-04-06 17:07:34 +00005035 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005036 return ExprError(Diag(E->getLocStart(),
5037 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerda139482009-04-05 15:49:53 +00005038 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner89a72c52009-04-05 00:59:53 +00005039 }
Mike Stump9afab102009-02-19 03:04:26 +00005040
Eli Friedman2b128322009-03-23 00:24:07 +00005041 // FIXME: Check that type is complete/non-abstract
Anders Carlsson36760332007-10-15 20:28:48 +00005042 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00005043
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005044 expr.release();
5045 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5046 RPLoc));
Anders Carlsson36760332007-10-15 20:28:48 +00005047}
5048
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005049Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregorad4b3792008-11-29 04:51:27 +00005050 // The type of __null will be int or long, depending on the size of
5051 // pointers on the target.
5052 QualType Ty;
5053 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5054 Ty = Context.IntTy;
5055 else
5056 Ty = Context.LongTy;
5057
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005058 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregorad4b3792008-11-29 04:51:27 +00005059}
5060
Chris Lattner005ed752008-01-04 18:04:52 +00005061bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5062 SourceLocation Loc,
5063 QualType DstType, QualType SrcType,
5064 Expr *SrcExpr, const char *Flavor) {
5065 // Decode the result (notice that AST's are still created for extensions).
5066 bool isInvalid = false;
5067 unsigned DiagKind;
5068 switch (ConvTy) {
5069 default: assert(0 && "Unknown conversion type");
5070 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005071 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00005072 DiagKind = diag::ext_typecheck_convert_pointer_int;
5073 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005074 case IntToPointer:
5075 DiagKind = diag::ext_typecheck_convert_int_pointer;
5076 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005077 case IncompatiblePointer:
5078 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5079 break;
Eli Friedman6ca28cb2009-03-22 23:59:44 +00005080 case IncompatiblePointerSign:
5081 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5082 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005083 case FunctionVoidPointer:
5084 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5085 break;
5086 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00005087 // If the qualifiers lost were because we were applying the
5088 // (deprecated) C++ conversion from a string literal to a char*
5089 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
5090 // Ideally, this check would be performed in
5091 // CheckPointerTypesForAssignment. However, that would require a
5092 // bit of refactoring (so that the second argument is an
5093 // expression, rather than a type), which should be done as part
5094 // of a larger effort to fix CheckPointerTypesForAssignment for
5095 // C++ semantics.
5096 if (getLangOptions().CPlusPlus &&
5097 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5098 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00005099 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5100 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005101 case IntToBlockPointer:
5102 DiagKind = diag::err_int_to_block_pointer;
5103 break;
5104 case IncompatibleBlockPointer:
Mike Stumpd331e752009-04-21 22:51:42 +00005105 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005106 break;
Steve Naroff19608432008-10-14 22:18:38 +00005107 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00005108 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00005109 // it can give a more specific diagnostic.
5110 DiagKind = diag::warn_incompatible_qualified_id;
5111 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00005112 case IncompatibleVectors:
5113 DiagKind = diag::warn_incompatible_vectors;
5114 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005115 case Incompatible:
5116 DiagKind = diag::err_typecheck_convert_incompatible;
5117 isInvalid = true;
5118 break;
5119 }
Mike Stump9afab102009-02-19 03:04:26 +00005120
Chris Lattner271d4c22008-11-24 05:29:24 +00005121 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5122 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00005123 return isInvalid;
5124}
Anders Carlssond5201b92008-11-30 19:50:32 +00005125
Chris Lattnereec8ae22009-04-25 21:59:05 +00005126bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmance329412009-04-25 22:26:58 +00005127 llvm::APSInt ICEResult;
5128 if (E->isIntegerConstantExpr(ICEResult, Context)) {
5129 if (Result)
5130 *Result = ICEResult;
5131 return false;
5132 }
5133
Anders Carlssond5201b92008-11-30 19:50:32 +00005134 Expr::EvalResult EvalResult;
5135
Mike Stump9afab102009-02-19 03:04:26 +00005136 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00005137 EvalResult.HasSideEffects) {
5138 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5139
5140 if (EvalResult.Diag) {
5141 // We only show the note if it's not the usual "invalid subexpression"
5142 // or if it's actually in a subexpression.
5143 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5144 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5145 Diag(EvalResult.DiagLoc, EvalResult.Diag);
5146 }
Mike Stump9afab102009-02-19 03:04:26 +00005147
Anders Carlssond5201b92008-11-30 19:50:32 +00005148 return true;
5149 }
5150
Eli Friedmance329412009-04-25 22:26:58 +00005151 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5152 E->getSourceRange();
Anders Carlssond5201b92008-11-30 19:50:32 +00005153
Eli Friedmance329412009-04-25 22:26:58 +00005154 if (EvalResult.Diag &&
5155 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5156 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump9afab102009-02-19 03:04:26 +00005157
Anders Carlssond5201b92008-11-30 19:50:32 +00005158 if (Result)
5159 *Result = EvalResult.Val.getInt();
5160 return false;
5161}