blob: bd76b9ff129f5527e029a76b0b22407ac156d568 [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-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 Lattner5b183d82006-11-10 05:03:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
15#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/AnalysisBasedWarnings.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000018#include "clang/AST/ASTContext.h"
Douglas Gregord1702062010-04-29 00:18:15 +000019#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000022#include "clang/AST/Expr.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000023#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregor5597ab42010-05-07 23:12:07 +000025#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000026#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000027#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000028#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000029#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000030#include "clang/Lex/LiteralSupport.h"
31#include "clang/Lex/Preprocessor.h"
John McCall8b0666c2010-08-20 18:27:03 +000032#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Designator.h"
34#include "clang/Sema/Scope.h"
35#include "clang/Sema/ParsedTemplate.h"
John McCallde6836a2010-08-24 07:21:54 +000036#include "clang/Sema/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000037using namespace clang;
38
David Chisnall9f57c292009-08-17 16:35:33 +000039
Douglas Gregor171c45a2009-02-18 21:56:37 +000040/// \brief Determine whether the use of this declaration is valid, and
41/// emit any corresponding diagnostics.
42///
43/// This routine diagnoses various problems with referencing
44/// declarations that can occur when using a declaration. For example,
45/// it might warn if a deprecated or unavailable declaration is being
46/// used, or produce an error (and return true) if a C++0x deleted
47/// function is being used.
48///
Chris Lattnerb7df3c62009-10-25 22:31:57 +000049/// If IgnoreDeprecated is set to true, this should not want about deprecated
50/// decls.
51///
Douglas Gregor171c45a2009-02-18 21:56:37 +000052/// \returns true if there was an error (this declaration cannot be
53/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000054///
John McCall28a6aea2009-11-04 02:18:39 +000055bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner4bf74fd2009-02-15 22:43:40 +000056 // See if the decl is deprecated.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000057 if (D->getAttr<DeprecatedAttr>()) {
John McCall28a6aea2009-11-04 02:18:39 +000058 EmitDeprecationWarning(D, Loc);
Chris Lattner4bf74fd2009-02-15 22:43:40 +000059 }
60
Chris Lattnera27dd592009-10-25 17:21:40 +000061 // See if the decl is unavailable
62 if (D->getAttr<UnavailableAttr>()) {
Ted Kremenek1ddd6d22010-07-21 20:43:11 +000063 Diag(Loc, diag::err_unavailable) << D->getDeclName();
Chris Lattnera27dd592009-10-25 17:21:40 +000064 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
65 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000066
Douglas Gregor171c45a2009-02-18 21:56:37 +000067 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000068 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000069 if (FD->isDeleted()) {
70 Diag(Loc, diag::err_deleted_function_use);
71 Diag(D->getLocation(), diag::note_unavailable_here) << true;
72 return true;
73 }
Douglas Gregorde681d42009-02-24 04:26:15 +000074 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000075
Douglas Gregor171c45a2009-02-18 21:56:37 +000076 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +000077}
78
Fariborz Jahanian027b8862009-05-13 18:09:35 +000079/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +000080/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +000081/// attribute. It warns if call does not have the sentinel argument.
82///
83void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +000084 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000085 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +000086 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +000087 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +000088
89 // FIXME: In C++0x, if any of the arguments are parameter pack
90 // expansions, we can't check for the sentinel now.
Fariborz Jahanian9e877212009-05-13 23:20:50 +000091 int sentinelPos = attr->getSentinel();
92 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +000093
Mike Stump87c57ac2009-05-16 07:39:55 +000094 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
95 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +000096 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +000097 bool warnNotEnoughArgs = false;
98 int isMethod = 0;
99 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
100 // skip over named parameters.
101 ObjCMethodDecl::param_iterator P, E = MD->param_end();
102 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
103 if (nullPos)
104 --nullPos;
105 else
106 ++i;
107 }
108 warnNotEnoughArgs = (P != E || i >= NumArgs);
109 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000110 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000111 // skip over named parameters.
112 ObjCMethodDecl::param_iterator P, E = FD->param_end();
113 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
114 if (nullPos)
115 --nullPos;
116 else
117 ++i;
118 }
119 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000120 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000121 // block or function pointer call.
122 QualType Ty = V->getType();
123 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000124 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000125 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
126 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000127 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
128 unsigned NumArgsInProto = Proto->getNumArgs();
129 unsigned k;
130 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
131 if (nullPos)
132 --nullPos;
133 else
134 ++i;
135 }
136 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
137 }
138 if (Ty->isBlockPointerType())
139 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000140 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000141 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000142 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000143 return;
144
145 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000146 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000147 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000148 return;
149 }
150 int sentinel = i;
151 while (sentinelPos > 0 && i < NumArgs-1) {
152 --sentinelPos;
153 ++i;
154 }
155 if (sentinelPos > 0) {
156 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000157 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000158 return;
159 }
160 while (i < NumArgs-1) {
161 ++i;
162 ++sentinel;
163 }
164 Expr *sentinelExpr = Args[sentinel];
John McCall7ddbcf42010-05-06 23:53:00 +0000165 if (!sentinelExpr) return;
166 if (sentinelExpr->isTypeDependent()) return;
167 if (sentinelExpr->isValueDependent()) return;
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000168 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-05-06 23:53:00 +0000169 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
170 Expr::NPC_ValueDependentIsNull))
171 return;
172
173 // Unfortunately, __null has type 'int'.
174 if (isa<GNUNullExpr>(sentinelExpr)) return;
175
176 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
177 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000178}
179
Douglas Gregor87f95b02009-02-26 21:00:50 +0000180SourceRange Sema::getExprRange(ExprTy *E) const {
181 Expr *Ex = (Expr *)E;
182 return Ex? Ex->getSourceRange() : SourceRange();
183}
184
Chris Lattner513165e2008-07-25 21:10:04 +0000185//===----------------------------------------------------------------------===//
186// Standard Promotions and Conversions
187//===----------------------------------------------------------------------===//
188
Chris Lattner513165e2008-07-25 21:10:04 +0000189/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
190void Sema::DefaultFunctionArrayConversion(Expr *&E) {
191 QualType Ty = E->getType();
192 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
193
Chris Lattner513165e2008-07-25 21:10:04 +0000194 if (Ty->isFunctionType())
Mike Stump11289f42009-09-09 15:08:12 +0000195 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlsson6904f642009-09-01 20:37:18 +0000196 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000197 else if (Ty->isArrayType()) {
198 // In C90 mode, arrays only promote to pointers if the array expression is
199 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
200 // type 'array of type' is converted to an expression that has type 'pointer
201 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
202 // that has type 'array of type' ...". The relevant change is "an lvalue"
203 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000204 //
205 // C++ 4.2p1:
206 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
207 // T" can be converted to an rvalue of type "pointer to T".
208 //
209 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
210 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson8fc489d2009-08-07 23:48:20 +0000211 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
212 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000213 }
Chris Lattner513165e2008-07-25 21:10:04 +0000214}
215
Douglas Gregorb92a1562010-02-03 00:27:59 +0000216void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
217 DefaultFunctionArrayConversion(E);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000218
Douglas Gregorb92a1562010-02-03 00:27:59 +0000219 QualType Ty = E->getType();
220 assert(!Ty.isNull() && "DefaultFunctionArrayLvalueConversion - missing type");
221 if (!Ty->isDependentType() && Ty.hasQualifiers() &&
222 (!getLangOptions().CPlusPlus || !Ty->isRecordType()) &&
223 E->isLvalue(Context) == Expr::LV_Valid) {
224 // C++ [conv.lval]p1:
225 // [...] If T is a non-class type, the type of the rvalue is the
226 // cv-unqualified version of T. Otherwise, the type of the
227 // rvalue is T
228 //
229 // C99 6.3.2.1p2:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000230 // If the lvalue has qualified type, the value has the unqualified
231 // version of the type of the lvalue; otherwise, the value has the
Douglas Gregorb92a1562010-02-03 00:27:59 +0000232 // type of the lvalue.
233 ImpCastExprToType(E, Ty.getUnqualifiedType(), CastExpr::CK_NoOp);
234 }
235}
236
237
Chris Lattner513165e2008-07-25 21:10:04 +0000238/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000239/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner513165e2008-07-25 21:10:04 +0000240/// sometimes surpressed. For example, the array->pointer conversion doesn't
241/// apply if the array is an argument to the sizeof or address (&) operators.
242/// In these instances, this routine should *not* be called.
243Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
244 QualType Ty = Expr->getType();
245 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000246
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000247 // C99 6.3.1.1p2:
248 //
249 // The following may be used in an expression wherever an int or
250 // unsigned int may be used:
251 // - an object or expression with an integer type whose integer
252 // conversion rank is less than or equal to the rank of int
253 // and unsigned int.
254 // - A bit-field of type _Bool, int, signed int, or unsigned int.
255 //
256 // If an int can represent all values of the original type, the
257 // value is converted to an int; otherwise, it is converted to an
258 // unsigned int. These are called the integer promotions. All
259 // other types are unchanged by the integer promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000260 QualType PTy = Context.isPromotableBitField(Expr);
261 if (!PTy.isNull()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +0000262 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman629ffb92009-08-20 04:21:42 +0000263 return Expr;
264 }
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000265 if (Ty->isPromotableIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000266 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman06ed2a52009-10-20 08:27:19 +0000267 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000268 return Expr;
Eli Friedman629ffb92009-08-20 04:21:42 +0000269 }
270
Douglas Gregorb92a1562010-02-03 00:27:59 +0000271 DefaultFunctionArrayLvalueConversion(Expr);
Chris Lattner513165e2008-07-25 21:10:04 +0000272 return Expr;
273}
274
Chris Lattner2ce500f2008-07-25 22:25:12 +0000275/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000276/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000277/// double. All other argument types are converted by UsualUnaryConversions().
278void Sema::DefaultArgumentPromotion(Expr *&Expr) {
279 QualType Ty = Expr->getType();
280 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000281
Chris Lattner2ce500f2008-07-25 22:25:12 +0000282 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000283 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
284 return ImpCastExprToType(Expr, Context.DoubleTy,
285 CastExpr::CK_FloatingCast);
Mike Stump11289f42009-09-09 15:08:12 +0000286
Chris Lattner2ce500f2008-07-25 22:25:12 +0000287 UsualUnaryConversions(Expr);
288}
289
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000290/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
291/// will warn if the resulting type is not a POD type, and rejects ObjC
292/// interfaces passed by value. This returns true if the argument type is
293/// completely illegal.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000294bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
295 FunctionDecl *FDecl) {
Anders Carlssona7d069d2009-01-16 16:48:51 +0000296 DefaultArgumentPromotion(Expr);
Mike Stump11289f42009-09-09 15:08:12 +0000297
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000298 // __builtin_va_start takes the second argument as a "varargs" argument, but
299 // it doesn't actually do anything with it. It doesn't need to be non-pod
300 // etc.
301 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
302 return false;
303
John McCall8b07ec22010-05-15 11:32:37 +0000304 if (Expr->getType()->isObjCObjectType() &&
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000305 DiagRuntimeBehavior(Expr->getLocStart(),
306 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
307 << Expr->getType() << CT))
308 return true;
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000309
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000310 if (!Expr->getType()->isPODType() &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000311 DiagRuntimeBehavior(Expr->getLocStart(),
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000312 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
313 << Expr->getType() << CT))
314 return true;
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000315
316 return false;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000317}
318
319
Chris Lattner513165e2008-07-25 21:10:04 +0000320/// UsualArithmeticConversions - Performs various conversions that are common to
321/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000322/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000323/// responsible for emitting appropriate error diagnostics.
324/// FIXME: verify the conversion rules for "complex int" are consistent with
325/// GCC.
326QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
327 bool isCompAssign) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000328 if (!isCompAssign)
Chris Lattner513165e2008-07-25 21:10:04 +0000329 UsualUnaryConversions(lhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000330
331 UsualUnaryConversions(rhsExpr);
Douglas Gregora11693b2008-11-12 17:17:38 +0000332
Mike Stump11289f42009-09-09 15:08:12 +0000333 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000334 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000335 QualType lhs =
336 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000337 QualType rhs =
Chris Lattner574dee62008-07-26 22:17:49 +0000338 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000339
340 // If both types are identical, no conversion is needed.
341 if (lhs == rhs)
342 return lhs;
343
344 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
345 // The caller can deal with this (e.g. pointer + int).
346 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
347 return lhs;
348
Douglas Gregord2c2d172009-05-02 00:36:19 +0000349 // Perform bitfield promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000350 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000351 if (!LHSBitfieldPromoteTy.isNull())
352 lhs = LHSBitfieldPromoteTy;
Eli Friedman629ffb92009-08-20 04:21:42 +0000353 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000354 if (!RHSBitfieldPromoteTy.isNull())
355 rhs = RHSBitfieldPromoteTy;
356
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000357 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000358 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +0000359 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
360 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregora11693b2008-11-12 17:17:38 +0000361 return destType;
362}
363
Chris Lattner513165e2008-07-25 21:10:04 +0000364//===----------------------------------------------------------------------===//
365// Semantic Analysis for various Expression Types
366//===----------------------------------------------------------------------===//
367
368
Steve Naroff83895f72007-09-16 03:34:24 +0000369/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000370/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
371/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
372/// multiple tokens. However, the common case is that StringToks points to one
373/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000374///
John McCalldadc5752010-08-24 06:29:42 +0000375ExprResult
Steve Naroff83895f72007-09-16 03:34:24 +0000376Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000377 assert(NumStringToks && "Must have at least one string!");
378
Chris Lattner8a24e582009-01-16 18:51:42 +0000379 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000380 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000381 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000382
Chris Lattner23b7eb62007-06-15 23:05:46 +0000383 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000384 for (unsigned i = 0; i != NumStringToks; ++i)
385 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000386
Chris Lattner36fc8792008-02-11 00:02:17 +0000387 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidiscbad7252008-08-09 17:20:01 +0000388 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattner36fc8792008-02-11 00:02:17 +0000389 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000390
391 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +0000392 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000393 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000394
Chris Lattner36fc8792008-02-11 00:02:17 +0000395 // Get an array type for the string, according to C99 6.4.5. This includes
396 // the nul terminator character as well as the string length for pascal
397 // strings.
398 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000399 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000400 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000401
Chris Lattner5b183d82006-11-10 05:03:26 +0000402 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump11289f42009-09-09 15:08:12 +0000403 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000404 Literal.GetStringLength(),
405 Literal.AnyWide, StrTy,
406 &StringTokLocs[0],
407 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000408}
409
Chris Lattner2a9d9892008-10-20 05:16:36 +0000410/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
411/// CurBlock to VD should cause it to be snapshotted (as we do for auto
412/// variables defined outside the block) or false if this is not needed (e.g.
413/// for values inside the block or for globals).
414///
Douglas Gregor4f13beb2010-03-01 20:44:28 +0000415/// This also keeps the 'hasBlockDeclRefExprs' in the BlockScopeInfo records
Chris Lattner497d7b02009-04-21 22:26:47 +0000416/// up-to-date.
417///
Douglas Gregor9a28e842010-03-01 23:15:13 +0000418static bool ShouldSnapshotBlockValueReference(Sema &S, BlockScopeInfo *CurBlock,
Chris Lattner2a9d9892008-10-20 05:16:36 +0000419 ValueDecl *VD) {
420 // If the value is defined inside the block, we couldn't snapshot it even if
421 // we wanted to.
422 if (CurBlock->TheDecl == VD->getDeclContext())
423 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000424
Chris Lattner2a9d9892008-10-20 05:16:36 +0000425 // If this is an enum constant or function, it is constant, don't snapshot.
426 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
427 return false;
428
429 // If this is a reference to an extern, static, or global variable, no need to
430 // snapshot it.
431 // FIXME: What about 'const' variables in C++?
432 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner497d7b02009-04-21 22:26:47 +0000433 if (!Var->hasLocalStorage())
434 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000435
Chris Lattner497d7b02009-04-21 22:26:47 +0000436 // Blocks that have these can't be constant.
437 CurBlock->hasBlockDeclRefExprs = true;
438
439 // If we have nested blocks, the decl may be declared in an outer block (in
440 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
441 // be defined outside all of the current blocks (in which case the blocks do
442 // all get the bit). Walk the nesting chain.
Douglas Gregor9a28e842010-03-01 23:15:13 +0000443 for (unsigned I = S.FunctionScopes.size() - 1; I; --I) {
444 BlockScopeInfo *NextBlock = dyn_cast<BlockScopeInfo>(S.FunctionScopes[I]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000445
Douglas Gregor9a28e842010-03-01 23:15:13 +0000446 if (!NextBlock)
447 continue;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000448
Chris Lattner497d7b02009-04-21 22:26:47 +0000449 // If we found the defining block for the variable, don't mark the block as
450 // having a reference outside it.
451 if (NextBlock->TheDecl == VD->getDeclContext())
452 break;
Mike Stump11289f42009-09-09 15:08:12 +0000453
Chris Lattner497d7b02009-04-21 22:26:47 +0000454 // Otherwise, the DeclRef from the inner block causes the outer one to need
455 // a snapshot as well.
456 NextBlock->hasBlockDeclRefExprs = true;
457 }
Mike Stump11289f42009-09-09 15:08:12 +0000458
Chris Lattner2a9d9892008-10-20 05:16:36 +0000459 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000460}
461
Chris Lattner2a9d9892008-10-20 05:16:36 +0000462
John McCalldadc5752010-08-24 06:29:42 +0000463ExprResult
John McCallce546572009-12-08 09:08:17 +0000464Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc,
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000465 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000466 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
467 return BuildDeclRefExpr(D, Ty, NameInfo, SS);
468}
469
470/// BuildDeclRefExpr - Build a DeclRefExpr.
John McCalldadc5752010-08-24 06:29:42 +0000471ExprResult
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000472Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty,
473 const DeclarationNameInfo &NameInfo,
474 const CXXScopeSpec *SS) {
Anders Carlsson364035d12009-06-26 19:16:07 +0000475 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000476 Diag(NameInfo.getLoc(),
Mike Stump11289f42009-09-09 15:08:12 +0000477 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlsson364035d12009-06-26 19:16:07 +0000478 << D->getDeclName();
479 return ExprError();
480 }
Mike Stump11289f42009-09-09 15:08:12 +0000481
Anders Carlsson946b86d2009-06-24 00:10:43 +0000482 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Douglas Gregor15243332010-04-27 21:10:04 +0000483 if (isa<NonTypeTemplateParmDecl>(VD)) {
484 // Non-type template parameters can be referenced anywhere they are
485 // visible.
Douglas Gregora8a089b2010-07-13 18:40:04 +0000486 Ty = Ty.getNonLValueExprType(Context);
Douglas Gregor15243332010-04-27 21:10:04 +0000487 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
Anders Carlsson946b86d2009-06-24 00:10:43 +0000488 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
489 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000490 Diag(NameInfo.getLoc(),
491 diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000492 << D->getIdentifier() << FD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +0000493 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000494 << D->getIdentifier();
495 return ExprError();
496 }
497 }
498 }
499 }
Mike Stump11289f42009-09-09 15:08:12 +0000500
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000501 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +0000502
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000503 return Owned(DeclRefExpr::Create(Context,
504 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
505 SS? SS->getRange() : SourceRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000506 D, NameInfo, Ty));
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000507}
508
Douglas Gregord5846a12009-04-15 06:41:24 +0000509/// \brief Given a field that represents a member of an anonymous
510/// struct/union, build the path from that field's context to the
511/// actual member.
512///
513/// Construct the sequence of field member references we'll have to
514/// perform to get to the field in the anonymous union/struct. The
515/// list of members is built from the field outward, so traverse it
516/// backwards to go from an object in the current context to the field
517/// we found.
518///
519/// \returns The variable from which the field access should begin,
520/// for an anonymous struct/union that is not a member of another
521/// class. Otherwise, returns NULL.
522VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
523 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000524 assert(Field->getDeclContext()->isRecord() &&
525 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
526 && "Field must be stored inside an anonymous struct or union");
527
Douglas Gregord5846a12009-04-15 06:41:24 +0000528 Path.push_back(Field);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000529 VarDecl *BaseObject = 0;
530 DeclContext *Ctx = Field->getDeclContext();
531 do {
532 RecordDecl *Record = cast<RecordDecl>(Ctx);
John McCall61925b02010-05-21 01:17:40 +0000533 ValueDecl *AnonObject = Record->getAnonymousStructOrUnionObject();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000534 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregord5846a12009-04-15 06:41:24 +0000535 Path.push_back(AnonField);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000536 else {
537 BaseObject = cast<VarDecl>(AnonObject);
538 break;
539 }
540 Ctx = Ctx->getParent();
Mike Stump11289f42009-09-09 15:08:12 +0000541 } while (Ctx->isRecord() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000542 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregord5846a12009-04-15 06:41:24 +0000543
544 return BaseObject;
545}
546
John McCalldadc5752010-08-24 06:29:42 +0000547ExprResult
Douglas Gregord5846a12009-04-15 06:41:24 +0000548Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
549 FieldDecl *Field,
550 Expr *BaseObjectExpr,
551 SourceLocation OpLoc) {
552 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump11289f42009-09-09 15:08:12 +0000553 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregord5846a12009-04-15 06:41:24 +0000554 AnonFields);
555
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000556 // Build the expression that refers to the base object, from
557 // which we will build a sequence of member references to each
558 // of the anonymous union objects and, eventually, the field we
559 // found via name lookup.
560 bool BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000561 Qualifiers BaseQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000562 if (BaseObject) {
563 // BaseObject is an anonymous struct/union variable (and is,
564 // therefore, not part of another non-anonymous record).
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000565 MarkDeclarationReferenced(Loc, BaseObject);
Steve Narofff6009ed2009-01-21 00:14:39 +0000566 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump4e1f26a2009-02-19 03:04:26 +0000567 SourceLocation());
John McCall8ccfcb52009-09-24 19:53:00 +0000568 BaseQuals
569 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000570 } else if (BaseObjectExpr) {
571 // The caller provided the base object expression. Determine
572 // whether its a pointer and whether it adds any qualifiers to the
573 // anonymous struct/union fields we're looking into.
574 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000575 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000576 BaseObjectIsPointer = true;
577 ObjectType = ObjectPtr->getPointeeType();
578 }
John McCall8ccfcb52009-09-24 19:53:00 +0000579 BaseQuals
580 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000581 } else {
582 // We've found a member of an anonymous struct/union that is
583 // inside a non-anonymous struct/union, so in a well-formed
584 // program our base object expression is "this".
John McCall87fe5d52010-05-20 01:18:31 +0000585 DeclContext *DC = getFunctionLevelDeclContext();
586 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000587 if (!MD->isStatic()) {
Mike Stump11289f42009-09-09 15:08:12 +0000588 QualType AnonFieldType
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000589 = Context.getTagDeclType(
590 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
591 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump11289f42009-09-09 15:08:12 +0000592 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000593 == Context.getCanonicalType(ThisType)) ||
594 IsDerivedFrom(ThisType, AnonFieldType)) {
595 // Our base object expression is "this".
Douglas Gregor4b654412009-12-24 20:23:34 +0000596 BaseObjectExpr = new (Context) CXXThisExpr(Loc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000597 MD->getThisType(Context),
598 /*isImplicit=*/true);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000599 BaseObjectIsPointer = true;
600 }
601 } else {
Sebastian Redlffbcf962009-01-18 18:53:16 +0000602 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
603 << Field->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000604 }
John McCall8ccfcb52009-09-24 19:53:00 +0000605 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000606 }
607
Mike Stump11289f42009-09-09 15:08:12 +0000608 if (!BaseObjectExpr)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000609 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
610 << Field->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000611 }
612
613 // Build the implicit member references to the field of the
614 // anonymous struct/union.
615 Expr *Result = BaseObjectExpr;
John McCall8ccfcb52009-09-24 19:53:00 +0000616 Qualifiers ResultQuals = BaseQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000617 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
618 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
619 FI != FIEnd; ++FI) {
620 QualType MemberType = (*FI)->getType();
John McCall8ccfcb52009-09-24 19:53:00 +0000621 Qualifiers MemberTypeQuals =
622 Context.getCanonicalType(MemberType).getQualifiers();
623
624 // CVR attributes from the base are picked up by members,
625 // except that 'mutable' members don't pick up 'const'.
626 if ((*FI)->isMutable())
627 ResultQuals.removeConst();
628
629 // GC attributes are never picked up by members.
630 ResultQuals.removeObjCGCAttr();
631
632 // TR 18037 does not allow fields to be declared with address spaces.
633 assert(!MemberTypeQuals.hasAddressSpace());
634
635 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
636 if (NewQuals != MemberTypeQuals)
637 MemberType = Context.getQualifiedType(MemberType, NewQuals);
638
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000639 MarkDeclarationReferenced(Loc, *FI);
John McCall16df1e52010-03-30 21:47:33 +0000640 PerformObjectMemberConversion(Result, /*FIXME:Qualifier=*/0, *FI, *FI);
Douglas Gregorc1905232009-08-26 22:36:53 +0000641 // FIXME: Might this end up being a qualified name?
Steve Narofff6009ed2009-01-21 00:14:39 +0000642 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
643 OpLoc, MemberType);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000644 BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000645 ResultQuals = NewQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000646 }
647
Sebastian Redlffbcf962009-01-18 18:53:16 +0000648 return Owned(Result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000649}
650
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000651/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +0000652/// possibly a list of template arguments.
653///
654/// If this produces template arguments, it is permitted to call
655/// DecomposeTemplateName.
656///
657/// This actually loses a lot of source location information for
658/// non-standard name kinds; we should consider preserving that in
659/// some way.
660static void DecomposeUnqualifiedId(Sema &SemaRef,
661 const UnqualifiedId &Id,
662 TemplateArgumentListInfo &Buffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000663 DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +0000664 const TemplateArgumentListInfo *&TemplateArgs) {
665 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
666 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
667 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
668
669 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
670 Id.TemplateId->getTemplateArgs(),
671 Id.TemplateId->NumArgs);
672 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
673 TemplateArgsPtr.release();
674
John McCall3e56fd42010-08-23 07:28:44 +0000675 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000676 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
677 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +0000678 TemplateArgs = &Buffer;
679 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000680 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +0000681 TemplateArgs = 0;
682 }
683}
684
John McCall69f9dbc2010-02-08 19:26:07 +0000685/// Determines whether the given record is "fully-formed" at the given
686/// location, i.e. whether a qualified lookup into it is assured of
687/// getting consistent results already.
John McCall10eae182009-11-30 22:42:35 +0000688static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
John McCall69f9dbc2010-02-08 19:26:07 +0000689 if (!Record->hasDefinition())
690 return false;
691
John McCall10eae182009-11-30 22:42:35 +0000692 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
693 E = Record->bases_end(); I != E; ++I) {
694 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
695 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
696 if (!BaseRT) return false;
697
698 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall69f9dbc2010-02-08 19:26:07 +0000699 if (!BaseRecord->hasDefinition() ||
John McCall10eae182009-11-30 22:42:35 +0000700 !IsFullyFormedScope(SemaRef, BaseRecord))
701 return false;
702 }
703
704 return true;
705}
706
John McCall2d74de92009-12-01 22:10:20 +0000707/// Determines if the given class is provably not derived from all of
708/// the prospective base classes.
709static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
710 CXXRecordDecl *Record,
711 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +0000712 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +0000713 return false;
714
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000715 RecordDecl *RD = Record->getDefinition();
John McCalla6d407c2009-12-01 22:28:41 +0000716 if (!RD) return false;
717 Record = cast<CXXRecordDecl>(RD);
718
John McCall2d74de92009-12-01 22:10:20 +0000719 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
720 E = Record->bases_end(); I != E; ++I) {
721 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
722 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
723 if (!BaseRT) return false;
724
725 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +0000726 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
727 return false;
728 }
729
730 return true;
731}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000732
John McCall2d74de92009-12-01 22:10:20 +0000733enum IMAKind {
734 /// The reference is definitely not an instance member access.
735 IMA_Static,
736
737 /// The reference may be an implicit instance member access.
738 IMA_Mixed,
739
740 /// The reference may be to an instance member, but it is invalid if
741 /// so, because the context is not an instance method.
742 IMA_Mixed_StaticContext,
743
744 /// The reference may be to an instance member, but it is invalid if
745 /// so, because the context is from an unrelated class.
746 IMA_Mixed_Unrelated,
747
748 /// The reference is definitely an implicit instance member access.
749 IMA_Instance,
750
751 /// The reference may be to an unresolved using declaration.
752 IMA_Unresolved,
753
754 /// The reference may be to an unresolved using declaration and the
755 /// context is not an instance method.
756 IMA_Unresolved_StaticContext,
757
758 /// The reference is to a member of an anonymous structure in a
759 /// non-class context.
760 IMA_AnonymousMember,
761
762 /// All possible referrents are instance members and the current
763 /// context is not an instance method.
764 IMA_Error_StaticContext,
765
766 /// All possible referrents are instance members of an unrelated
767 /// class.
768 IMA_Error_Unrelated
769};
770
771/// The given lookup names class member(s) and is not being used for
772/// an address-of-member expression. Classify the type of access
773/// according to whether it's possible that this reference names an
774/// instance member. This is best-effort; it is okay to
775/// conservatively answer "yes", in which case some errors will simply
776/// not be caught until template-instantiation.
777static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
778 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +0000779 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +0000780
John McCall87fe5d52010-05-20 01:18:31 +0000781 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCall2d74de92009-12-01 22:10:20 +0000782 bool isStaticContext =
John McCall87fe5d52010-05-20 01:18:31 +0000783 (!isa<CXXMethodDecl>(DC) ||
784 cast<CXXMethodDecl>(DC)->isStatic());
John McCall2d74de92009-12-01 22:10:20 +0000785
786 if (R.isUnresolvableResult())
787 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
788
789 // Collect all the declaring classes of instance members we find.
790 bool hasNonInstance = false;
791 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
792 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCalla8ae2222010-04-06 21:38:20 +0000793 NamedDecl *D = *I;
794 if (D->isCXXInstanceMember()) {
John McCall2d74de92009-12-01 22:10:20 +0000795 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
796
797 // If this is a member of an anonymous record, move out to the
798 // innermost non-anonymous struct or union. If there isn't one,
799 // that's a special case.
800 while (R->isAnonymousStructOrUnion()) {
801 R = dyn_cast<CXXRecordDecl>(R->getParent());
802 if (!R) return IMA_AnonymousMember;
803 }
804 Classes.insert(R->getCanonicalDecl());
805 }
806 else
807 hasNonInstance = true;
808 }
809
810 // If we didn't find any instance members, it can't be an implicit
811 // member reference.
812 if (Classes.empty())
813 return IMA_Static;
814
815 // If the current context is not an instance method, it can't be
816 // an implicit member reference.
817 if (isStaticContext)
818 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
819
820 // If we can prove that the current context is unrelated to all the
821 // declaring classes, it can't be an implicit member reference (in
822 // which case it's an error if any of those members are selected).
823 if (IsProvablyNotDerivedFrom(SemaRef,
John McCall87fe5d52010-05-20 01:18:31 +0000824 cast<CXXMethodDecl>(DC)->getParent(),
John McCall2d74de92009-12-01 22:10:20 +0000825 Classes))
826 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
827
828 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
829}
830
831/// Diagnose a reference to a field with no object available.
832static void DiagnoseInstanceReference(Sema &SemaRef,
833 const CXXScopeSpec &SS,
834 const LookupResult &R) {
835 SourceLocation Loc = R.getNameLoc();
836 SourceRange Range(Loc);
837 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
838
839 if (R.getAsSingle<FieldDecl>()) {
840 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
841 if (MD->isStatic()) {
842 // "invalid use of member 'x' in static member function"
843 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
844 << Range << R.getLookupName();
845 return;
846 }
847 }
848
849 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
850 << R.getLookupName() << Range;
851 return;
852 }
853
854 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +0000855}
856
John McCalld681c392009-12-16 08:11:27 +0000857/// Diagnose an empty lookup.
858///
859/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000860bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
861 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +0000862 DeclarationName Name = R.getLookupName();
863
John McCalld681c392009-12-16 08:11:27 +0000864 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +0000865 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +0000866 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
867 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +0000868 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +0000869 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +0000870 diagnostic_suggest = diag::err_undeclared_use_suggest;
871 }
John McCalld681c392009-12-16 08:11:27 +0000872
Douglas Gregor598b08f2009-12-31 05:20:13 +0000873 // If the original lookup was an unqualified lookup, fake an
874 // unqualified lookup. This is useful when (for example) the
875 // original lookup would not have found something because it was a
876 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000877 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +0000878 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +0000879 if (isa<CXXRecordDecl>(DC)) {
880 LookupQualifiedName(R, DC);
881
882 if (!R.empty()) {
883 // Don't give errors about ambiguities in this lookup.
884 R.suppressDiagnostics();
885
886 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
887 bool isInstance = CurMethod &&
888 CurMethod->isInstance() &&
889 DC == CurMethod->getParent();
890
891 // Give a code modification hint to insert 'this->'.
892 // TODO: fixit for inserting 'Base<T>::' in the other cases.
893 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000894 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000895 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
896 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +0000897 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000898 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +0000899 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +0000900 Diag(R.getNameLoc(), diagnostic) << Name
901 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
902 QualType DepThisType = DepMethod->getThisType(Context);
903 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
904 R.getNameLoc(), DepThisType, false);
905 TemplateArgumentListInfo TList;
906 if (ULE->hasExplicitTemplateArgs())
907 ULE->copyTemplateArgumentsInto(TList);
908 CXXDependentScopeMemberExpr *DepExpr =
909 CXXDependentScopeMemberExpr::Create(
910 Context, DepThis, DepThisType, true, SourceLocation(),
911 ULE->getQualifier(), ULE->getQualifierRange(), NULL,
912 R.getLookupNameInfo(), &TList);
913 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +0000914 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +0000915 // FIXME: we should be able to handle this case too. It is correct
916 // to add this-> here. This is a workaround for PR7947.
917 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +0000918 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000919 } else {
John McCalld681c392009-12-16 08:11:27 +0000920 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000921 }
John McCalld681c392009-12-16 08:11:27 +0000922
923 // Do we really want to note all of these?
924 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
925 Diag((*I)->getLocation(), diag::note_dependent_var_use);
926
927 // Tell the callee to try to recover.
928 return false;
929 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +0000930
931 R.clear();
John McCalld681c392009-12-16 08:11:27 +0000932 }
933 }
934
Douglas Gregor598b08f2009-12-31 05:20:13 +0000935 // We didn't find anything, so try to correct for a typo.
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000936 DeclarationName Corrected;
Daniel Dunbarf7ced252010-06-02 15:46:52 +0000937 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000938 if (!R.empty()) {
939 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
940 if (SS.isEmpty())
941 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
942 << FixItHint::CreateReplacement(R.getNameLoc(),
943 R.getLookupName().getAsString());
944 else
945 Diag(R.getNameLoc(), diag::err_no_member_suggest)
946 << Name << computeDeclContext(SS, false) << R.getLookupName()
947 << SS.getRange()
948 << FixItHint::CreateReplacement(R.getNameLoc(),
949 R.getLookupName().getAsString());
950 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
951 Diag(ND->getLocation(), diag::note_previous_decl)
952 << ND->getDeclName();
953
954 // Tell the callee to try to recover.
955 return false;
956 }
Alexis Huntc46382e2010-04-28 23:02:27 +0000957
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000958 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
959 // FIXME: If we ended up with a typo for a type name or
960 // Objective-C class name, we're in trouble because the parser
961 // is in the wrong place to recover. Suggest the typo
962 // correction, but don't make it a fix-it since we're not going
963 // to recover well anyway.
964 if (SS.isEmpty())
965 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
966 else
967 Diag(R.getNameLoc(), diag::err_no_member_suggest)
968 << Name << computeDeclContext(SS, false) << R.getLookupName()
969 << SS.getRange();
970
971 // Don't try to recover; it won't work.
972 return true;
973 }
974 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +0000975 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000976 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +0000977 if (SS.isEmpty())
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000978 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000979 else
Douglas Gregor25363982010-01-01 00:15:04 +0000980 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000981 << Name << computeDeclContext(SS, false) << Corrected
982 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +0000983 return true;
984 }
Douglas Gregor25363982010-01-01 00:15:04 +0000985 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +0000986 }
987
988 // Emit a special diagnostic for failed member lookups.
989 // FIXME: computing the declaration context might fail here (?)
990 if (!SS.isEmpty()) {
991 Diag(R.getNameLoc(), diag::err_no_member)
992 << Name << computeDeclContext(SS, false)
993 << SS.getRange();
994 return true;
995 }
996
John McCalld681c392009-12-16 08:11:27 +0000997 // Give up, we can't recover.
998 Diag(R.getNameLoc(), diagnostic) << Name;
999 return true;
1000}
1001
Fariborz Jahanian86151342010-07-22 23:33:21 +00001002static ObjCPropertyDecl *OkToSynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001003 IdentifierInfo *II,
1004 SourceLocation NameLoc) {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001005 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
1006 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1007 if (!IDecl)
1008 return 0;
1009 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1010 if (!ClassImpDecl)
1011 return 0;
1012 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1013 if (!property)
1014 return 0;
1015 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
1016 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
1017 return 0;
1018 return property;
1019}
1020
Fariborz Jahanian18722982010-07-17 00:59:30 +00001021static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001022 LookupResult &Lookup,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001023 IdentifierInfo *II,
1024 SourceLocation NameLoc) {
1025 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001026 bool LookForIvars;
1027 if (Lookup.empty())
1028 LookForIvars = true;
1029 else if (CurMeth->isClassMethod())
1030 LookForIvars = false;
1031 else
1032 LookForIvars = (Lookup.isSingleResult() &&
1033 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1034 if (!LookForIvars)
1035 return 0;
1036
Fariborz Jahanian18722982010-07-17 00:59:30 +00001037 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1038 if (!IDecl)
1039 return 0;
1040 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001041 if (!ClassImpDecl)
1042 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001043 bool DynamicImplSeen = false;
1044 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1045 if (!property)
1046 return 0;
1047 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
1048 DynamicImplSeen =
1049 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
1050 if (!DynamicImplSeen) {
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001051 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1052 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001053 NameLoc,
1054 II, PropType, /*Dinfo=*/0,
1055 ObjCIvarDecl::Protected,
1056 (Expr *)0, true);
1057 ClassImpDecl->addDecl(Ivar);
1058 IDecl->makeDeclVisibleInContext(Ivar, false);
1059 property->setPropertyIvarDecl(Ivar);
1060 return Ivar;
1061 }
1062 return 0;
1063}
1064
John McCalldadc5752010-08-24 06:29:42 +00001065ExprResult Sema::ActOnIdExpression(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001066 CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +00001067 UnqualifiedId &Id,
1068 bool HasTrailingLParen,
1069 bool isAddressOfOperand) {
1070 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1071 "cannot be direct & operand and have a trailing lparen");
1072
1073 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001074 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001075
John McCall10eae182009-11-30 22:42:35 +00001076 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001077
1078 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001079 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001080 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001081 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001082
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001083 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001084 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001085 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001086
John McCalle66edc12009-11-24 19:00:30 +00001087 // C++ [temp.dep.expr]p3:
1088 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001089 // -- an identifier that was declared with a dependent type,
1090 // (note: handled after lookup)
1091 // -- a template-id that is dependent,
1092 // (note: handled in BuildTemplateIdExpr)
1093 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001094 // -- a nested-name-specifier that contains a class-name that
1095 // names a dependent type.
1096 // Determine whether this is a member of an unknown specialization;
1097 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001098 bool DependentID = false;
1099 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1100 Name.getCXXNameType()->isDependentType()) {
1101 DependentID = true;
1102 } else if (SS.isSet()) {
1103 DeclContext *DC = computeDeclContext(SS, false);
1104 if (DC) {
1105 if (RequireCompleteDeclContext(SS, DC))
1106 return ExprError();
1107 // FIXME: We should be checking whether DC is the current instantiation.
1108 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
1109 DependentID = !IsFullyFormedScope(*this, RD);
1110 } else {
1111 DependentID = true;
1112 }
1113 }
1114
1115 if (DependentID) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001116 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001117 TemplateArgs);
1118 }
Fariborz Jahanian86151342010-07-22 23:33:21 +00001119 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001120 // Perform the required lookup.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001121 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001122 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001123 // Lookup the template name again to correctly establish the context in
1124 // which it was found. This is really unfortunate as we already did the
1125 // lookup to determine that it was a template name in the first place. If
1126 // this becomes a performance hit, we can work harder to preserve those
1127 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001128 bool MemberOfUnknownSpecialization;
1129 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1130 MemberOfUnknownSpecialization);
John McCalle66edc12009-11-24 19:00:30 +00001131 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001132 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001133 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001134
John McCalle66edc12009-11-24 19:00:30 +00001135 // If this reference is in an Objective-C method, then we need to do
1136 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001137 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001138 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001139 if (E.isInvalid())
1140 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001141
John McCalle66edc12009-11-24 19:00:30 +00001142 Expr *Ex = E.takeAs<Expr>();
1143 if (Ex) return Owned(Ex);
Fariborz Jahanian18722982010-07-17 00:59:30 +00001144 // Synthesize ivars lazily
1145 if (getLangOptions().ObjCNonFragileABI2) {
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001146 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc))
Fariborz Jahanian18722982010-07-17 00:59:30 +00001147 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1148 isAddressOfOperand);
1149 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001150 // for further use, this must be set to false if in class method.
1151 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001152 }
Chris Lattner59a25942008-03-31 00:36:02 +00001153 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001154
John McCalle66edc12009-11-24 19:00:30 +00001155 if (R.isAmbiguous())
1156 return ExprError();
1157
Douglas Gregor171c45a2009-02-18 21:56:37 +00001158 // Determine whether this name might be a candidate for
1159 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001160 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001161
John McCalle66edc12009-11-24 19:00:30 +00001162 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001163 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001164 // in C90, extension in C99, forbidden in C++).
1165 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1166 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1167 if (D) R.addDecl(D);
1168 }
1169
1170 // If this name wasn't predeclared and if this is not a function
1171 // call, diagnose the problem.
1172 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001173 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001174 return ExprError();
1175
1176 assert(!R.empty() &&
1177 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001178
1179 // If we found an Objective-C instance variable, let
1180 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001181 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001182 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1183 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001184 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001185 assert(E.isInvalid() || E.get());
1186 return move(E);
1187 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001188 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001189 }
Mike Stump11289f42009-09-09 15:08:12 +00001190
John McCalle66edc12009-11-24 19:00:30 +00001191 // This is guaranteed from this point on.
1192 assert(!R.empty() || ADL);
1193
1194 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001195 if (getLangOptions().ObjCNonFragileABI && IvarLookupFollowUp &&
Fariborz Jahanianc15dfd82010-07-29 16:53:53 +00001196 !getLangOptions().ObjCNonFragileABI2 &&
1197 Var->isFileVarDecl()) {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001198 ObjCPropertyDecl *Property =
1199 OkToSynthesizeProvisionalIvar(*this, II, NameLoc);
1200 if (Property) {
1201 Diag(NameLoc, diag::warn_ivar_variable_conflict) << Var->getDeclName();
1202 Diag(Property->getLocation(), diag::note_property_declare);
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001203 Diag(Var->getLocation(), diag::note_global_declared_at);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001204 }
1205 }
John McCalle66edc12009-11-24 19:00:30 +00001206 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001207 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1208 // C99 DR 316 says that, if a function type comes from a
1209 // function definition (without a prototype), that type is only
1210 // used for checking compatibility. Therefore, when referencing
1211 // the function, we pretend that we don't have the full function
1212 // type.
John McCalle66edc12009-11-24 19:00:30 +00001213 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor3256d042009-06-30 15:47:41 +00001214 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001215
Douglas Gregor3256d042009-06-30 15:47:41 +00001216 QualType T = Func->getType();
1217 QualType NoProtoType = T;
John McCall9dd450b2009-09-21 23:43:11 +00001218 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Eli Friedmanb41ad0f2010-05-17 02:50:18 +00001219 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType(),
1220 Proto->getExtInfo());
John McCalle66edc12009-11-24 19:00:30 +00001221 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor3256d042009-06-30 15:47:41 +00001222 }
1223 }
Mike Stump11289f42009-09-09 15:08:12 +00001224
John McCall2d74de92009-12-01 22:10:20 +00001225 // Check whether this might be a C++ implicit instance member access.
1226 // C++ [expr.prim.general]p6:
1227 // Within the definition of a non-static member function, an
1228 // identifier that names a non-static member is transformed to a
1229 // class member access expression.
1230 // But note that &SomeClass::foo is grammatically distinct, even
1231 // though we don't parse it that way.
John McCall57500772009-12-16 12:17:52 +00001232 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCalle66edc12009-11-24 19:00:30 +00001233 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCall57500772009-12-16 12:17:52 +00001234 if (!isAbstractMemberPointer)
1235 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001236 }
1237
John McCalle66edc12009-11-24 19:00:30 +00001238 if (TemplateArgs)
1239 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001240
John McCalle66edc12009-11-24 19:00:30 +00001241 return BuildDeclarationNameExpr(SS, R, ADL);
1242}
1243
John McCall57500772009-12-16 12:17:52 +00001244/// Builds an expression which might be an implicit member expression.
John McCalldadc5752010-08-24 06:29:42 +00001245ExprResult
John McCall57500772009-12-16 12:17:52 +00001246Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1247 LookupResult &R,
1248 const TemplateArgumentListInfo *TemplateArgs) {
1249 switch (ClassifyImplicitMemberAccess(*this, R)) {
1250 case IMA_Instance:
1251 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1252
1253 case IMA_AnonymousMember:
1254 assert(R.isSingleResult());
1255 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1256 R.getAsSingle<FieldDecl>());
1257
1258 case IMA_Mixed:
1259 case IMA_Mixed_Unrelated:
1260 case IMA_Unresolved:
1261 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1262
1263 case IMA_Static:
1264 case IMA_Mixed_StaticContext:
1265 case IMA_Unresolved_StaticContext:
1266 if (TemplateArgs)
1267 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1268 return BuildDeclarationNameExpr(SS, R, false);
1269
1270 case IMA_Error_StaticContext:
1271 case IMA_Error_Unrelated:
1272 DiagnoseInstanceReference(*this, SS, R);
1273 return ExprError();
1274 }
1275
1276 llvm_unreachable("unexpected instance member access kind");
1277 return ExprError();
1278}
1279
John McCall10eae182009-11-30 22:42:35 +00001280/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1281/// declaration name, generally during template instantiation.
1282/// There's a large number of things which don't need to be done along
1283/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001284ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001285Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001286 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001287 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001288 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001289 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001290
John McCall0b66eb32010-05-01 00:40:08 +00001291 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001292 return ExprError();
1293
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001294 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001295 LookupQualifiedName(R, DC);
1296
1297 if (R.isAmbiguous())
1298 return ExprError();
1299
1300 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001301 Diag(NameInfo.getLoc(), diag::err_no_member)
1302 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001303 return ExprError();
1304 }
1305
1306 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1307}
1308
1309/// LookupInObjCMethod - The parser has read a name in, and Sema has
1310/// detected that we're currently inside an ObjC method. Perform some
1311/// additional lookup.
1312///
1313/// Ideally, most of this would be done by lookup, but there's
1314/// actually quite a lot of extra work involved.
1315///
1316/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001317ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001318Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001319 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001320 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001321 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001322
John McCalle66edc12009-11-24 19:00:30 +00001323 // There are two cases to handle here. 1) scoped lookup could have failed,
1324 // in which case we should look for an ivar. 2) scoped lookup could have
1325 // found a decl, but that decl is outside the current instance method (i.e.
1326 // a global variable). In these two cases, we do a lookup for an ivar with
1327 // this name, if the lookup sucedes, we replace it our current decl.
1328
1329 // If we're in a class method, we don't normally want to look for
1330 // ivars. But if we don't find anything else, and there's an
1331 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001332 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001333
1334 bool LookForIvars;
1335 if (Lookup.empty())
1336 LookForIvars = true;
1337 else if (IsClassMethod)
1338 LookForIvars = false;
1339 else
1340 LookForIvars = (Lookup.isSingleResult() &&
1341 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001342 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001343 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001344 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001345 ObjCInterfaceDecl *ClassDeclared;
1346 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1347 // Diagnose using an ivar in a class method.
1348 if (IsClassMethod)
1349 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1350 << IV->getDeclName());
1351
1352 // If we're referencing an invalid decl, just return this as a silent
1353 // error node. The error diagnostic was already emitted on the decl.
1354 if (IV->isInvalidDecl())
1355 return ExprError();
1356
1357 // Check if referencing a field with __attribute__((deprecated)).
1358 if (DiagnoseUseOfDecl(IV, Loc))
1359 return ExprError();
1360
1361 // Diagnose the use of an ivar outside of the declaring class.
1362 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1363 ClassDeclared != IFace)
1364 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1365
1366 // FIXME: This should use a new expr for a direct reference, don't
1367 // turn this into Self->ivar, just return a BareIVarExpr or something.
1368 IdentifierInfo &II = Context.Idents.get("self");
1369 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001370 SelfName.setIdentifier(&II, SourceLocation());
John McCalle66edc12009-11-24 19:00:30 +00001371 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001372 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
John McCalle66edc12009-11-24 19:00:30 +00001373 SelfName, false, false);
1374 MarkDeclarationReferenced(Loc, IV);
1375 return Owned(new (Context)
1376 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1377 SelfExpr.takeAs<Expr>(), true, true));
1378 }
Chris Lattner87313662010-04-12 05:10:17 +00001379 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001380 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001381 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001382 ObjCInterfaceDecl *ClassDeclared;
1383 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1384 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1385 IFace == ClassDeclared)
1386 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1387 }
1388 }
1389
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001390 if (Lookup.empty() && II && AllowBuiltinCreation) {
1391 // FIXME. Consolidate this with similar code in LookupName.
1392 if (unsigned BuiltinID = II->getBuiltinID()) {
1393 if (!(getLangOptions().CPlusPlus &&
1394 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1395 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1396 S, Lookup.isForRedeclaration(),
1397 Lookup.getNameLoc());
1398 if (D) Lookup.addDecl(D);
1399 }
1400 }
1401 }
John McCalle66edc12009-11-24 19:00:30 +00001402 // Sentinel value saying that we didn't do anything special.
1403 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001404}
John McCalld14a8642009-11-21 08:51:07 +00001405
John McCall16df1e52010-03-30 21:47:33 +00001406/// \brief Cast a base object to a member's actual type.
1407///
1408/// Logically this happens in three phases:
1409///
1410/// * First we cast from the base type to the naming class.
1411/// The naming class is the class into which we were looking
1412/// when we found the member; it's the qualifier type if a
1413/// qualifier was provided, and otherwise it's the base type.
1414///
1415/// * Next we cast from the naming class to the declaring class.
1416/// If the member we found was brought into a class's scope by
1417/// a using declaration, this is that class; otherwise it's
1418/// the class declaring the member.
1419///
1420/// * Finally we cast from the declaring class to the "true"
1421/// declaring class of the member. This conversion does not
1422/// obey access control.
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001423bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001424Sema::PerformObjectMemberConversion(Expr *&From,
1425 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001426 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001427 NamedDecl *Member) {
1428 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1429 if (!RD)
1430 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001431
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001432 QualType DestRecordType;
1433 QualType DestType;
1434 QualType FromRecordType;
1435 QualType FromType = From->getType();
1436 bool PointerConversions = false;
1437 if (isa<FieldDecl>(Member)) {
1438 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001439
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001440 if (FromType->getAs<PointerType>()) {
1441 DestType = Context.getPointerType(DestRecordType);
1442 FromRecordType = FromType->getPointeeType();
1443 PointerConversions = true;
1444 } else {
1445 DestType = DestRecordType;
1446 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001447 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001448 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1449 if (Method->isStatic())
1450 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001451
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001452 DestType = Method->getThisType(Context);
1453 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001454
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001455 if (FromType->getAs<PointerType>()) {
1456 FromRecordType = FromType->getPointeeType();
1457 PointerConversions = true;
1458 } else {
1459 FromRecordType = FromType;
1460 DestType = DestRecordType;
1461 }
1462 } else {
1463 // No conversion necessary.
1464 return false;
1465 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001466
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001467 if (DestType->isDependentType() || FromType->isDependentType())
1468 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001469
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001470 // If the unqualified types are the same, no conversion is necessary.
1471 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1472 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001473
John McCall16df1e52010-03-30 21:47:33 +00001474 SourceRange FromRange = From->getSourceRange();
1475 SourceLocation FromLoc = FromRange.getBegin();
1476
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001477 ImplicitCastExpr::ResultCategory Category = CastCategory(From);
1478
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001479 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001480 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001481 // class name.
1482 //
1483 // If the member was a qualified name and the qualified referred to a
1484 // specific base subobject type, we'll cast to that intermediate type
1485 // first and then to the object in which the member is declared. That allows
1486 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1487 //
1488 // class Base { public: int x; };
1489 // class Derived1 : public Base { };
1490 // class Derived2 : public Base { };
1491 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1492 //
1493 // void VeryDerived::f() {
1494 // x = 17; // error: ambiguous base subobjects
1495 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1496 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001497 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00001498 QualType QType = QualType(Qualifier->getAsType(), 0);
1499 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1500 assert(QType->isRecordType() && "lookup done with non-record type");
1501
1502 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1503
1504 // In C++98, the qualifier type doesn't actually have to be a base
1505 // type of the object type, in which case we just ignore it.
1506 // Otherwise build the appropriate casts.
1507 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00001508 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001509 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001510 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00001511 return true;
1512
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001513 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00001514 QType = Context.getPointerType(QType);
John McCalld9c7c6562010-03-30 23:58:03 +00001515 ImpCastExprToType(From, QType, CastExpr::CK_UncheckedDerivedToBase,
John McCallcf142162010-08-07 06:22:56 +00001516 Category, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00001517
1518 FromType = QType;
1519 FromRecordType = QRecordType;
1520
1521 // If the qualifier type was the same as the destination type,
1522 // we're done.
1523 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1524 return false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001525 }
1526 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001527
John McCall16df1e52010-03-30 21:47:33 +00001528 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001529
John McCall16df1e52010-03-30 21:47:33 +00001530 // If we actually found the member through a using declaration, cast
1531 // down to the using declaration's type.
1532 //
1533 // Pointer equality is fine here because only one declaration of a
1534 // class ever has member declarations.
1535 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
1536 assert(isa<UsingShadowDecl>(FoundDecl));
1537 QualType URecordType = Context.getTypeDeclType(
1538 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
1539
1540 // We only need to do this if the naming-class to declaring-class
1541 // conversion is non-trivial.
1542 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
1543 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00001544 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001545 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001546 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00001547 return true;
Alexis Huntc46382e2010-04-28 23:02:27 +00001548
John McCall16df1e52010-03-30 21:47:33 +00001549 QualType UType = URecordType;
1550 if (PointerConversions)
1551 UType = Context.getPointerType(UType);
John McCalld9c7c6562010-03-30 23:58:03 +00001552 ImpCastExprToType(From, UType, CastExpr::CK_UncheckedDerivedToBase,
John McCallcf142162010-08-07 06:22:56 +00001553 Category, &BasePath);
John McCall16df1e52010-03-30 21:47:33 +00001554 FromType = UType;
1555 FromRecordType = URecordType;
1556 }
1557
1558 // We don't do access control for the conversion from the
1559 // declaring class to the true declaring class.
1560 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001561 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001562
John McCallcf142162010-08-07 06:22:56 +00001563 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00001564 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
1565 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00001566 IgnoreAccess))
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001567 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001568
John McCalld9c7c6562010-03-30 23:58:03 +00001569 ImpCastExprToType(From, DestType, CastExpr::CK_UncheckedDerivedToBase,
John McCallcf142162010-08-07 06:22:56 +00001570 Category, &BasePath);
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001571 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001572}
Douglas Gregor3256d042009-06-30 15:47:41 +00001573
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001574/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00001575static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00001576 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalla8ae2222010-04-06 21:38:20 +00001577 DeclAccessPair FoundDecl,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001578 const DeclarationNameInfo &MemberNameInfo,
1579 QualType Ty,
John McCalle66edc12009-11-24 19:00:30 +00001580 const TemplateArgumentListInfo *TemplateArgs = 0) {
1581 NestedNameSpecifier *Qualifier = 0;
1582 SourceRange QualifierRange;
John McCall10eae182009-11-30 22:42:35 +00001583 if (SS.isSet()) {
1584 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1585 QualifierRange = SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001586 }
Mike Stump11289f42009-09-09 15:08:12 +00001587
John McCalle66edc12009-11-24 19:00:30 +00001588 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001589 Member, FoundDecl, MemberNameInfo,
1590 TemplateArgs, Ty);
Douglas Gregorc1905232009-08-26 22:36:53 +00001591}
1592
John McCall2d74de92009-12-01 22:10:20 +00001593/// Builds an implicit member access expression. The current context
1594/// is known to be an instance method, and the given unqualified lookup
1595/// set is known to contain only instance members, at least one of which
1596/// is from an appropriate type.
John McCalldadc5752010-08-24 06:29:42 +00001597ExprResult
John McCall2d74de92009-12-01 22:10:20 +00001598Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1599 LookupResult &R,
1600 const TemplateArgumentListInfo *TemplateArgs,
1601 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00001602 assert(!R.empty() && !R.isAmbiguous());
1603
John McCalld14a8642009-11-21 08:51:07 +00001604 SourceLocation Loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00001605
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001606 // We may have found a field within an anonymous union or struct
1607 // (C++ [class.union]).
Douglas Gregor6493d9c2009-10-22 07:08:30 +00001608 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCalle66edc12009-11-24 19:00:30 +00001609 // FIXME: template-ids inside anonymous structs?
John McCall10eae182009-11-30 22:42:35 +00001610 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001611 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCallb53bbd42009-11-22 01:44:31 +00001612 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001613
John McCall2d74de92009-12-01 22:10:20 +00001614 // If this is known to be an instance access, go ahead and build a
1615 // 'this' expression now.
John McCall87fe5d52010-05-20 01:18:31 +00001616 DeclContext *DC = getFunctionLevelDeclContext();
1617 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCall2d74de92009-12-01 22:10:20 +00001618 Expr *This = 0; // null signifies implicit access
1619 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00001620 SourceLocation Loc = R.getNameLoc();
1621 if (SS.getRange().isValid())
1622 Loc = SS.getRange().getBegin();
1623 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00001624 }
1625
John McCallb268a282010-08-23 23:25:46 +00001626 return BuildMemberReferenceExpr(This, ThisType,
John McCall2d74de92009-12-01 22:10:20 +00001627 /*OpLoc*/ SourceLocation(),
1628 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00001629 SS,
1630 /*FirstQualifierInScope*/ 0,
1631 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00001632}
1633
John McCalle66edc12009-11-24 19:00:30 +00001634bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001635 const LookupResult &R,
1636 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00001637 // Only when used directly as the postfix-expression of a call.
1638 if (!HasTrailingLParen)
1639 return false;
1640
1641 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00001642 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00001643 return false;
1644
1645 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00001646 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00001647 return false;
1648
1649 // Turn off ADL when we find certain kinds of declarations during
1650 // normal lookup:
1651 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1652 NamedDecl *D = *I;
1653
1654 // C++0x [basic.lookup.argdep]p3:
1655 // -- a declaration of a class member
1656 // Since using decls preserve this property, we check this on the
1657 // original decl.
John McCall57500772009-12-16 12:17:52 +00001658 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00001659 return false;
1660
1661 // C++0x [basic.lookup.argdep]p3:
1662 // -- a block-scope function declaration that is not a
1663 // using-declaration
1664 // NOTE: we also trigger this for function templates (in fact, we
1665 // don't check the decl type at all, since all other decl types
1666 // turn off ADL anyway).
1667 if (isa<UsingShadowDecl>(D))
1668 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1669 else if (D->getDeclContext()->isFunctionOrMethod())
1670 return false;
1671
1672 // C++0x [basic.lookup.argdep]p3:
1673 // -- a declaration that is neither a function or a function
1674 // template
1675 // And also for builtin functions.
1676 if (isa<FunctionDecl>(D)) {
1677 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1678
1679 // But also builtin functions.
1680 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1681 return false;
1682 } else if (!isa<FunctionTemplateDecl>(D))
1683 return false;
1684 }
1685
1686 return true;
1687}
1688
1689
John McCalld14a8642009-11-21 08:51:07 +00001690/// Diagnoses obvious problems with the use of the given declaration
1691/// as an expression. This is only actually called for lookups that
1692/// were not overloaded, and it doesn't promise that the declaration
1693/// will in fact be used.
1694static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1695 if (isa<TypedefDecl>(D)) {
1696 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1697 return true;
1698 }
1699
1700 if (isa<ObjCInterfaceDecl>(D)) {
1701 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1702 return true;
1703 }
1704
1705 if (isa<NamespaceDecl>(D)) {
1706 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1707 return true;
1708 }
1709
1710 return false;
1711}
1712
John McCalldadc5752010-08-24 06:29:42 +00001713ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001714Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001715 LookupResult &R,
1716 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00001717 // If this is a single, fully-resolved result and we don't need ADL,
1718 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00001719 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001720 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
1721 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00001722
1723 // We only need to check the declaration if there's exactly one
1724 // result, because in the overloaded case the results can only be
1725 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00001726 if (R.isSingleResult() &&
1727 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00001728 return ExprError();
1729
John McCall58cc69d2010-01-27 01:50:18 +00001730 // Otherwise, just build an unresolved lookup expression. Suppress
1731 // any lookup-related diagnostics; we'll hash these out later, when
1732 // we've picked a target.
1733 R.suppressDiagnostics();
1734
John McCalle66edc12009-11-24 19:00:30 +00001735 bool Dependent
1736 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCalld14a8642009-11-21 08:51:07 +00001737 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001738 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001739 (NestedNameSpecifier*) SS.getScopeRep(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001740 SS.getRange(), R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00001741 NeedsADL, R.isOverloadedResult(),
1742 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00001743
1744 return Owned(ULE);
1745}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001746
John McCalld14a8642009-11-21 08:51:07 +00001747
1748/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00001749ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001750Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001751 const DeclarationNameInfo &NameInfo,
1752 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00001753 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00001754 assert(!isa<FunctionTemplateDecl>(D) &&
1755 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00001756
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001757 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001758 if (CheckDeclInExpr(*this, Loc, D))
1759 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00001760
Douglas Gregore7488b92009-12-01 16:58:18 +00001761 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1762 // Specifically diagnose references to class templates that are missing
1763 // a template argument list.
1764 Diag(Loc, diag::err_template_decl_ref)
1765 << Template << SS.getRange();
1766 Diag(Template->getLocation(), diag::note_template_decl_here);
1767 return ExprError();
1768 }
1769
1770 // Make sure that we're referring to a value.
1771 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1772 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001773 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00001774 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00001775 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00001776 return ExprError();
1777 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001778
Douglas Gregor171c45a2009-02-18 21:56:37 +00001779 // Check whether this declaration can be used. Note that we suppress
1780 // this check when we're going to perform argument-dependent lookup
1781 // on this function name, because this might not be the function
1782 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00001783 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00001784 return ExprError();
1785
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001786 // Only create DeclRefExpr's for valid Decl's.
1787 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001788 return ExprError();
1789
Chris Lattner2a9d9892008-10-20 05:16:36 +00001790 // If the identifier reference is inside a block, and it refers to a value
1791 // that is outside the block, create a BlockDeclRefExpr instead of a
1792 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1793 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001794 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00001795 // We do not do this for things like enum constants, global variables, etc,
1796 // as they do not get snapshotted.
1797 //
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001798 if (getCurBlock() &&
Douglas Gregor9a28e842010-03-01 23:15:13 +00001799 ShouldSnapshotBlockValueReference(*this, getCurBlock(), VD)) {
Mike Stump7dafa0d2010-01-05 02:56:35 +00001800 if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
1801 Diag(Loc, diag::err_ref_vm_type);
1802 Diag(D->getLocation(), diag::note_declared_at);
1803 return ExprError();
1804 }
1805
Fariborz Jahanianfa24e102010-03-16 23:39:51 +00001806 if (VD->getType()->isArrayType()) {
Mike Stump8971a862010-01-05 03:10:36 +00001807 Diag(Loc, diag::err_ref_array_type);
1808 Diag(D->getLocation(), diag::note_declared_at);
1809 return ExprError();
1810 }
1811
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001812 MarkDeclarationReferenced(Loc, VD);
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001813 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001814 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001815 if (VD->getAttr<BlocksAttr>())
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001816 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001817 // This is to record that a 'const' was actually synthesize and added.
1818 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001819 // Variable will be bound by-copy, make it const within the closure.
Mike Stump11289f42009-09-09 15:08:12 +00001820
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001821 ExprTy.addConst();
Fariborz Jahanian70c0b082010-07-12 17:26:57 +00001822 QualType T = VD->getType();
Fariborz Jahanianea882cd2010-06-04 21:35:44 +00001823 BlockDeclRefExpr *BDRE = new (Context) BlockDeclRefExpr(VD,
1824 ExprTy, Loc, false,
Fariborz Jahanianc289bce2010-07-12 18:12:03 +00001825 constAdded);
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00001826 if (getLangOptions().CPlusPlus) {
1827 if (!T->isDependentType() && !T->isReferenceType()) {
1828 Expr *E = new (Context)
1829 DeclRefExpr(const_cast<ValueDecl*>(BDRE->getDecl()), T,
1830 SourceLocation());
Fariborz Jahanianea882cd2010-06-04 21:35:44 +00001831
John McCalldadc5752010-08-24 06:29:42 +00001832 ExprResult Res = PerformCopyInitialization(
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00001833 InitializedEntity::InitializeBlock(VD->getLocation(),
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00001834 T, false),
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00001835 SourceLocation(),
1836 Owned(E));
1837 if (!Res.isInvalid()) {
John McCallb268a282010-08-23 23:25:46 +00001838 Res = MaybeCreateCXXExprWithTemporaries(Res.get());
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00001839 Expr *Init = Res.takeAs<Expr>();
1840 BDRE->setCopyConstructorExpr(Init);
1841 }
Fariborz Jahanianea882cd2010-06-04 21:35:44 +00001842 }
1843 }
1844 return Owned(BDRE);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001845 }
1846 // If this reference is not in a block or if the referenced variable is
1847 // within the block, create a normal DeclRefExpr.
Douglas Gregor4619e432008-12-05 23:32:09 +00001848
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001849 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
1850 NameInfo, &SS);
Chris Lattner17ed4872006-11-20 04:58:19 +00001851}
Chris Lattnere168f762006-11-10 05:29:30 +00001852
John McCalldadc5752010-08-24 06:29:42 +00001853ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Sebastian Redlffbcf962009-01-18 18:53:16 +00001854 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00001855 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001856
Chris Lattnere168f762006-11-10 05:29:30 +00001857 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00001858 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00001859 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1860 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1861 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00001862 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00001863
Chris Lattnera81a0272008-01-12 08:14:25 +00001864 // Pre-defined identifiers are of type char[x], where x is the length of the
1865 // string.
Mike Stump11289f42009-09-09 15:08:12 +00001866
Anders Carlsson2fb08242009-09-08 18:24:21 +00001867 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00001868 if (!currentDecl && getCurBlock())
1869 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00001870 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001871 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00001872 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001873 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001874
Anders Carlsson0b209a82009-09-11 01:22:35 +00001875 QualType ResTy;
1876 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1877 ResTy = Context.DependentTy;
1878 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00001879 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001880
Anders Carlsson0b209a82009-09-11 01:22:35 +00001881 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00001882 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00001883 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1884 }
Steve Narofff6009ed2009-01-21 00:14:39 +00001885 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00001886}
1887
John McCalldadc5752010-08-24 06:29:42 +00001888ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001889 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00001890 bool Invalid = false;
1891 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
1892 if (Invalid)
1893 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001894
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001895 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
1896 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00001897 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001898 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00001899
Chris Lattnerc3847ba2009-12-30 21:19:39 +00001900 QualType Ty;
1901 if (!getLangOptions().CPlusPlus)
1902 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
1903 else if (Literal.isWide())
1904 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00001905 else if (Literal.isMultiChar())
1906 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00001907 else
1908 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00001909
Sebastian Redl20614a72009-01-20 22:23:13 +00001910 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1911 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00001912 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00001913}
1914
John McCalldadc5752010-08-24 06:29:42 +00001915ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00001916 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00001917 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1918 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00001919 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00001920 unsigned IntSize = Context.Target.getIntWidth();
Steve Narofff6009ed2009-01-21 00:14:39 +00001921 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00001922 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00001923 }
Ted Kremeneke9814182009-01-13 23:19:12 +00001924
Chris Lattner23b7eb62007-06-15 23:05:46 +00001925 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00001926 // Add padding so that NumericLiteralParser can overread by one character.
1927 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00001928 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00001929
Chris Lattner67ca9252007-05-21 01:08:44 +00001930 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00001931 bool Invalid = false;
1932 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
1933 if (Invalid)
1934 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001935
Mike Stump11289f42009-09-09 15:08:12 +00001936 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00001937 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00001938 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001939 return ExprError();
1940
Chris Lattner1c20a172007-08-26 03:42:43 +00001941 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001942
Chris Lattner1c20a172007-08-26 03:42:43 +00001943 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001944 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001945 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001946 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001947 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001948 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001949 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00001950 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001951
1952 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1953
John McCall53b93a02009-12-24 09:08:04 +00001954 using llvm::APFloat;
1955 APFloat Val(Format);
1956
1957 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00001958
1959 // Overflow is always an error, but underflow is only an error if
1960 // we underflowed to zero (APFloat reports denormals as underflow).
1961 if ((result & APFloat::opOverflow) ||
1962 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00001963 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001964 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00001965 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00001966 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00001967 APFloat::getLargest(Format).toString(buffer);
1968 } else {
John McCall62abc942010-02-26 23:35:57 +00001969 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00001970 APFloat::getSmallest(Format).toString(buffer);
1971 }
1972
1973 Diag(Tok.getLocation(), diagnostic)
1974 << Ty
1975 << llvm::StringRef(buffer.data(), buffer.size());
1976 }
1977
1978 bool isExact = (result == APFloat::opOK);
Chris Lattnere4edb8e2009-06-29 17:34:55 +00001979 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00001980
Chris Lattner1c20a172007-08-26 03:42:43 +00001981 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00001982 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00001983 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001984 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00001985
Neil Boothac582c52007-08-29 22:00:19 +00001986 // long long is a C99 feature.
1987 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00001988 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00001989 Diag(Tok.getLocation(), diag::ext_longlong);
1990
Chris Lattner67ca9252007-05-21 01:08:44 +00001991 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00001992 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001993
Chris Lattner67ca9252007-05-21 01:08:44 +00001994 if (Literal.GetIntegerValue(ResultVal)) {
1995 // If this value didn't fit into uintmax_t, warn and force to ull.
1996 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001997 Ty = Context.UnsignedLongLongTy;
1998 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00001999 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002000 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002001 // If this value fits into a ULL, try to figure out what else it fits into
2002 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002003
Chris Lattner67ca9252007-05-21 01:08:44 +00002004 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2005 // be an unsigned int.
2006 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2007
2008 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002009 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002010 if (!Literal.isLong && !Literal.isLongLong) {
2011 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002012 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002013
Chris Lattner67ca9252007-05-21 01:08:44 +00002014 // Does it fit in a unsigned int?
2015 if (ResultVal.isIntN(IntSize)) {
2016 // Does it fit in a signed int?
2017 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002018 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002019 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002020 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002021 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002022 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002023 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002024
Chris Lattner67ca9252007-05-21 01:08:44 +00002025 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002026 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002027 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002028
Chris Lattner67ca9252007-05-21 01:08:44 +00002029 // Does it fit in a unsigned long?
2030 if (ResultVal.isIntN(LongSize)) {
2031 // Does it fit in a signed long?
2032 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002033 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002034 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002035 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002036 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002037 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002038 }
2039
Chris Lattner67ca9252007-05-21 01:08:44 +00002040 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002041 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002042 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002043
Chris Lattner67ca9252007-05-21 01:08:44 +00002044 // Does it fit in a unsigned long long?
2045 if (ResultVal.isIntN(LongLongSize)) {
2046 // Does it fit in a signed long long?
2047 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002048 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002049 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002050 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002051 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002052 }
2053 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002054
Chris Lattner67ca9252007-05-21 01:08:44 +00002055 // If we still couldn't decide a type, we probably have something that
2056 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002057 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002058 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002059 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002060 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002061 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002062
Chris Lattner55258cf2008-05-09 05:59:00 +00002063 if (ResultVal.getBitWidth() != Width)
2064 ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002065 }
Sebastian Redl20614a72009-01-20 22:23:13 +00002066 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002067 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002068
Chris Lattner1c20a172007-08-26 03:42:43 +00002069 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2070 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002071 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002072 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002073
2074 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002075}
2076
John McCalldadc5752010-08-24 06:29:42 +00002077ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002078 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002079 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002080 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002081}
2082
Steve Naroff71b59a92007-06-04 22:22:31 +00002083/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00002084/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002085bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl6f282892008-11-11 17:56:53 +00002086 SourceLocation OpLoc,
2087 const SourceRange &ExprRange,
2088 bool isSizeof) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002089 if (exprType->isDependentType())
2090 return false;
2091
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002092 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2093 // the result is the size of the referenced type."
2094 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2095 // result shall be the alignment of the referenced type."
2096 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2097 exprType = Ref->getPointeeType();
2098
Steve Naroff043d45d2007-05-15 02:32:35 +00002099 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00002100 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002101 // alignof(function) is allowed as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00002102 if (isSizeof)
2103 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2104 return false;
2105 }
Mike Stump11289f42009-09-09 15:08:12 +00002106
Chris Lattner62975a72009-04-24 00:30:45 +00002107 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00002108 if (exprType->isVoidType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002109 Diag(OpLoc, diag::ext_sizeof_void_type)
2110 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00002111 return false;
2112 }
Mike Stump11289f42009-09-09 15:08:12 +00002113
Chris Lattner62975a72009-04-24 00:30:45 +00002114 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002115 PDiag(diag::err_sizeof_alignof_incomplete_type)
2116 << int(!isSizeof) << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002117 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002118
Chris Lattner62975a72009-04-24 00:30:45 +00002119 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCall8b07ec22010-05-15 11:32:37 +00002120 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002121 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002122 << exprType << isSizeof << ExprRange;
2123 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00002124 }
Mike Stump11289f42009-09-09 15:08:12 +00002125
Douglas Gregor27887822010-05-23 19:43:23 +00002126 if (Context.hasSameUnqualifiedType(exprType, Context.OverloadTy)) {
2127 Diag(OpLoc, diag::err_sizeof_alignof_overloaded_function_type)
2128 << !isSizeof << ExprRange;
2129 return true;
2130 }
2131
Chris Lattner62975a72009-04-24 00:30:45 +00002132 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002133}
2134
Chris Lattner8dff0172009-01-24 20:17:12 +00002135bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
2136 const SourceRange &ExprRange) {
2137 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002138
Mike Stump11289f42009-09-09 15:08:12 +00002139 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002140 if (isa<DeclRefExpr>(E))
2141 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002142
2143 // Cannot know anything else if the expression is dependent.
2144 if (E->isTypeDependent())
2145 return false;
2146
Douglas Gregor71235ec2009-05-02 02:18:30 +00002147 if (E->getBitField()) {
2148 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
2149 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002150 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002151
2152 // Alignment of a field access is always okay, so long as it isn't a
2153 // bit-field.
2154 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002155 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002156 return false;
2157
Chris Lattner8dff0172009-01-24 20:17:12 +00002158 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
2159}
2160
Douglas Gregor0950e412009-03-13 21:01:28 +00002161/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002162ExprResult
John McCallbcd03502009-12-07 02:54:59 +00002163Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall4c98fd82009-11-04 07:28:41 +00002164 SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00002165 bool isSizeOf, SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002166 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002167 return ExprError();
2168
John McCallbcd03502009-12-07 02:54:59 +00002169 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002170
Douglas Gregor0950e412009-03-13 21:01:28 +00002171 if (!T->isDependentType() &&
2172 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2173 return ExprError();
2174
2175 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCallbcd03502009-12-07 02:54:59 +00002176 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregor0950e412009-03-13 21:01:28 +00002177 Context.getSizeType(), OpLoc,
2178 R.getEnd()));
2179}
2180
2181/// \brief Build a sizeof or alignof expression given an expression
2182/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002183ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00002184Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00002185 bool isSizeOf, SourceRange R) {
2186 // Verify that the operand is valid.
2187 bool isInvalid = false;
2188 if (E->isTypeDependent()) {
2189 // Delay type-checking for type-dependent expressions.
2190 } else if (!isSizeOf) {
2191 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002192 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00002193 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2194 isInvalid = true;
2195 } else {
2196 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2197 }
2198
2199 if (isInvalid)
2200 return ExprError();
2201
2202 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2203 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2204 Context.getSizeType(), OpLoc,
2205 R.getEnd()));
2206}
2207
Sebastian Redl6f282892008-11-11 17:56:53 +00002208/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2209/// the same for @c alignof and @c __alignof
2210/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002211ExprResult
Sebastian Redl6f282892008-11-11 17:56:53 +00002212Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2213 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002214 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002215 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002216
Sebastian Redl6f282892008-11-11 17:56:53 +00002217 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002218 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002219 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
John McCallbcd03502009-12-07 02:54:59 +00002220 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002221 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002222
Douglas Gregor0950e412009-03-13 21:01:28 +00002223 Expr *ArgEx = (Expr *)TyOrEx;
John McCalldadc5752010-08-24 06:29:42 +00002224 ExprResult Result
Douglas Gregor0950e412009-03-13 21:01:28 +00002225 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2226
2227 if (Result.isInvalid())
2228 DeleteExpr(ArgEx);
2229
2230 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002231}
2232
Chris Lattner709322b2009-02-17 08:12:06 +00002233QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002234 if (V->isTypeDependent())
2235 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002236
Chris Lattnere267f5d2007-08-26 05:39:26 +00002237 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00002238 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002239 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002240
Chris Lattnere267f5d2007-08-26 05:39:26 +00002241 // Otherwise they pass through real integer and floating point types here.
2242 if (V->getType()->isArithmeticType())
2243 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002244
Chris Lattnere267f5d2007-08-26 05:39:26 +00002245 // Reject anything else.
Chris Lattner709322b2009-02-17 08:12:06 +00002246 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
2247 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002248 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002249}
2250
2251
Chris Lattnere168f762006-11-10 05:29:30 +00002252
John McCalldadc5752010-08-24 06:29:42 +00002253ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002254Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002255 tok::TokenKind Kind, Expr *Input) {
Chris Lattnere168f762006-11-10 05:29:30 +00002256 UnaryOperator::Opcode Opc;
2257 switch (Kind) {
2258 default: assert(0 && "Unknown unary op!");
2259 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
2260 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
2261 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002262
John McCallb268a282010-08-23 23:25:46 +00002263 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002264}
2265
John McCalldadc5752010-08-24 06:29:42 +00002266ExprResult
John McCallb268a282010-08-23 23:25:46 +00002267Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2268 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002269 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002270 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002271 if (Result.isInvalid()) return ExprError();
2272 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002273
John McCallb268a282010-08-23 23:25:46 +00002274 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00002275
Douglas Gregor40412ac2008-11-19 17:17:41 +00002276 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002277 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002278 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
2279 Context.DependentTy, RLoc));
2280 }
2281
Mike Stump11289f42009-09-09 15:08:12 +00002282 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002283 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002284 LHSExp->getType()->isEnumeralType() ||
2285 RHSExp->getType()->isRecordType() ||
2286 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00002287 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00002288 }
2289
John McCallb268a282010-08-23 23:25:46 +00002290 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00002291}
2292
2293
John McCalldadc5752010-08-24 06:29:42 +00002294ExprResult
John McCallb268a282010-08-23 23:25:46 +00002295Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2296 Expr *Idx, SourceLocation RLoc) {
2297 Expr *LHSExp = Base;
2298 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00002299
Chris Lattner36d572b2007-07-16 00:14:47 +00002300 // Perform default conversions.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002301 if (!LHSExp->getType()->getAs<VectorType>())
2302 DefaultFunctionArrayLvalueConversion(LHSExp);
2303 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002304
Chris Lattner36d572b2007-07-16 00:14:47 +00002305 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Steve Narofff1e53692007-03-23 22:27:02 +00002306
Steve Naroffc1aadb12007-03-28 21:49:40 +00002307 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00002308 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00002309 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00002310 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00002311 Expr *BaseExpr, *IndexExpr;
2312 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002313 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2314 BaseExpr = LHSExp;
2315 IndexExpr = RHSExp;
2316 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002317 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00002318 BaseExpr = LHSExp;
2319 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002320 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002321 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00002322 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00002323 BaseExpr = RHSExp;
2324 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002325 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002326 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002327 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002328 BaseExpr = LHSExp;
2329 IndexExpr = RHSExp;
2330 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002331 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002332 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002333 // Handle the uncommon case of "123[Ptr]".
2334 BaseExpr = RHSExp;
2335 IndexExpr = LHSExp;
2336 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00002337 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00002338 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00002339 IndexExpr = RHSExp;
Nate Begemanc1bf0612009-01-18 00:45:31 +00002340
Chris Lattner36d572b2007-07-16 00:14:47 +00002341 // FIXME: need to deal with const...
2342 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002343 } else if (LHSTy->isArrayType()) {
2344 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00002345 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00002346 // wasn't promoted because of the C90 rule that doesn't
2347 // allow promoting non-lvalue arrays. Warn, then
2348 // force the promotion here.
2349 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2350 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002351 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
2352 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002353 LHSTy = LHSExp->getType();
2354
2355 BaseExpr = LHSExp;
2356 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002357 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002358 } else if (RHSTy->isArrayType()) {
2359 // Same as previous, except for 123[f().a] case
2360 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2361 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002362 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
2363 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002364 RHSTy = RHSExp->getType();
2365
2366 BaseExpr = RHSExp;
2367 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002368 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00002369 } else {
Chris Lattner003af242009-04-25 22:50:55 +00002370 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2371 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002372 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00002373 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00002374 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00002375 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2376 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00002377
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002378 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00002379 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2380 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00002381 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2382
Douglas Gregorac1fb652009-03-24 19:52:54 +00002383 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00002384 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2385 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00002386 // incomplete types are not object types.
2387 if (ResultType->isFunctionType()) {
2388 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2389 << ResultType << BaseExpr->getSourceRange();
2390 return ExprError();
2391 }
Mike Stump11289f42009-09-09 15:08:12 +00002392
Douglas Gregorac1fb652009-03-24 19:52:54 +00002393 if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00002394 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00002395 PDiag(diag::err_subscript_incomplete_type)
2396 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00002397 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002398
Chris Lattner62975a72009-04-24 00:30:45 +00002399 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00002400 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00002401 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2402 << ResultType << BaseExpr->getSourceRange();
2403 return ExprError();
2404 }
Mike Stump11289f42009-09-09 15:08:12 +00002405
Mike Stump4e1f26a2009-02-19 03:04:26 +00002406 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Narofff6009ed2009-01-21 00:14:39 +00002407 ResultType, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00002408}
2409
Steve Narofff8fd09e2007-07-27 22:15:19 +00002410QualType Sema::
Nate Begemance4d7fc2008-04-18 23:10:10 +00002411CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002412 const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00002413 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00002414 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2415 // see FIXME there.
2416 //
2417 // FIXME: This logic can be greatly simplified by splitting it along
2418 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00002419 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00002420
Steve Narofff8fd09e2007-07-27 22:15:19 +00002421 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002422 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002423
Mike Stump4e1f26a2009-02-19 03:04:26 +00002424 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00002425 // special names that indicate a subset of exactly half the elements are
2426 // to be selected.
2427 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00002428
Nate Begemanbb70bf62009-01-18 01:47:54 +00002429 // This flag determines whether or not CompName has an 's' char prefix,
2430 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00002431 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00002432
2433 // Check that we've found one of the special components, or that the component
2434 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002435 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00002436 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2437 HalvingSwizzle = true;
Nate Begemanf322eab2008-05-09 06:41:27 +00002438 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00002439 do
2440 compStr++;
2441 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begemanbb70bf62009-01-18 01:47:54 +00002442 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00002443 do
2444 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002445 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner7e152db2007-08-02 22:33:49 +00002446 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00002447
Mike Stump4e1f26a2009-02-19 03:04:26 +00002448 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00002449 // We didn't get to the end of the string. This means the component names
2450 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner3b054132008-11-19 05:08:23 +00002451 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramere8394df2010-08-11 14:47:12 +00002452 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00002453 return QualType();
2454 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002455
Nate Begemanbb70bf62009-01-18 01:47:54 +00002456 // Ensure no component accessor exceeds the width of the vector type it
2457 // operates on.
2458 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002459 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002460
2461 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00002462 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002463
2464 while (*compStr) {
2465 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2466 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2467 << baseType << SourceRange(CompLoc);
2468 return QualType();
2469 }
2470 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00002471 }
Nate Begemanf322eab2008-05-09 06:41:27 +00002472
Steve Narofff8fd09e2007-07-27 22:15:19 +00002473 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002474 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00002475 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00002476 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00002477 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00002478 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00002479 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002480 if (HexSwizzle)
2481 CompSize--;
2482
Steve Narofff8fd09e2007-07-27 22:15:19 +00002483 if (CompSize == 1)
2484 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002485
Nate Begemance4d7fc2008-04-18 23:10:10 +00002486 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00002487 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00002488 // diagostics look bad. We want extended vector types to appear built-in.
2489 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2490 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2491 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00002492 }
2493 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00002494}
2495
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002496static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00002497 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002498 const Selector &Sel,
2499 ASTContext &Context) {
Mike Stump11289f42009-09-09 15:08:12 +00002500
Anders Carlssonf571c112009-08-26 18:25:21 +00002501 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002502 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002503 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002504 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00002505
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002506 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2507 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00002508 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002509 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002510 return D;
2511 }
2512 return 0;
2513}
2514
Steve Narofffb4330f2009-06-17 22:40:22 +00002515static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlssonf571c112009-08-26 18:25:21 +00002516 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002517 const Selector &Sel,
2518 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002519 // Check protocols on qualified interfaces.
2520 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00002521 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002522 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002523 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002524 GDecl = PD;
2525 break;
2526 }
2527 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002528 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002529 GDecl = OMD;
2530 break;
2531 }
2532 }
2533 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00002534 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002535 E = QIdTy->qual_end(); I != E; ++I) {
2536 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002537 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002538 if (GDecl)
2539 return GDecl;
2540 }
2541 }
2542 return GDecl;
2543}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00002544
John McCalldadc5752010-08-24 06:29:42 +00002545ExprResult
John McCallb268a282010-08-23 23:25:46 +00002546Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCall2d74de92009-12-01 22:10:20 +00002547 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002548 const CXXScopeSpec &SS,
2549 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002550 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00002551 const TemplateArgumentListInfo *TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00002552 // Even in dependent contexts, try to diagnose base expressions with
2553 // obviously wrong types, e.g.:
2554 //
2555 // T* t;
2556 // t.f;
2557 //
2558 // In Obj-C++, however, the above expression is valid, since it could be
2559 // accessing the 'f' property if T is an Obj-C interface. The extra check
2560 // allows this, while still reporting an error if T is a struct pointer.
2561 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00002562 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00002563 if (PT && (!getLangOptions().ObjC1 ||
2564 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00002565 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002566 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00002567 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00002568 return ExprError();
2569 }
2570 }
2571
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002572 assert(BaseType->isDependentType() ||
2573 NameInfo.getName().isDependentName() ||
Douglas Gregor41f90302010-04-12 20:54:26 +00002574 isDependentScopeSpecifier(SS));
John McCall10eae182009-11-30 22:42:35 +00002575
2576 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2577 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00002578 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00002579 IsArrow, OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002580 SS.getScopeRep(),
John McCall10eae182009-11-30 22:42:35 +00002581 SS.getRange(),
2582 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002583 NameInfo, TemplateArgs));
John McCall10eae182009-11-30 22:42:35 +00002584}
2585
2586/// We know that the given qualified member reference points only to
2587/// declarations which do not belong to the static type of the base
2588/// expression. Diagnose the problem.
2589static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2590 Expr *BaseExpr,
2591 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00002592 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002593 const LookupResult &R) {
John McCallcd4b4772009-12-02 03:53:29 +00002594 // If this is an implicit member access, use a different set of
2595 // diagnostics.
2596 if (!BaseExpr)
2597 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall10eae182009-11-30 22:42:35 +00002598
John McCall1e67dd62010-04-27 01:43:38 +00002599 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_of_unrelated)
2600 << SS.getRange() << R.getRepresentativeDecl() << BaseType;
John McCall10eae182009-11-30 22:42:35 +00002601}
2602
2603// Check whether the declarations we found through a nested-name
2604// specifier in a member expression are actually members of the base
2605// type. The restriction here is:
2606//
2607// C++ [expr.ref]p2:
2608// ... In these cases, the id-expression shall name a
2609// member of the class or of one of its base classes.
2610//
2611// So it's perfectly legitimate for the nested-name specifier to name
2612// an unrelated class, and for us to find an overload set including
2613// decls from classes which are not superclasses, as long as the decl
2614// we actually pick through overload resolution is from a superclass.
2615bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2616 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00002617 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002618 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00002619 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2620 if (!BaseRT) {
2621 // We can't check this yet because the base type is still
2622 // dependent.
2623 assert(BaseType->isDependentType());
2624 return false;
2625 }
2626 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00002627
2628 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00002629 // If this is an implicit member reference and we find a
2630 // non-instance member, it's not an error.
John McCalla8ae2222010-04-06 21:38:20 +00002631 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCall2d74de92009-12-01 22:10:20 +00002632 return false;
John McCall10eae182009-11-30 22:42:35 +00002633
John McCall2d74de92009-12-01 22:10:20 +00002634 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman75300492010-07-27 20:51:02 +00002635 DeclContext *DC = (*I)->getDeclContext();
2636 while (DC->isTransparentContext())
2637 DC = DC->getParent();
John McCall2d74de92009-12-01 22:10:20 +00002638
Douglas Gregora9c3e822010-07-28 22:27:52 +00002639 if (!DC->isRecord())
2640 continue;
2641
John McCall2d74de92009-12-01 22:10:20 +00002642 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman75300492010-07-27 20:51:02 +00002643 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCall2d74de92009-12-01 22:10:20 +00002644
2645 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2646 return false;
2647 }
2648
John McCallcd4b4772009-12-02 03:53:29 +00002649 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCall2d74de92009-12-01 22:10:20 +00002650 return true;
2651}
2652
2653static bool
2654LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2655 SourceRange BaseRange, const RecordType *RTy,
John McCalle9cccd82010-06-16 08:42:20 +00002656 SourceLocation OpLoc, CXXScopeSpec &SS,
2657 bool HasTemplateArgs) {
John McCall2d74de92009-12-01 22:10:20 +00002658 RecordDecl *RDecl = RTy->getDecl();
2659 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor89336232010-03-29 23:34:08 +00002660 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCall2d74de92009-12-01 22:10:20 +00002661 << BaseRange))
2662 return true;
2663
John McCalle9cccd82010-06-16 08:42:20 +00002664 if (HasTemplateArgs) {
2665 // LookupTemplateName doesn't expect these both to exist simultaneously.
2666 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
2667
2668 bool MOUS;
2669 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
2670 return false;
2671 }
2672
John McCall2d74de92009-12-01 22:10:20 +00002673 DeclContext *DC = RDecl;
2674 if (SS.isSet()) {
2675 // If the member name was a qualified-id, look into the
2676 // nested-name-specifier.
2677 DC = SemaRef.computeDeclContext(SS, false);
2678
John McCall0b66eb32010-05-01 00:40:08 +00002679 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCallcd4b4772009-12-02 03:53:29 +00002680 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2681 << SS.getRange() << DC;
2682 return true;
2683 }
2684
John McCall2d74de92009-12-01 22:10:20 +00002685 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002686
John McCall2d74de92009-12-01 22:10:20 +00002687 if (!isa<TypeDecl>(DC)) {
2688 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2689 << DC << SS.getRange();
2690 return true;
John McCall10eae182009-11-30 22:42:35 +00002691 }
2692 }
2693
John McCall2d74de92009-12-01 22:10:20 +00002694 // The record definition is complete, now look up the member.
2695 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00002696
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002697 if (!R.empty())
2698 return false;
2699
2700 // We didn't find anything with the given name, so try to correct
2701 // for typos.
2702 DeclarationName Name = R.getLookupName();
Alexis Huntc46382e2010-04-28 23:02:27 +00002703 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002704 !R.empty() &&
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002705 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
2706 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
2707 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00002708 << FixItHint::CreateReplacement(R.getNameLoc(),
2709 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00002710 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
2711 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
2712 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002713 return false;
2714 } else {
2715 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002716 R.setLookupName(Name);
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002717 }
2718
John McCall10eae182009-11-30 22:42:35 +00002719 return false;
2720}
2721
John McCalldadc5752010-08-24 06:29:42 +00002722ExprResult
John McCallb268a282010-08-23 23:25:46 +00002723Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00002724 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002725 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002726 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002727 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00002728 const TemplateArgumentListInfo *TemplateArgs) {
John McCallcd4b4772009-12-02 03:53:29 +00002729 if (BaseType->isDependentType() ||
2730 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallb268a282010-08-23 23:25:46 +00002731 return ActOnDependentMemberExpr(Base, BaseType,
John McCall10eae182009-11-30 22:42:35 +00002732 IsArrow, OpLoc,
2733 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002734 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002735
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002736 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00002737
John McCall2d74de92009-12-01 22:10:20 +00002738 // Implicit member accesses.
2739 if (!Base) {
2740 QualType RecordTy = BaseType;
2741 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2742 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2743 RecordTy->getAs<RecordType>(),
John McCalle9cccd82010-06-16 08:42:20 +00002744 OpLoc, SS, TemplateArgs != 0))
John McCall2d74de92009-12-01 22:10:20 +00002745 return ExprError();
2746
2747 // Explicit member accesses.
2748 } else {
John McCalldadc5752010-08-24 06:29:42 +00002749 ExprResult Result =
John McCall2d74de92009-12-01 22:10:20 +00002750 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCall48871652010-08-21 09:40:31 +00002751 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCall2d74de92009-12-01 22:10:20 +00002752
2753 if (Result.isInvalid()) {
2754 Owned(Base);
2755 return ExprError();
2756 }
2757
2758 if (Result.get())
2759 return move(Result);
Sebastian Redlfa1f70f2010-05-07 09:25:11 +00002760
2761 // LookupMemberExpr can modify Base, and thus change BaseType
2762 BaseType = Base->getType();
John McCall10eae182009-11-30 22:42:35 +00002763 }
2764
John McCallb268a282010-08-23 23:25:46 +00002765 return BuildMemberReferenceExpr(Base, BaseType,
John McCall38836f02010-01-15 08:34:02 +00002766 OpLoc, IsArrow, SS, FirstQualifierInScope,
2767 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002768}
2769
John McCalldadc5752010-08-24 06:29:42 +00002770ExprResult
John McCallb268a282010-08-23 23:25:46 +00002771Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCall2d74de92009-12-01 22:10:20 +00002772 SourceLocation OpLoc, bool IsArrow,
2773 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00002774 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00002775 LookupResult &R,
Douglas Gregorb139cd52010-05-01 20:49:11 +00002776 const TemplateArgumentListInfo *TemplateArgs,
2777 bool SuppressQualifierCheck) {
John McCall2d74de92009-12-01 22:10:20 +00002778 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00002779 if (IsArrow) {
2780 assert(BaseType->isPointerType());
2781 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2782 }
John McCalla8ae2222010-04-06 21:38:20 +00002783 R.setBaseObjectType(BaseType);
John McCall10eae182009-11-30 22:42:35 +00002784
John McCallb268a282010-08-23 23:25:46 +00002785 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002786 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
2787 DeclarationName MemberName = MemberNameInfo.getName();
2788 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall10eae182009-11-30 22:42:35 +00002789
2790 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00002791 return ExprError();
2792
John McCall10eae182009-11-30 22:42:35 +00002793 if (R.empty()) {
2794 // Rederive where we looked up.
2795 DeclContext *DC = (SS.isSet()
2796 ? computeDeclContext(SS, false)
2797 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00002798
John McCall10eae182009-11-30 22:42:35 +00002799 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00002800 << MemberName << DC
2801 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00002802 return ExprError();
2803 }
2804
John McCall38836f02010-01-15 08:34:02 +00002805 // Diagnose lookups that find only declarations from a non-base
2806 // type. This is possible for either qualified lookups (which may
2807 // have been qualified with an unrelated type) or implicit member
2808 // expressions (which were found with unqualified lookup and thus
2809 // may have come from an enclosing scope). Note that it's okay for
2810 // lookup to find declarations from a non-base type as long as those
2811 // aren't the ones picked by overload resolution.
2812 if ((SS.isSet() || !BaseExpr ||
2813 (isa<CXXThisExpr>(BaseExpr) &&
2814 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00002815 !SuppressQualifierCheck &&
John McCall38836f02010-01-15 08:34:02 +00002816 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00002817 return ExprError();
2818
2819 // Construct an unresolved result if we in fact got an unresolved
2820 // result.
2821 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall2d74de92009-12-01 22:10:20 +00002822 bool Dependent =
John McCall71739032009-12-19 02:05:44 +00002823 BaseExprType->isDependentType() ||
John McCall2d74de92009-12-01 22:10:20 +00002824 R.isUnresolvableResult() ||
John McCall1acbbb52010-02-02 06:20:04 +00002825 OverloadExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002826
John McCall58cc69d2010-01-27 01:50:18 +00002827 // Suppress any lookup-related diagnostics; we'll do these when we
2828 // pick a member.
2829 R.suppressDiagnostics();
2830
John McCall10eae182009-11-30 22:42:35 +00002831 UnresolvedMemberExpr *MemExpr
2832 = UnresolvedMemberExpr::Create(Context, Dependent,
2833 R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00002834 BaseExpr, BaseExprType,
2835 IsArrow, OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002836 Qualifier, SS.getRange(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002837 MemberNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002838 TemplateArgs, R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00002839
2840 return Owned(MemExpr);
2841 }
2842
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002843 assert(R.isSingleResult());
John McCalla8ae2222010-04-06 21:38:20 +00002844 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall10eae182009-11-30 22:42:35 +00002845 NamedDecl *MemberDecl = R.getFoundDecl();
2846
2847 // FIXME: diagnose the presence of template arguments now.
2848
2849 // If the decl being referenced had an error, return an error for this
2850 // sub-expr without emitting another error, in order to avoid cascading
2851 // error cases.
2852 if (MemberDecl->isInvalidDecl())
2853 return ExprError();
2854
John McCall2d74de92009-12-01 22:10:20 +00002855 // Handle the implicit-member-access case.
2856 if (!BaseExpr) {
2857 // If this is not an instance member, convert to a non-member access.
John McCalla8ae2222010-04-06 21:38:20 +00002858 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002859 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCall2d74de92009-12-01 22:10:20 +00002860
Douglas Gregorb15af892010-01-07 23:12:05 +00002861 SourceLocation Loc = R.getNameLoc();
2862 if (SS.getRange().isValid())
2863 Loc = SS.getRange().getBegin();
2864 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00002865 }
2866
John McCall10eae182009-11-30 22:42:35 +00002867 bool ShouldCheckUse = true;
2868 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2869 // Don't diagnose the use of a virtual member function unless it's
2870 // explicitly qualified.
2871 if (MD->isVirtual() && !SS.isSet())
2872 ShouldCheckUse = false;
2873 }
2874
2875 // Check the use of this member.
2876 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2877 Owned(BaseExpr);
2878 return ExprError();
2879 }
2880
2881 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2882 // We may have found a field within an anonymous union or struct
2883 // (C++ [class.union]).
Eli Friedman78cde142009-12-04 07:18:51 +00002884 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2885 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
John McCall10eae182009-11-30 22:42:35 +00002886 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2887 BaseExpr, OpLoc);
2888
2889 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2890 QualType MemberType = FD->getType();
2891 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2892 MemberType = Ref->getPointeeType();
2893 else {
2894 Qualifiers BaseQuals = BaseType.getQualifiers();
2895 BaseQuals.removeObjCGCAttr();
2896 if (FD->isMutable()) BaseQuals.removeConst();
2897
2898 Qualifiers MemberQuals
2899 = Context.getCanonicalType(MemberType).getQualifiers();
2900
2901 Qualifiers Combined = BaseQuals + MemberQuals;
2902 if (Combined != MemberQuals)
2903 MemberType = Context.getQualifiedType(MemberType, Combined);
2904 }
2905
2906 MarkDeclarationReferenced(MemberLoc, FD);
John McCall16df1e52010-03-30 21:47:33 +00002907 if (PerformObjectMemberConversion(BaseExpr, Qualifier, FoundDecl, FD))
John McCall10eae182009-11-30 22:42:35 +00002908 return ExprError();
2909 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002910 FD, FoundDecl, MemberNameInfo,
2911 MemberType));
John McCall10eae182009-11-30 22:42:35 +00002912 }
2913
2914 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2915 MarkDeclarationReferenced(MemberLoc, Var);
2916 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002917 Var, FoundDecl, MemberNameInfo,
John McCall10eae182009-11-30 22:42:35 +00002918 Var->getType().getNonReferenceType()));
2919 }
2920
2921 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2922 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2923 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002924 MemberFn, FoundDecl, MemberNameInfo,
John McCall10eae182009-11-30 22:42:35 +00002925 MemberFn->getType()));
2926 }
2927
2928 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2929 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2930 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002931 Enum, FoundDecl, MemberNameInfo,
2932 Enum->getType()));
John McCall10eae182009-11-30 22:42:35 +00002933 }
2934
2935 Owned(BaseExpr);
2936
Douglas Gregor861eb802010-04-25 20:55:08 +00002937 // We found something that we didn't expect. Complain.
John McCall10eae182009-11-30 22:42:35 +00002938 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002939 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregor861eb802010-04-25 20:55:08 +00002940 << MemberName << BaseType << int(IsArrow);
2941 else
2942 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
2943 << MemberName << BaseType << int(IsArrow);
John McCall10eae182009-11-30 22:42:35 +00002944
Douglas Gregor861eb802010-04-25 20:55:08 +00002945 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
2946 << MemberName;
Douglas Gregor516d6722010-04-25 21:15:30 +00002947 R.suppressDiagnostics();
Douglas Gregor861eb802010-04-25 20:55:08 +00002948 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00002949}
2950
2951/// Look up the given member of the given non-type-dependent
2952/// expression. This can return in one of two ways:
2953/// * If it returns a sentinel null-but-valid result, the caller will
2954/// assume that lookup was performed and the results written into
2955/// the provided structure. It will take over from there.
2956/// * Otherwise, the returned expression will be produced in place of
2957/// an ordinary member expression.
2958///
2959/// The ObjCImpDecl bit is a gross hack that will need to be properly
2960/// fixed for ObjC++.
John McCalldadc5752010-08-24 06:29:42 +00002961ExprResult
John McCall10eae182009-11-30 22:42:35 +00002962Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00002963 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002964 CXXScopeSpec &SS,
John McCall48871652010-08-21 09:40:31 +00002965 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00002966 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00002967
Steve Naroffeaaae462007-12-16 21:42:28 +00002968 // Perform default conversions.
2969 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002970
Steve Naroff185616f2007-07-26 03:11:44 +00002971 QualType BaseType = BaseExpr->getType();
John McCall10eae182009-11-30 22:42:35 +00002972 assert(!BaseType->isDependentType());
2973
2974 DeclarationName MemberName = R.getLookupName();
2975 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00002976
2977 // If the user is trying to apply -> or . to a function pointer
John McCall10eae182009-11-30 22:42:35 +00002978 // type, it's probably because they forgot parentheses to call that
Douglas Gregord82ae382009-11-06 06:30:47 +00002979 // function. Suggest the addition of those parentheses, build the
2980 // call, and continue on.
2981 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2982 if (const FunctionProtoType *Fun
2983 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2984 QualType ResultTy = Fun->getResultType();
2985 if (Fun->getNumArgs() == 0 &&
John McCall10eae182009-11-30 22:42:35 +00002986 ((!IsArrow && ResultTy->isRecordType()) ||
2987 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregord82ae382009-11-06 06:30:47 +00002988 ResultTy->getAs<PointerType>()->getPointeeType()
2989 ->isRecordType()))) {
2990 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2991 Diag(Loc, diag::err_member_reference_needs_call)
2992 << QualType(Fun, 0)
Douglas Gregora771f462010-03-31 17:46:05 +00002993 << FixItHint::CreateInsertion(Loc, "()");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002994
John McCalldadc5752010-08-24 06:29:42 +00002995 ExprResult NewBase
John McCallb268a282010-08-23 23:25:46 +00002996 = ActOnCallExpr(0, BaseExpr, Loc,
Douglas Gregord82ae382009-11-06 06:30:47 +00002997 MultiExprArg(*this, 0, 0), 0, Loc);
Douglas Gregor143d3672010-06-21 22:46:46 +00002998 BaseExpr = 0;
Douglas Gregord82ae382009-11-06 06:30:47 +00002999 if (NewBase.isInvalid())
John McCall10eae182009-11-30 22:42:35 +00003000 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003001
Douglas Gregord82ae382009-11-06 06:30:47 +00003002 BaseExpr = NewBase.takeAs<Expr>();
3003 DefaultFunctionArrayConversion(BaseExpr);
3004 BaseType = BaseExpr->getType();
3005 }
3006 }
3007 }
3008
David Chisnall9f57c292009-08-17 16:35:33 +00003009 // If this is an Objective-C pseudo-builtin and a definition is provided then
3010 // use that.
3011 if (BaseType->isObjCIdType()) {
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00003012 if (IsArrow) {
3013 // Handle the following exceptional case PObj->isa.
3014 if (const ObjCObjectPointerType *OPT =
3015 BaseType->getAs<ObjCObjectPointerType>()) {
John McCall8b07ec22010-05-15 11:32:37 +00003016 if (OPT->getObjectType()->isObjCId() &&
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00003017 MemberName.getAsIdentifierInfo()->isStr("isa"))
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00003018 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
3019 Context.getObjCClassType()));
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00003020 }
3021 }
David Chisnall9f57c292009-08-17 16:35:33 +00003022 // We have an 'id' type. Rather than fall through, we check if this
3023 // is a reference to 'isa'.
3024 if (BaseType != Context.ObjCIdRedefinitionType) {
3025 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00003026 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00003027 }
David Chisnall9f57c292009-08-17 16:35:33 +00003028 }
John McCall10eae182009-11-30 22:42:35 +00003029
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00003030 // If this is an Objective-C pseudo-builtin and a definition is provided then
3031 // use that.
3032 if (Context.isObjCSelType(BaseType)) {
3033 // We have an 'SEL' type. Rather than fall through, we check if this
3034 // is a reference to 'sel_id'.
3035 if (BaseType != Context.ObjCSelRedefinitionType) {
3036 BaseType = Context.ObjCSelRedefinitionType;
3037 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
3038 }
3039 }
John McCall10eae182009-11-30 22:42:35 +00003040
Steve Naroff185616f2007-07-26 03:11:44 +00003041 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003042
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003043 // Handle properties on ObjC 'Class' types.
John McCall10eae182009-11-30 22:42:35 +00003044 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003045 // Also must look for a getter name which uses property syntax.
3046 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3047 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3048 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
3049 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3050 ObjCMethodDecl *Getter;
3051 // FIXME: need to also look locally in the implementation.
3052 if ((Getter = IFace->lookupClassMethod(Sel))) {
3053 // Check the use of this method.
3054 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3055 return ExprError();
3056 }
3057 // If we found a getter then this may be a valid dot-reference, we
3058 // will look for the matching setter, in case it is needed.
3059 Selector SetterSel =
3060 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3061 PP.getSelectorTable(), Member);
3062 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3063 if (!Setter) {
3064 // If this reference is in an @implementation, also check for 'private'
3065 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00003066 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003067 }
3068 // Look through local category implementations associated with the class.
3069 if (!Setter)
3070 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003071
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003072 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3073 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003074
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003075 if (Getter || Setter) {
3076 QualType PType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003077
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003078 if (Getter)
Douglas Gregor603d81b2010-07-13 08:18:22 +00003079 PType = Getter->getSendResultType();
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003080 else
3081 // Get the expression type from Setter's incoming parameter.
3082 PType = (*(Setter->param_end() -1))->getType();
3083 // FIXME: we must check that the setter has property type.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003084 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003085 PType,
3086 Setter, MemberLoc, BaseExpr));
3087 }
3088 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3089 << MemberName << BaseType);
3090 }
3091 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003092
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003093 if (BaseType->isObjCClassType() &&
3094 BaseType != Context.ObjCClassRedefinitionType) {
3095 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00003096 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003097 }
Mike Stump11289f42009-09-09 15:08:12 +00003098
John McCall10eae182009-11-30 22:42:35 +00003099 if (IsArrow) {
3100 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff185616f2007-07-26 03:11:44 +00003101 BaseType = PT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00003102 else if (BaseType->isObjCObjectPointerType())
3103 ;
John McCalla928c652009-12-07 22:46:59 +00003104 else if (BaseType->isRecordType()) {
3105 // Recover from arrow accesses to records, e.g.:
3106 // struct MyRecord foo;
3107 // foo->bar
3108 // This is actually well-formed in C++ if MyRecord has an
3109 // overloaded operator->, but that should have been dealt with
3110 // by now.
3111 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3112 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003113 << FixItHint::CreateReplacement(OpLoc, ".");
John McCalla928c652009-12-07 22:46:59 +00003114 IsArrow = false;
3115 } else {
John McCall10eae182009-11-30 22:42:35 +00003116 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3117 << BaseType << BaseExpr->getSourceRange();
3118 return ExprError();
Anders Carlsson524d5a42009-05-16 20:31:20 +00003119 }
John McCalla928c652009-12-07 22:46:59 +00003120 } else {
3121 // Recover from dot accesses to pointers, e.g.:
3122 // type *foo;
3123 // foo.bar
3124 // This is actually well-formed in two cases:
3125 // - 'type' is an Objective C type
3126 // - 'bar' is a pseudo-destructor name which happens to refer to
3127 // the appropriate pointer type
3128 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
3129 const PointerType *PT = BaseType->getAs<PointerType>();
3130 if (PT && PT->getPointeeType()->isRecordType()) {
3131 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3132 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003133 << FixItHint::CreateReplacement(OpLoc, "->");
John McCalla928c652009-12-07 22:46:59 +00003134 BaseType = PT->getPointeeType();
3135 IsArrow = true;
3136 }
3137 }
John McCall10eae182009-11-30 22:42:35 +00003138 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003139
John McCall8b07ec22010-05-15 11:32:37 +00003140 // Handle field access to simple records.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003141 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCall2d74de92009-12-01 22:10:20 +00003142 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
John McCalle9cccd82010-06-16 08:42:20 +00003143 RTy, OpLoc, SS, HasTemplateArgs))
Douglas Gregordd430f72009-01-19 19:26:10 +00003144 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00003145 return Owned((Expr*) 0);
Chris Lattnerb63a7452008-07-21 04:28:12 +00003146 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003147
Chris Lattnerdc420f42008-07-21 04:59:05 +00003148 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
3149 // (*Obj).ivar.
John McCall10eae182009-11-30 22:42:35 +00003150 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCall8b07ec22010-05-15 11:32:37 +00003151 (!IsArrow && BaseType->isObjCObjectType())) {
John McCall9dd450b2009-09-21 23:43:11 +00003152 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
John McCall8b07ec22010-05-15 11:32:37 +00003153 ObjCInterfaceDecl *IDecl =
3154 OPT ? OPT->getInterfaceDecl()
3155 : BaseType->getAs<ObjCObjectType>()->getInterface();
3156 if (IDecl) {
Anders Carlssonf571c112009-08-26 18:25:21 +00003157 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3158
Steve Naroffa057ba92009-07-16 00:25:06 +00003159 ObjCInterfaceDecl *ClassDeclared;
Anders Carlssonf571c112009-08-26 18:25:21 +00003160 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump11289f42009-09-09 15:08:12 +00003161
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003162 if (!IV) {
3163 // Attempt to correct for typos in ivar names.
3164 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3165 LookupMemberName);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003166 if (CorrectTypo(Res, 0, 0, IDecl, false, CTC_MemberLookup) &&
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003167 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003168 Diag(R.getNameLoc(),
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003169 diag::err_typecheck_member_reference_ivar_suggest)
3170 << IDecl->getDeclName() << MemberName << IV->getDeclName()
Douglas Gregora771f462010-03-31 17:46:05 +00003171 << FixItHint::CreateReplacement(R.getNameLoc(),
3172 IV->getNameAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003173 Diag(IV->getLocation(), diag::note_previous_decl)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003174 << IV->getDeclName();
Douglas Gregorc048c522010-06-29 19:27:42 +00003175 } else {
3176 Res.clear();
3177 Res.setLookupName(Member);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003178 }
3179 }
3180
Steve Naroffa057ba92009-07-16 00:25:06 +00003181 if (IV) {
3182 // If the decl being referenced had an error, return an error for this
3183 // sub-expr without emitting another error, in order to avoid cascading
3184 // error cases.
3185 if (IV->isInvalidDecl())
3186 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003187
Steve Naroffa057ba92009-07-16 00:25:06 +00003188 // Check whether we can reference this field.
3189 if (DiagnoseUseOfDecl(IV, MemberLoc))
3190 return ExprError();
3191 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3192 IV->getAccessControl() != ObjCIvarDecl::Package) {
3193 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3194 if (ObjCMethodDecl *MD = getCurMethodDecl())
3195 ClassOfMethodDecl = MD->getClassInterface();
3196 else if (ObjCImpDecl && getCurFunctionDecl()) {
3197 // Case of a c-function declared inside an objc implementation.
3198 // FIXME: For a c-style function nested inside an objc implementation
3199 // class, there is no implementation context available, so we pass
3200 // down the context as argument to this routine. Ideally, this context
3201 // need be passed down in the AST node and somehow calculated from the
3202 // AST for a function decl.
Mike Stump11289f42009-09-09 15:08:12 +00003203 if (ObjCImplementationDecl *IMPD =
John McCall48871652010-08-21 09:40:31 +00003204 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
Steve Naroffa057ba92009-07-16 00:25:06 +00003205 ClassOfMethodDecl = IMPD->getClassInterface();
3206 else if (ObjCCategoryImplDecl* CatImplClass =
John McCall48871652010-08-21 09:40:31 +00003207 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
Steve Naroffa057ba92009-07-16 00:25:06 +00003208 ClassOfMethodDecl = CatImplClass->getClassInterface();
3209 }
Mike Stump11289f42009-09-09 15:08:12 +00003210
3211 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3212 if (ClassDeclared != IDecl ||
Steve Naroffa057ba92009-07-16 00:25:06 +00003213 ClassOfMethodDecl != ClassDeclared)
Mike Stump11289f42009-09-09 15:08:12 +00003214 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00003215 << IV->getDeclName();
Mike Stump12b8ce12009-08-04 21:02:39 +00003216 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3217 // @protected
Mike Stump11289f42009-09-09 15:08:12 +00003218 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00003219 << IV->getDeclName();
Steve Naroffd1b64be2009-03-04 18:34:24 +00003220 }
Steve Naroffa057ba92009-07-16 00:25:06 +00003221
3222 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3223 MemberLoc, BaseExpr,
John McCall10eae182009-11-30 22:42:35 +00003224 IsArrow));
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +00003225 }
Steve Naroffa057ba92009-07-16 00:25:06 +00003226 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlssonf571c112009-08-26 18:25:21 +00003227 << IDecl->getDeclName() << MemberName
Steve Naroffa057ba92009-07-16 00:25:06 +00003228 << BaseExpr->getSourceRange());
Fariborz Jahanianb1378f92008-12-13 22:20:28 +00003229 }
Chris Lattnerb63a7452008-07-21 04:28:12 +00003230 }
Steve Naroff1329fa02009-07-15 18:40:39 +00003231 // Handle properties on 'id' and qualified "id".
John McCall10eae182009-11-30 22:42:35 +00003232 if (!IsArrow && (BaseType->isObjCIdType() ||
3233 BaseType->isObjCQualifiedIdType())) {
John McCall9dd450b2009-09-21 23:43:11 +00003234 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlssonf571c112009-08-26 18:25:21 +00003235 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003236
Steve Naroff7cae42b2009-07-10 23:34:53 +00003237 // Check protocols on qualified interfaces.
Anders Carlssonf571c112009-08-26 18:25:21 +00003238 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003239 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
3240 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3241 // Check the use of this declaration
3242 if (DiagnoseUseOfDecl(PD, MemberLoc))
3243 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003244
Steve Naroff7cae42b2009-07-10 23:34:53 +00003245 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3246 MemberLoc, BaseExpr));
3247 }
3248 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3249 // Check the use of this method.
3250 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3251 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003252
Alexis Huntc46382e2010-04-28 23:02:27 +00003253 return Owned(ObjCMessageExpr::Create(Context,
Douglas Gregor603d81b2010-07-13 08:18:22 +00003254 OMD->getSendResultType(),
Douglas Gregor9a129192010-04-21 00:45:42 +00003255 OpLoc, BaseExpr, Sel,
3256 OMD, NULL, 0, MemberLoc));
Steve Naroff7cae42b2009-07-10 23:34:53 +00003257 }
3258 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003259
Steve Naroff7cae42b2009-07-10 23:34:53 +00003260 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00003261 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003262 }
Alexis Huntc46382e2010-04-28 23:02:27 +00003263
Chris Lattnerdc420f42008-07-21 04:59:05 +00003264 // Handle Objective-C property access, which is "Obj.property" where Obj is a
3265 // pointer to a (potentially qualified) interface type.
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00003266 if (!IsArrow)
3267 if (const ObjCObjectPointerType *OPT =
3268 BaseType->getAsObjCInterfacePointerType())
Chris Lattner90c58fa2010-04-11 07:51:10 +00003269 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003270
Steve Naroffe87026a2009-07-24 17:54:45 +00003271 // Handle the following exceptional case (*Obj).isa.
John McCall10eae182009-11-30 22:42:35 +00003272 if (!IsArrow &&
John McCall8b07ec22010-05-15 11:32:37 +00003273 BaseType->isObjCObjectType() &&
3274 BaseType->getAs<ObjCObjectType>()->isObjCId() &&
Anders Carlssonf571c112009-08-26 18:25:21 +00003275 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroffe87026a2009-07-24 17:54:45 +00003276 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00003277 Context.getObjCClassType()));
Steve Naroffe87026a2009-07-24 17:54:45 +00003278
Chris Lattnerb63a7452008-07-21 04:28:12 +00003279 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003280 if (BaseType->isExtVectorType()) {
Anders Carlssonf571c112009-08-26 18:25:21 +00003281 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerb63a7452008-07-21 04:28:12 +00003282 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
3283 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003284 return ExprError();
Anders Carlssonf571c112009-08-26 18:25:21 +00003285 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Narofff6009ed2009-01-21 00:14:39 +00003286 MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00003287 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003288
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003289 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3290 << BaseType << BaseExpr->getSourceRange();
3291
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003292 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00003293}
3294
John McCall10eae182009-11-30 22:42:35 +00003295/// The main callback when the parser finds something like
3296/// expression . [nested-name-specifier] identifier
3297/// expression -> [nested-name-specifier] identifier
3298/// where 'identifier' encompasses a fairly broad spectrum of
3299/// possibilities, including destructor and operator references.
3300///
3301/// \param OpKind either tok::arrow or tok::period
3302/// \param HasTrailingLParen whether the next token is '(', which
3303/// is used to diagnose mis-uses of special members that can
3304/// only be called
3305/// \param ObjCImpDecl the current ObjC @implementation decl;
3306/// this is an ugly hack around the fact that ObjC @implementations
3307/// aren't properly put in the context chain
John McCalldadc5752010-08-24 06:29:42 +00003308ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall10eae182009-11-30 22:42:35 +00003309 SourceLocation OpLoc,
3310 tok::TokenKind OpKind,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003311 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003312 UnqualifiedId &Id,
John McCall48871652010-08-21 09:40:31 +00003313 Decl *ObjCImpDecl,
John McCall10eae182009-11-30 22:42:35 +00003314 bool HasTrailingLParen) {
3315 if (SS.isSet() && SS.isInvalid())
3316 return ExprError();
3317
3318 TemplateArgumentListInfo TemplateArgsBuffer;
3319
3320 // Decompose the name into its component parts.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003321 DeclarationNameInfo NameInfo;
John McCall10eae182009-11-30 22:42:35 +00003322 const TemplateArgumentListInfo *TemplateArgs;
3323 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003324 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003325
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003326 DeclarationName Name = NameInfo.getName();
John McCall10eae182009-11-30 22:42:35 +00003327 bool IsArrow = (OpKind == tok::arrow);
3328
3329 NamedDecl *FirstQualifierInScope
3330 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3331 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3332
3333 // This is a postfix expression, so get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003334 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003335 if (Result.isInvalid()) return ExprError();
3336 Base = Result.take();
John McCall10eae182009-11-30 22:42:35 +00003337
Douglas Gregor41f90302010-04-12 20:54:26 +00003338 if (Base->getType()->isDependentType() || Name.isDependentName() ||
3339 isDependentScopeSpecifier(SS)) {
John McCallb268a282010-08-23 23:25:46 +00003340 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00003341 IsArrow, OpLoc,
3342 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003343 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003344 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003345 LookupResult R(*this, NameInfo, LookupMemberName);
John McCalle9cccd82010-06-16 08:42:20 +00003346 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3347 SS, ObjCImpDecl, TemplateArgs != 0);
Alexis Huntc46382e2010-04-28 23:02:27 +00003348
John McCalle9cccd82010-06-16 08:42:20 +00003349 if (Result.isInvalid()) {
3350 Owned(Base);
3351 return ExprError();
3352 }
John McCall10eae182009-11-30 22:42:35 +00003353
John McCalle9cccd82010-06-16 08:42:20 +00003354 if (Result.get()) {
3355 // The only way a reference to a destructor can be used is to
3356 // immediately call it, which falls into this case. If the
3357 // next token is not a '(', produce a diagnostic and build the
3358 // call now.
3359 if (!HasTrailingLParen &&
3360 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCallb268a282010-08-23 23:25:46 +00003361 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall10eae182009-11-30 22:42:35 +00003362
John McCalle9cccd82010-06-16 08:42:20 +00003363 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00003364 }
3365
John McCallb268a282010-08-23 23:25:46 +00003366 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00003367 OpLoc, IsArrow, SS, FirstQualifierInScope,
3368 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003369 }
3370
3371 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00003372}
3373
John McCalldadc5752010-08-24 06:29:42 +00003374ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Anders Carlsson355933d2009-08-25 03:49:14 +00003375 FunctionDecl *FD,
3376 ParmVarDecl *Param) {
3377 if (Param->hasUnparsedDefaultArg()) {
3378 Diag (CallLoc,
3379 diag::err_use_of_default_argument_to_function_declared_later) <<
3380 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003381 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson355933d2009-08-25 03:49:14 +00003382 diag::note_default_argument_declared_here);
3383 } else {
3384 if (Param->hasUninstantiatedDefaultArg()) {
3385 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3386
3387 // Instantiate the expression.
Douglas Gregor8c702532010-02-05 07:33:43 +00003388 MultiLevelTemplateArgumentList ArgList
3389 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003390
Douglas Gregor9961ce92010-07-08 18:37:38 +00003391 std::pair<const TemplateArgument *, unsigned> Innermost
3392 = ArgList.getInnermost();
3393 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3394 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003395
John McCalldadc5752010-08-24 06:29:42 +00003396 ExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump11289f42009-09-09 15:08:12 +00003397 if (Result.isInvalid())
Anders Carlsson355933d2009-08-25 03:49:14 +00003398 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003399
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003400 // Check the expression as an initializer for the parameter.
3401 InitializedEntity Entity
3402 = InitializedEntity::InitializeParameter(Param);
3403 InitializationKind Kind
3404 = InitializationKind::CreateCopy(Param->getLocation(),
3405 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3406 Expr *ResultE = Result.takeAs<Expr>();
3407
3408 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003409 Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00003410 MultiExprArg(*this, &ResultE, 1));
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003411 if (Result.isInvalid())
Anders Carlsson355933d2009-08-25 03:49:14 +00003412 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003413
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003414 // Build the default argument expression.
Douglas Gregor033f6752009-12-23 23:03:06 +00003415 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003416 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003417 }
Mike Stump11289f42009-09-09 15:08:12 +00003418
Anders Carlsson355933d2009-08-25 03:49:14 +00003419 // If the default expression creates temporaries, we need to
3420 // push them to the current stack of expression temporaries so they'll
3421 // be properly destroyed.
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003422 // FIXME: We should really be rebuilding the default argument with new
3423 // bound temporaries; see the comment in PR5810.
Anders Carlsson714d0962009-12-15 19:16:31 +00003424 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i)
3425 ExprTemporaries.push_back(Param->getDefaultArgTemporary(i));
Anders Carlsson355933d2009-08-25 03:49:14 +00003426 }
3427
3428 // We already type-checked the argument, so we know it works.
Douglas Gregor033f6752009-12-23 23:03:06 +00003429 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003430}
3431
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003432/// ConvertArgumentsForCall - Converts the arguments specified in
3433/// Args/NumArgs to the parameter types of the function FDecl with
3434/// function prototype Proto. Call is the call expression itself, and
3435/// Fn is the function expression. For a C++ member function, this
3436/// routine does not attempt to convert the object argument. Returns
3437/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003438bool
3439Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003440 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003441 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003442 Expr **Args, unsigned NumArgs,
3443 SourceLocation RParenLoc) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003444 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003445 // assignment, to the types of the corresponding parameter, ...
3446 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003447 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003448
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003449 // If too few arguments are available (and we don't have default
3450 // arguments for the remaining parameters), don't make the call.
3451 if (NumArgs < NumArgsInProto) {
3452 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3453 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003454 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00003455 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00003456 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003457 }
3458
3459 // If too many are passed and not variadic, error on the extras and drop
3460 // them.
3461 if (NumArgs > NumArgsInProto) {
3462 if (!Proto->isVariadic()) {
3463 Diag(Args[NumArgsInProto]->getLocStart(),
3464 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003465 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003466 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003467 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3468 Args[NumArgs-1]->getLocEnd());
3469 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003470 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003471 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003472 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003473 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003474 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003475 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003476 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3477 if (Fn->getType()->isBlockPointerType())
3478 CallType = VariadicBlock; // Block
3479 else if (isa<MemberExpr>(Fn))
3480 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003481 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003482 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003483 if (Invalid)
3484 return true;
3485 unsigned TotalNumArgs = AllArgs.size();
3486 for (unsigned i = 0; i < TotalNumArgs; ++i)
3487 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003488
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003489 return false;
3490}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003491
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003492bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3493 FunctionDecl *FDecl,
3494 const FunctionProtoType *Proto,
3495 unsigned FirstProtoArg,
3496 Expr **Args, unsigned NumArgs,
3497 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003498 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003499 unsigned NumArgsInProto = Proto->getNumArgs();
3500 unsigned NumArgsToCheck = NumArgs;
3501 bool Invalid = false;
3502 if (NumArgs != NumArgsInProto)
3503 // Use default arguments for missing arguments
3504 NumArgsToCheck = NumArgsInProto;
3505 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003506 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003507 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003508 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003509
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003510 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003511 if (ArgIx < NumArgs) {
3512 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003513
Eli Friedman3164fb12009-03-22 22:00:50 +00003514 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3515 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003516 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003517 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003518 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003519
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003520 // Pass the argument
3521 ParmVarDecl *Param = 0;
3522 if (FDecl && i < FDecl->getNumParams())
3523 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003524
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003525
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003526 InitializedEntity Entity =
3527 Param? InitializedEntity::InitializeParameter(Param)
3528 : InitializedEntity::InitializeParameter(ProtoArgType);
John McCalldadc5752010-08-24 06:29:42 +00003529 ExprResult ArgE = PerformCopyInitialization(Entity,
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003530 SourceLocation(),
3531 Owned(Arg));
3532 if (ArgE.isInvalid())
3533 return true;
3534
3535 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003536 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003537 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003538
John McCalldadc5752010-08-24 06:29:42 +00003539 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003540 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003541 if (ArgExpr.isInvalid())
3542 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003543
Anders Carlsson355933d2009-08-25 03:49:14 +00003544 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003545 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003546 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003547 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003548
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003549 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003550 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003551 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattnerbb53efb2010-05-16 04:01:30 +00003552 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003553 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00003554 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003555 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003556 }
3557 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003558 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003559}
3560
Steve Naroff83895f72007-09-16 03:34:24 +00003561/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003562/// This provides the location of the left/right parens and a list of comma
3563/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003564ExprResult
John McCallb268a282010-08-23 23:25:46 +00003565Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003566 MultiExprArg args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003567 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003568 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003569
3570 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003571 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003572 if (Result.isInvalid()) return ExprError();
3573 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003574
John McCallb268a282010-08-23 23:25:46 +00003575 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00003576
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003577 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003578 // If this is a pseudo-destructor expression, build the call immediately.
3579 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3580 if (NumArgs > 0) {
3581 // Pseudo-destructor calls should not have any arguments.
3582 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003583 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003584 SourceRange(Args[0]->getLocStart(),
3585 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003586
Douglas Gregorad8a3362009-09-04 17:36:40 +00003587 NumArgs = 0;
3588 }
Mike Stump11289f42009-09-09 15:08:12 +00003589
Douglas Gregorad8a3362009-09-04 17:36:40 +00003590 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3591 RParenLoc));
3592 }
Mike Stump11289f42009-09-09 15:08:12 +00003593
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003594 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003595 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003596 // FIXME: Will need to cache the results of name lookup (including ADL) in
3597 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003598 bool Dependent = false;
3599 if (Fn->isTypeDependent())
3600 Dependent = true;
3601 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3602 Dependent = true;
3603
3604 if (Dependent)
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003605 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003606 Context.DependentTy, RParenLoc));
3607
3608 // Determine whether this is a call to an object (C++ [over.call.object]).
3609 if (Fn->getType()->isRecordType())
3610 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3611 CommaLocs, RParenLoc));
3612
John McCall10eae182009-11-30 22:42:35 +00003613 Expr *NakedFn = Fn->IgnoreParens();
3614
3615 // Determine whether this is a call to an unresolved member function.
3616 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3617 // If lookup was unresolved but not dependent (i.e. didn't find
3618 // an unresolved using declaration), it has to be an overloaded
3619 // function set, which means it must contain either multiple
3620 // declarations (all methods or method templates) or a single
3621 // method template.
3622 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor516d6722010-04-25 21:15:30 +00003623 isa<FunctionTemplateDecl>(
3624 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00003625 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00003626
John McCall2d74de92009-12-01 22:10:20 +00003627 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3628 CommaLocs, RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003629 }
3630
Douglas Gregore254f902009-02-04 00:32:51 +00003631 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00003632 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003633 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00003634 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00003635 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3636 CommaLocs, RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003637 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003638
Anders Carlsson61914b52009-10-03 17:40:22 +00003639 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00003640 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson61914b52009-10-03 17:40:22 +00003641 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3642 BO->getOpcode() == BinaryOperator::PtrMemI) {
Douglas Gregorc8be9522010-05-04 18:18:31 +00003643 if (const FunctionProtoType *FPT
3644 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00003645 QualType ResultTy = FPT->getCallResultType(Context);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003646
John McCallb268a282010-08-23 23:25:46 +00003647 CXXMemberCallExpr *TheCall
3648 = new (Context) CXXMemberCallExpr(Context, BO, Args,
3649 NumArgs, ResultTy,
3650 RParenLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003651
3652 if (CheckCallReturnType(FPT->getResultType(),
3653 BO->getRHS()->getSourceRange().getBegin(),
John McCallb268a282010-08-23 23:25:46 +00003654 TheCall, 0))
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003655 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00003656
John McCallb268a282010-08-23 23:25:46 +00003657 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003658 RParenLoc))
3659 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00003660
John McCallb268a282010-08-23 23:25:46 +00003661 return MaybeBindToTemporary(TheCall);
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003662 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003663 return ExprError(Diag(Fn->getLocStart(),
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003664 diag::err_typecheck_call_not_function)
3665 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson61914b52009-10-03 17:40:22 +00003666 }
3667 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003668 }
3669
Douglas Gregore254f902009-02-04 00:32:51 +00003670 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003671 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00003672 // lookup and whether there were any explicitly-specified template arguments.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003673
Eli Friedmane14b1992009-12-26 03:35:45 +00003674 Expr *NakedFn = Fn->IgnoreParens();
John McCall57500772009-12-16 12:17:52 +00003675 if (isa<UnresolvedLookupExpr>(NakedFn)) {
3676 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
Douglas Gregor2fb18b72010-04-14 20:27:54 +00003677 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall57500772009-12-16 12:17:52 +00003678 CommaLocs, RParenLoc);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003679 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003680
John McCall57500772009-12-16 12:17:52 +00003681 NamedDecl *NDecl = 0;
3682 if (isa<DeclRefExpr>(NakedFn))
3683 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3684
John McCall2d74de92009-12-01 22:10:20 +00003685 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3686}
3687
John McCall57500772009-12-16 12:17:52 +00003688/// BuildResolvedCallExpr - Build a call to a resolved expression,
3689/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003690/// unary-convert to an expression of function-pointer or
3691/// block-pointer type.
3692///
3693/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003694ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003695Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3696 SourceLocation LParenLoc,
3697 Expr **Args, unsigned NumArgs,
3698 SourceLocation RParenLoc) {
3699 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3700
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003701 // Promote the function operand.
3702 UsualUnaryConversions(Fn);
3703
Chris Lattner08464942007-12-28 05:29:59 +00003704 // Make the call expr early, before semantic checks. This guarantees cleanup
3705 // of arguments and function on error.
John McCallb268a282010-08-23 23:25:46 +00003706 CallExpr *TheCall = new (Context) CallExpr(Context, Fn,
3707 Args, NumArgs,
3708 Context.BoolTy,
3709 RParenLoc);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003710
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003711 const FunctionType *FuncT;
3712 if (!Fn->getType()->isBlockPointerType()) {
3713 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3714 // have type pointer to function".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003715 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003716 if (PT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003717 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3718 << Fn->getType() << Fn->getSourceRange());
John McCall9dd450b2009-09-21 23:43:11 +00003719 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003720 } else { // This is a block call.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003721 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall9dd450b2009-09-21 23:43:11 +00003722 getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003723 }
Chris Lattner08464942007-12-28 05:29:59 +00003724 if (FuncT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003725 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3726 << Fn->getType() << Fn->getSourceRange());
3727
Eli Friedman3164fb12009-03-22 22:00:50 +00003728 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003729 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00003730 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003731 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003732 return ExprError();
3733
Chris Lattner08464942007-12-28 05:29:59 +00003734 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003735 TheCall->setType(FuncT->getCallResultType(Context));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003736
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003737 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003738 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003739 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003740 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003741 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003742 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003743
Douglas Gregord8e97de2009-04-02 15:37:10 +00003744 if (FDecl) {
3745 // Check if we have too few/too many template arguments, based
3746 // on our knowledge of the function definition.
3747 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003748 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003749 const FunctionProtoType *Proto =
John McCall9dd450b2009-09-21 23:43:11 +00003750 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003751 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3752 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3753 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3754 }
3755 }
Douglas Gregord8e97de2009-04-02 15:37:10 +00003756 }
3757
Steve Naroff0b661582007-08-28 23:30:39 +00003758 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003759 for (unsigned i = 0; i != NumArgs; i++) {
3760 Expr *Arg = Args[i];
3761 DefaultArgumentPromotion(Arg);
Eli Friedman3164fb12009-03-22 22:00:50 +00003762 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3763 Arg->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00003764 PDiag(diag::err_call_incomplete_argument)
3765 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003766 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003767 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003768 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003769 }
Chris Lattner08464942007-12-28 05:29:59 +00003770
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003771 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3772 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003773 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3774 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003775
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003776 // Check for sentinels
3777 if (NDecl)
3778 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003779
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003780 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003781 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003782 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003783 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003784
Douglas Gregor15fc9562009-09-12 00:22:50 +00003785 if (unsigned BuiltinID = FDecl->getBuiltinID())
John McCallb268a282010-08-23 23:25:46 +00003786 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003787 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003788 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003789 return ExprError();
3790 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003791
John McCallb268a282010-08-23 23:25:46 +00003792 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003793}
3794
John McCalldadc5752010-08-24 06:29:42 +00003795ExprResult
John McCallba7bf592010-08-24 05:47:05 +00003796Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00003797 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003798 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003799 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003800 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003801
3802 TypeSourceInfo *TInfo;
3803 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3804 if (!TInfo)
3805 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3806
John McCallb268a282010-08-23 23:25:46 +00003807 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00003808}
3809
John McCalldadc5752010-08-24 06:29:42 +00003810ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00003811Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00003812 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00003813 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003814
Eli Friedman37a186d2008-05-20 05:22:08 +00003815 if (literalType->isArrayType()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003816 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003817 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3818 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003819 } else if (!literalType->isDependentType() &&
3820 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003821 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003822 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003823 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003824 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003825
Douglas Gregor85dabae2009-12-16 01:38:02 +00003826 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003827 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003828 InitializationKind Kind
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003829 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor85dabae2009-12-16 01:38:02 +00003830 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00003831 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00003832 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00003833 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00003834 &literalType);
3835 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003836 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00003837 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00003838
Chris Lattner79413952008-12-04 23:50:19 +00003839 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003840 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003841 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003842 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003843 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003844
John McCall5d7aa7f2010-01-19 22:33:45 +00003845 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Steve Narofff6009ed2009-01-21 00:14:39 +00003846 literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003847}
3848
John McCalldadc5752010-08-24 06:29:42 +00003849ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00003850Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003851 SourceLocation RBraceLoc) {
3852 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00003853 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00003854
Steve Naroff30d242c2007-09-15 18:49:24 +00003855 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003856 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003857
Ted Kremenekac034612010-04-13 23:39:13 +00003858 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3859 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003860 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003861 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003862}
3863
Anders Carlsson094c4592009-10-18 18:12:03 +00003864static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3865 QualType SrcTy, QualType DestTy) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003866 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson094c4592009-10-18 18:12:03 +00003867 return CastExpr::CK_NoOp;
3868
3869 if (SrcTy->hasPointerRepresentation()) {
3870 if (DestTy->hasPointerRepresentation())
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003871 return DestTy->isObjCObjectPointerType() ?
3872 CastExpr::CK_AnyPointerToObjCPointerCast :
Fariborz Jahanian2b9fc832009-12-15 21:34:52 +00003873 CastExpr::CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00003874 if (DestTy->isIntegerType())
3875 return CastExpr::CK_PointerToIntegral;
3876 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003877
Anders Carlsson094c4592009-10-18 18:12:03 +00003878 if (SrcTy->isIntegerType()) {
3879 if (DestTy->isIntegerType())
3880 return CastExpr::CK_IntegralCast;
3881 if (DestTy->hasPointerRepresentation())
3882 return CastExpr::CK_IntegralToPointer;
3883 if (DestTy->isRealFloatingType())
3884 return CastExpr::CK_IntegralToFloating;
3885 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003886
Anders Carlsson094c4592009-10-18 18:12:03 +00003887 if (SrcTy->isRealFloatingType()) {
3888 if (DestTy->isRealFloatingType())
3889 return CastExpr::CK_FloatingCast;
3890 if (DestTy->isIntegerType())
3891 return CastExpr::CK_FloatingToIntegral;
3892 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003893
Anders Carlsson094c4592009-10-18 18:12:03 +00003894 // FIXME: Assert here.
3895 // assert(false && "Unhandled cast combination!");
3896 return CastExpr::CK_Unknown;
3897}
3898
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003899/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redl955a0672009-07-29 13:50:23 +00003900bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump11289f42009-09-09 15:08:12 +00003901 CastExpr::CastKind& Kind,
John McCallcf142162010-08-07 06:22:56 +00003902 CXXCastPath &BasePath,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003903 bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00003904 if (getLangOptions().CPlusPlus)
Anders Carlssona70cff62010-04-24 19:06:50 +00003905 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, BasePath,
3906 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003907
Douglas Gregorb92a1562010-02-03 00:27:59 +00003908 DefaultFunctionArrayLvalueConversion(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003909
3910 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3911 // type needs to be scalar.
3912 if (castType->isVoidType()) {
3913 // Cast to void allows any expr type.
Anders Carlssonef918ac2009-10-16 02:35:04 +00003914 Kind = CastExpr::CK_ToVoid;
3915 return false;
3916 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003917
Eli Friedmane98194d2010-07-17 20:43:49 +00003918 if (RequireCompleteType(TyR.getBegin(), castType,
3919 diag::err_typecheck_cast_to_incomplete))
3920 return true;
3921
Anders Carlssonef918ac2009-10-16 02:35:04 +00003922 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003923 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003924 (castType->isStructureType() || castType->isUnionType())) {
3925 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00003926 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003927 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3928 << castType << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003929 Kind = CastExpr::CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003930 return false;
3931 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003932
Anders Carlsson525b76b2009-10-16 02:48:28 +00003933 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003934 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003935 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003936 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003937 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003938 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003939 if (Context.hasSameUnqualifiedType(Field->getType(),
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003940 castExpr->getType())) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003941 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3942 << castExpr->getSourceRange();
3943 break;
3944 }
3945 }
3946 if (Field == FieldEnd)
3947 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3948 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003949 Kind = CastExpr::CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003950 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003951 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003952
Anders Carlsson525b76b2009-10-16 02:48:28 +00003953 // Reject any other conversions to non-scalar types.
3954 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3955 << castType << castExpr->getSourceRange();
3956 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003957
3958 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00003959 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003960 return Diag(castExpr->getLocStart(),
3961 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003962 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00003963 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003964
3965 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00003966 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003967
Anders Carlsson525b76b2009-10-16 02:48:28 +00003968 if (castType->isVectorType())
3969 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3970 if (castExpr->getType()->isVectorType())
3971 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3972
Anders Carlsson43d70f82009-10-16 05:23:41 +00003973 if (isa<ObjCSelectorExpr>(castExpr))
3974 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003975
Anders Carlsson525b76b2009-10-16 02:48:28 +00003976 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00003977 QualType castExprType = castExpr->getType();
Douglas Gregor6972a622010-06-16 00:35:25 +00003978 if (!castExprType->isIntegralType(Context) &&
Douglas Gregorb90df602010-06-16 00:17:44 +00003979 castExprType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00003980 return Diag(castExpr->getLocStart(),
3981 diag::err_cast_pointer_from_non_pointer_int)
3982 << castExprType << castExpr->getSourceRange();
3983 } else if (!castExpr->getType()->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00003984 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00003985 return Diag(castExpr->getLocStart(),
3986 diag::err_cast_pointer_to_non_pointer_int)
3987 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003988 }
Anders Carlsson094c4592009-10-18 18:12:03 +00003989
3990 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
John McCall2b5c1b22010-08-12 21:44:57 +00003991
3992 if (Kind == CastExpr::CK_Unknown || Kind == CastExpr::CK_BitCast)
3993 CheckCastAlign(castExpr, castType, TyR);
3994
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003995 return false;
3996}
3997
Anders Carlsson525b76b2009-10-16 02:48:28 +00003998bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3999 CastExpr::CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004000 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004001
Anders Carlssonde71adf2007-11-27 05:51:55 +00004002 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004003 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004004 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004005 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004006 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004007 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004008 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004009 } else
4010 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004011 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004012 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004013
Anders Carlsson525b76b2009-10-16 02:48:28 +00004014 Kind = CastExpr::CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004015 return false;
4016}
4017
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004018bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
Anders Carlsson43d70f82009-10-16 05:23:41 +00004019 CastExpr::CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004020 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004021
Anders Carlsson43d70f82009-10-16 05:23:41 +00004022 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004023
Nate Begemanc8961a42009-06-27 22:05:55 +00004024 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4025 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00004026 if (SrcTy->isVectorType()) {
4027 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
4028 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4029 << DestTy << SrcTy << R;
Anders Carlsson43d70f82009-10-16 05:23:41 +00004030 Kind = CastExpr::CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00004031 return false;
4032 }
4033
Nate Begemanbd956c42009-06-28 02:36:38 +00004034 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004035 // conversion will take place first from scalar to elt type, and then
4036 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004037 if (SrcTy->isPointerType())
4038 return Diag(R.getBegin(),
4039 diag::err_invalid_conversion_between_vector_and_scalar)
4040 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004041
4042 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4043 ImpCastExprToType(CastExpr, DestElemTy,
4044 getScalarCastKind(Context, SrcTy, DestElemTy));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004045
Anders Carlsson43d70f82009-10-16 05:23:41 +00004046 Kind = CastExpr::CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00004047 return false;
4048}
4049
John McCalldadc5752010-08-24 06:29:42 +00004050ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004051Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004052 SourceLocation RParenLoc, Expr *castExpr) {
4053 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004054 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004055
John McCall97513962010-01-15 18:39:57 +00004056 TypeSourceInfo *castTInfo;
4057 QualType castType = GetTypeFromParser(Ty, &castTInfo);
4058 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00004059 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00004060
Nate Begeman5ec4b312009-08-10 23:49:36 +00004061 // If the Expr being casted is a ParenListExpr, handle it specially.
4062 if (isa<ParenListExpr>(castExpr))
John McCallb268a282010-08-23 23:25:46 +00004063 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCalle15bbff2010-01-18 19:35:47 +00004064 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00004065
John McCallb268a282010-08-23 23:25:46 +00004066 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00004067}
4068
John McCalldadc5752010-08-24 06:29:42 +00004069ExprResult
John McCallebe54742010-01-15 18:56:44 +00004070Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00004071 SourceLocation RParenLoc, Expr *castExpr) {
John McCallebe54742010-01-15 18:56:44 +00004072 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
John McCallcf142162010-08-07 06:22:56 +00004073 CXXCastPath BasePath;
John McCallebe54742010-01-15 18:56:44 +00004074 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
Anders Carlssona70cff62010-04-24 19:06:50 +00004075 Kind, BasePath))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004076 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00004077
John McCallcf142162010-08-07 06:22:56 +00004078 return Owned(CStyleCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +00004079 Ty->getType().getNonLValueExprType(Context),
John McCallcf142162010-08-07 06:22:56 +00004080 Kind, castExpr, &BasePath, Ty,
4081 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004082}
4083
Nate Begeman5ec4b312009-08-10 23:49:36 +00004084/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4085/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004086ExprResult
John McCallb268a282010-08-23 23:25:46 +00004087Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004088 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4089 if (!E)
4090 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00004091
John McCalldadc5752010-08-24 06:29:42 +00004092 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004093
Nate Begeman5ec4b312009-08-10 23:49:36 +00004094 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004095 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4096 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004097
John McCallb268a282010-08-23 23:25:46 +00004098 if (Result.isInvalid()) return ExprError();
4099
4100 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004101}
4102
John McCalldadc5752010-08-24 06:29:42 +00004103ExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00004104Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00004105 SourceLocation RParenLoc, Expr *Op,
John McCalle15bbff2010-01-18 19:35:47 +00004106 TypeSourceInfo *TInfo) {
John McCallb268a282010-08-23 23:25:46 +00004107 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCalle15bbff2010-01-18 19:35:47 +00004108 QualType Ty = TInfo->getType();
John Thompson781ad172010-06-30 22:55:51 +00004109 bool isAltiVecLiteral = false;
Mike Stump11289f42009-09-09 15:08:12 +00004110
John Thompson781ad172010-06-30 22:55:51 +00004111 // Check for an altivec literal,
4112 // i.e. all the elements are integer constants.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004113 if (getLangOptions().AltiVec && Ty->isVectorType()) {
4114 if (PE->getNumExprs() == 0) {
4115 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
4116 return ExprError();
4117 }
John Thompson781ad172010-06-30 22:55:51 +00004118 if (PE->getNumExprs() == 1) {
4119 if (!PE->getExpr(0)->getType()->isVectorType())
4120 isAltiVecLiteral = true;
4121 }
4122 else
4123 isAltiVecLiteral = true;
4124 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00004125
John Thompson781ad172010-06-30 22:55:51 +00004126 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
4127 // then handle it as such.
4128 if (isAltiVecLiteral) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004129 llvm::SmallVector<Expr *, 8> initExprs;
4130 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
4131 initExprs.push_back(PE->getExpr(i));
4132
4133 // FIXME: This means that pretty-printing the final AST will produce curly
4134 // braces instead of the original commas.
Ted Kremenekac034612010-04-13 23:39:13 +00004135 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
4136 &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00004137 initExprs.size(), RParenLoc);
4138 E->setType(Ty);
John McCallb268a282010-08-23 23:25:46 +00004139 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004140 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004141 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00004142 // sequence of BinOp comma operators.
John McCalldadc5752010-08-24 06:29:42 +00004143 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCallb268a282010-08-23 23:25:46 +00004144 if (Result.isInvalid()) return ExprError();
4145 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004146 }
4147}
4148
John McCalldadc5752010-08-24 06:29:42 +00004149ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00004150 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004151 MultiExprArg Val,
John McCallba7bf592010-08-24 05:47:05 +00004152 ParsedType TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004153 unsigned nexprs = Val.size();
4154 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004155 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4156 Expr *expr;
4157 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4158 expr = new (Context) ParenExpr(L, R, exprs[0]);
4159 else
4160 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004161 return Owned(expr);
4162}
4163
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004164/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4165/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004166/// C99 6.5.15
4167QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
4168 SourceLocation QuestionLoc) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004169 // C++ is sufficiently different to merit its own checker.
4170 if (getLangOptions().CPlusPlus)
4171 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
4172
Chris Lattner432cff52009-02-18 04:28:32 +00004173 UsualUnaryConversions(Cond);
4174 UsualUnaryConversions(LHS);
4175 UsualUnaryConversions(RHS);
4176 QualType CondTy = Cond->getType();
4177 QualType LHSTy = LHS->getType();
4178 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004179
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004180 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004181 if (!CondTy->isScalarType()) { // C99 6.5.15p2
4182 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4183 << CondTy;
4184 return QualType();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004185 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004186
Chris Lattnere2949f42008-01-06 22:42:25 +00004187 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004188 if (LHSTy->isVectorType() || RHSTy->isVectorType())
4189 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00004190
Chris Lattnere2949f42008-01-06 22:42:25 +00004191 // If both operands have arithmetic type, do the usual arithmetic conversions
4192 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004193 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4194 UsualArithmeticConversions(LHS, RHS);
4195 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004196 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004197
Chris Lattnere2949f42008-01-06 22:42:25 +00004198 // If both operands are the same structure or union type, the result is that
4199 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004200 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4201 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004202 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004203 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004204 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004205 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004206 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004207 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004208
Chris Lattnere2949f42008-01-06 22:42:25 +00004209 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004210 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004211 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4212 if (!LHSTy->isVoidType())
4213 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4214 << RHS->getSourceRange();
4215 if (!RHSTy->isVoidType())
4216 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4217 << LHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004218 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
4219 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00004220 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00004221 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00004222 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4223 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00004224 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004225 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004226 // promote the null to a pointer.
4227 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00004228 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004229 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004230 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004231 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004232 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00004233 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004234 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004235
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004236 // All objective-c pointer type analysis is done here.
4237 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4238 QuestionLoc);
4239 if (!compositeType.isNull())
4240 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004241
4242
Steve Naroff05efa972009-07-01 14:36:47 +00004243 // Handle block pointer types.
4244 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4245 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4246 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4247 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004248 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4249 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004250 return destType;
4251 }
4252 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004253 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004254 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00004255 }
Steve Naroff05efa972009-07-01 14:36:47 +00004256 // We have 2 block pointer types.
4257 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4258 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00004259 return LHSTy;
4260 }
Steve Naroff05efa972009-07-01 14:36:47 +00004261 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004262 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4263 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004264
Steve Naroff05efa972009-07-01 14:36:47 +00004265 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4266 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00004267 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004268 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00004269 // In this situation, we assume void* type. No especially good
4270 // reason, but this is what gcc does, and we do have to pick
4271 // to get a consistent AST.
4272 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004273 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4274 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00004275 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004276 }
Steve Naroff05efa972009-07-01 14:36:47 +00004277 // The block pointer types are compatible.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004278 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4279 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00004280 return LHSTy;
4281 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004282
Steve Naroff05efa972009-07-01 14:36:47 +00004283 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4284 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4285 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004286 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4287 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00004288
4289 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4290 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4291 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00004292 QualType destPointee
4293 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004294 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004295 // Add qualifiers if necessary.
4296 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4297 // Promote to void*.
4298 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004299 return destType;
4300 }
4301 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004302 QualType destPointee
4303 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004304 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004305 // Add qualifiers if necessary.
Eli Friedmanb0bc5592009-11-17 01:22:05 +00004306 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004307 // Promote to void*.
Eli Friedmanb0bc5592009-11-17 01:22:05 +00004308 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004309 return destType;
4310 }
4311
4312 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4313 // Two identical pointer types are always compatible.
4314 return LHSTy;
4315 }
4316 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4317 rhptee.getUnqualifiedType())) {
4318 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4319 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4320 // In this situation, we assume void* type. No especially good
4321 // reason, but this is what gcc does, and we do have to pick
4322 // to get a consistent AST.
4323 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004324 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4325 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004326 return incompatTy;
4327 }
4328 // The pointer types are compatible.
4329 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4330 // differently qualified versions of compatible types, the result type is
4331 // a pointer to an appropriately qualified version of the *composite*
4332 // type.
4333 // FIXME: Need to calculate the composite type.
4334 // FIXME: Need to add qualifiers
Eli Friedman06ed2a52009-10-20 08:27:19 +00004335 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4336 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004337 return LHSTy;
4338 }
Mike Stump11289f42009-09-09 15:08:12 +00004339
Steve Naroff05efa972009-07-01 14:36:47 +00004340 // GCC compatibility: soften pointer/integer mismatch.
4341 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4342 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4343 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004344 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004345 return RHSTy;
4346 }
4347 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4348 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4349 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004350 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004351 return LHSTy;
4352 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00004353
Chris Lattnere2949f42008-01-06 22:42:25 +00004354 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004355 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4356 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004357 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004358}
4359
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004360/// FindCompositeObjCPointerType - Helper method to find composite type of
4361/// two objective-c pointer types of the two input expressions.
4362QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4363 SourceLocation QuestionLoc) {
4364 QualType LHSTy = LHS->getType();
4365 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004366
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004367 // Handle things like Class and struct objc_class*. Here we case the result
4368 // to the pseudo-builtin, because that will be implicitly cast back to the
4369 // redefinition type if an attempt is made to access its fields.
4370 if (LHSTy->isObjCClassType() &&
4371 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4372 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4373 return LHSTy;
4374 }
4375 if (RHSTy->isObjCClassType() &&
4376 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4377 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4378 return RHSTy;
4379 }
4380 // And the same for struct objc_object* / id
4381 if (LHSTy->isObjCIdType() &&
4382 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4383 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4384 return LHSTy;
4385 }
4386 if (RHSTy->isObjCIdType() &&
4387 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4388 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4389 return RHSTy;
4390 }
4391 // And the same for struct objc_selector* / SEL
4392 if (Context.isObjCSelType(LHSTy) &&
4393 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4394 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4395 return LHSTy;
4396 }
4397 if (Context.isObjCSelType(RHSTy) &&
4398 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4399 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4400 return RHSTy;
4401 }
4402 // Check constraints for Objective-C object pointers types.
4403 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004404
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004405 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4406 // Two identical object pointer types are always compatible.
4407 return LHSTy;
4408 }
4409 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4410 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4411 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004412
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004413 // If both operands are interfaces and either operand can be
4414 // assigned to the other, use that type as the composite
4415 // type. This allows
4416 // xxx ? (A*) a : (B*) b
4417 // where B is a subclass of A.
4418 //
4419 // Additionally, as for assignment, if either type is 'id'
4420 // allow silent coercion. Finally, if the types are
4421 // incompatible then make sure to use 'id' as the composite
4422 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004423
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004424 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4425 // It could return the composite type.
4426 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4427 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4428 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4429 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4430 } else if ((LHSTy->isObjCQualifiedIdType() ||
4431 RHSTy->isObjCQualifiedIdType()) &&
4432 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4433 // Need to handle "id<xx>" explicitly.
4434 // GCC allows qualified id and any Objective-C type to devolve to
4435 // id. Currently localizing to here until clear this should be
4436 // part of ObjCQualifiedIdTypesAreCompatible.
4437 compositeType = Context.getObjCIdType();
4438 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4439 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004440 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004441 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4442 ;
4443 else {
4444 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4445 << LHSTy << RHSTy
4446 << LHS->getSourceRange() << RHS->getSourceRange();
4447 QualType incompatTy = Context.getObjCIdType();
4448 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4449 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4450 return incompatTy;
4451 }
4452 // The object pointer types are compatible.
4453 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4454 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
4455 return compositeType;
4456 }
4457 // Check Objective-C object pointer types and 'void *'
4458 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4459 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4460 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4461 QualType destPointee
4462 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4463 QualType destType = Context.getPointerType(destPointee);
4464 // Add qualifiers if necessary.
4465 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4466 // Promote to void*.
4467 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4468 return destType;
4469 }
4470 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4471 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4472 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4473 QualType destPointee
4474 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4475 QualType destType = Context.getPointerType(destPointee);
4476 // Add qualifiers if necessary.
4477 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4478 // Promote to void*.
4479 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4480 return destType;
4481 }
4482 return QualType();
4483}
4484
Steve Naroff83895f72007-09-16 03:34:24 +00004485/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004486/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00004487ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004488 SourceLocation ColonLoc,
John McCallb268a282010-08-23 23:25:46 +00004489 Expr *CondExpr, Expr *LHSExpr,
4490 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00004491 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4492 // was the condition.
4493 bool isLHSNull = LHSExpr == 0;
4494 if (isLHSNull)
4495 LHSExpr = CondExpr;
Sebastian Redlb5d49352009-01-19 22:31:54 +00004496
4497 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattnerdaaa9f22007-07-16 21:39:03 +00004498 RHSExpr, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00004499 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004500 return ExprError();
4501
Douglas Gregor7e112b02009-08-26 14:37:04 +00004502 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Narofff6009ed2009-01-21 00:14:39 +00004503 isLHSNull ? 0 : LHSExpr,
Douglas Gregor7e112b02009-08-26 14:37:04 +00004504 ColonLoc, RHSExpr, result));
Chris Lattnere168f762006-11-10 05:29:30 +00004505}
4506
Steve Naroff3f597292007-05-11 22:18:03 +00004507// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00004508// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00004509// routine is it effectively iqnores the qualifiers on the top level pointee.
4510// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4511// FIXME: add a couple examples in this comment.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004512Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00004513Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Steve Naroff3f597292007-05-11 22:18:03 +00004514 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004515
David Chisnall9f57c292009-08-17 16:35:33 +00004516 if ((lhsType->isObjCClassType() &&
4517 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4518 (rhsType->isObjCClassType() &&
4519 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4520 return Compatible;
4521 }
4522
Steve Naroff1f4d7272007-05-11 04:00:31 +00004523 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004524 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4525 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004526
Steve Naroff1f4d7272007-05-11 04:00:31 +00004527 // make sure we operate on the canonical type
Chris Lattner574dee62008-07-26 22:17:49 +00004528 lhptee = Context.getCanonicalType(lhptee);
4529 rhptee = Context.getCanonicalType(rhptee);
Steve Naroff1f4d7272007-05-11 04:00:31 +00004530
Chris Lattner9bad62c2008-01-04 18:04:52 +00004531 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004532
4533 // C99 6.5.16.1p1: This following citation is common to constraints
4534 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4535 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianece85822009-02-17 18:27:45 +00004536 // FIXME: Handle ExtQualType
Douglas Gregor9a657932008-10-21 23:43:52 +00004537 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner9bad62c2008-01-04 18:04:52 +00004538 ConvTy = CompatiblePointerDiscardsQualifiers;
Steve Naroff3f597292007-05-11 22:18:03 +00004539
Mike Stump4e1f26a2009-02-19 03:04:26 +00004540 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4541 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00004542 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00004543 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004544 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004545 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004546
Chris Lattner0a788432008-01-03 22:56:36 +00004547 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004548 assert(rhptee->isFunctionType());
4549 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004550 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004551
Chris Lattner0a788432008-01-03 22:56:36 +00004552 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004553 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004554 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00004555
4556 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004557 assert(lhptee->isFunctionType());
4558 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004559 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004560 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00004561 // unqualified versions of compatible types, ...
Eli Friedman80160bd2009-03-22 23:59:44 +00004562 lhptee = lhptee.getUnqualifiedType();
4563 rhptee = rhptee.getUnqualifiedType();
4564 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4565 // Check if the pointee types are compatible ignoring the sign.
4566 // We explicitly check for char so that we catch "char" vs
4567 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00004568 if (lhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004569 lhptee = Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00004570 else if (lhptee->hasSignedIntegerRepresentation())
Eli Friedman80160bd2009-03-22 23:59:44 +00004571 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004572
Chris Lattnerec3a1562009-10-17 20:33:28 +00004573 if (rhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004574 rhptee = Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00004575 else if (rhptee->hasSignedIntegerRepresentation())
Eli Friedman80160bd2009-03-22 23:59:44 +00004576 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00004577
Eli Friedman80160bd2009-03-22 23:59:44 +00004578 if (lhptee == rhptee) {
4579 // Types are compatible ignoring the sign. Qualifier incompatibility
4580 // takes priority over sign incompatibility because the sign
4581 // warning can be disabled.
4582 if (ConvTy != Compatible)
4583 return ConvTy;
4584 return IncompatiblePointerSign;
4585 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004586
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004587 // If we are a multi-level pointer, it's possible that our issue is simply
4588 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4589 // the eventual target type is the same and the pointers have the same
4590 // level of indirection, this must be the issue.
4591 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4592 do {
4593 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4594 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004595
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004596 lhptee = Context.getCanonicalType(lhptee);
4597 rhptee = Context.getCanonicalType(rhptee);
4598 } while (lhptee->isPointerType() && rhptee->isPointerType());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004599
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004600 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Alexis Hunt6f3de502009-11-08 07:46:34 +00004601 return IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004602 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004603
Eli Friedman80160bd2009-03-22 23:59:44 +00004604 // General pointer incompatibility takes priority over qualifiers.
Mike Stump11289f42009-09-09 15:08:12 +00004605 return IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00004606 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00004607 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00004608}
4609
Steve Naroff081c7422008-09-04 15:10:53 +00004610/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4611/// block pointer types are compatible or whether a block and normal pointer
4612/// are compatible. It is more restrict than comparing two function pointer
4613// types.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004614Sema::AssignConvertType
4615Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff081c7422008-09-04 15:10:53 +00004616 QualType rhsType) {
4617 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004618
Steve Naroff081c7422008-09-04 15:10:53 +00004619 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004620 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4621 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004622
Steve Naroff081c7422008-09-04 15:10:53 +00004623 // make sure we operate on the canonical type
4624 lhptee = Context.getCanonicalType(lhptee);
4625 rhptee = Context.getCanonicalType(rhptee);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004626
Steve Naroff081c7422008-09-04 15:10:53 +00004627 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004628
Steve Naroff081c7422008-09-04 15:10:53 +00004629 // For blocks we enforce that qualifiers are identical.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004630 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff081c7422008-09-04 15:10:53 +00004631 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004632
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004633 if (!getLangOptions().CPlusPlus) {
4634 if (!Context.typesAreBlockPointerCompatible(lhsType, rhsType))
4635 return IncompatibleBlockPointer;
4636 }
4637 else if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump4e1f26a2009-02-19 03:04:26 +00004638 return IncompatibleBlockPointer;
Steve Naroff081c7422008-09-04 15:10:53 +00004639 return ConvTy;
4640}
4641
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004642/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4643/// for assignment compatibility.
4644Sema::AssignConvertType
4645Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00004646 if (lhsType->isObjCBuiltinType()) {
4647 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00004648 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
4649 !rhsType->isObjCQualifiedClassType())
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00004650 return IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004651 return Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00004652 }
4653 if (rhsType->isObjCBuiltinType()) {
4654 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00004655 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
4656 !lhsType->isObjCQualifiedClassType())
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00004657 return IncompatiblePointer;
4658 return Compatible;
4659 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004660 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004661 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004662 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004663 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4664 // make sure we operate on the canonical type
4665 lhptee = Context.getCanonicalType(lhptee);
4666 rhptee = Context.getCanonicalType(rhptee);
4667 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4668 return CompatiblePointerDiscardsQualifiers;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004669
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004670 if (Context.typesAreCompatible(lhsType, rhsType))
4671 return Compatible;
4672 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4673 return IncompatibleObjCQualifiedId;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004674 return IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004675}
4676
Mike Stump4e1f26a2009-02-19 03:04:26 +00004677/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4678/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00004679/// pointers. Here are some objectionable examples that GCC considers warnings:
4680///
4681/// int a, *pint;
4682/// short *pshort;
4683/// struct foo *pfoo;
4684///
4685/// pint = pshort; // warning: assignment from incompatible pointer type
4686/// a = pint; // warning: assignment makes integer from pointer without a cast
4687/// pint = a; // warning: assignment makes pointer from integer without a cast
4688/// pint = pfoo; // warning: assignment from incompatible pointer type
4689///
4690/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00004691/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00004692///
Chris Lattner9bad62c2008-01-04 18:04:52 +00004693Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00004694Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnera52c2f22008-01-04 23:18:45 +00004695 // Get canonical types. We're not formatting these types, just comparing
4696 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00004697 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4698 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00004699
4700 if (lhsType == rhsType)
Chris Lattnerf5c973d2008-01-07 17:51:46 +00004701 return Compatible; // Common case: fast path an exact match.
Steve Naroff44fd8ff2007-07-24 21:46:40 +00004702
David Chisnall9f57c292009-08-17 16:35:33 +00004703 if ((lhsType->isObjCClassType() &&
4704 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4705 (rhsType->isObjCClassType() &&
4706 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4707 return Compatible;
4708 }
4709
Douglas Gregor6b754842008-10-28 00:22:11 +00004710 // If the left-hand side is a reference type, then we are in a
4711 // (rare!) case where we've allowed the use of references in C,
4712 // e.g., as a parameter type in a built-in function. In this case,
4713 // just make sure that the type referenced is compatible with the
4714 // right-hand side type. The caller is responsible for adjusting
4715 // lhsType so that the resulting expression does not have reference
4716 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004717 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor6b754842008-10-28 00:22:11 +00004718 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson24ebce62007-10-12 23:56:29 +00004719 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004720 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00004721 }
Nate Begemanbd956c42009-06-28 02:36:38 +00004722 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4723 // to the same ExtVector type.
4724 if (lhsType->isExtVectorType()) {
4725 if (rhsType->isExtVectorType())
4726 return lhsType == rhsType ? Compatible : Incompatible;
Douglas Gregora3208f92010-06-22 23:41:02 +00004727 if (rhsType->isArithmeticType())
Nate Begemanbd956c42009-06-28 02:36:38 +00004728 return Compatible;
4729 }
Mike Stump11289f42009-09-09 15:08:12 +00004730
Nate Begeman191a6b12008-07-14 18:02:46 +00004731 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004732 if (lhsType->isVectorType() && rhsType->isVectorType()) {
4733 // If we are allowing lax vector conversions, and LHS and RHS are both
4734 // vectors, the total size only needs to be the same. This is a bitcast;
4735 // no bits are changed but the result type is different.
4736 if (getLangOptions().LaxVectorConversions &&
4737 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)))
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004738 return IncompatibleVectors;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004739
4740 // Allow assignments of an AltiVec vector type to an equivalent GCC
4741 // vector type and vice versa
4742 if (Context.areCompatibleVectorTypes(lhsType, rhsType))
4743 return Compatible;
Chris Lattner881a2122008-01-04 23:32:24 +00004744 }
4745 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004746 }
Eli Friedman3360d892008-05-30 18:07:22 +00004747
Douglas Gregorbea453a2010-05-23 21:53:47 +00004748 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
4749 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType()))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004750 return Compatible;
Eli Friedman3360d892008-05-30 18:07:22 +00004751
Chris Lattnerec646832008-04-07 06:49:41 +00004752 if (isa<PointerType>(lhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00004753 if (rhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00004754 return IntToPointer;
Eli Friedman3360d892008-05-30 18:07:22 +00004755
Chris Lattnerec646832008-04-07 06:49:41 +00004756 if (isa<PointerType>(rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004757 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004758
Steve Naroffaccc4882009-07-20 17:56:53 +00004759 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004760 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004761 if (lhsType->isVoidPointerType()) // an exception to the rule.
4762 return Compatible;
4763 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004764 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004765 if (rhsType->getAs<BlockPointerType>()) {
4766 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004767 return Compatible;
Steve Naroff32d072c2008-09-29 18:10:17 +00004768
4769 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004770 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00004771 return Compatible;
4772 }
Steve Naroff081c7422008-09-04 15:10:53 +00004773 return Incompatible;
4774 }
4775
4776 if (isa<BlockPointerType>(lhsType)) {
4777 if (rhsType->isIntegerType())
Eli Friedman8163b7a2009-02-25 04:20:42 +00004778 return IntToBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004779
Steve Naroff32d072c2008-09-29 18:10:17 +00004780 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004781 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00004782 return Compatible;
4783
Steve Naroff081c7422008-09-04 15:10:53 +00004784 if (rhsType->isBlockPointerType())
4785 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004786
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004787 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff081c7422008-09-04 15:10:53 +00004788 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004789 return Compatible;
Steve Naroff081c7422008-09-04 15:10:53 +00004790 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00004791 return Incompatible;
4792 }
4793
Steve Naroff7cae42b2009-07-10 23:34:53 +00004794 if (isa<ObjCObjectPointerType>(lhsType)) {
4795 if (rhsType->isIntegerType())
4796 return IntToPointer;
Mike Stump11289f42009-09-09 15:08:12 +00004797
Steve Naroffaccc4882009-07-20 17:56:53 +00004798 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004799 if (isa<PointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004800 if (rhsType->isVoidPointerType()) // an exception to the rule.
4801 return Compatible;
4802 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004803 }
4804 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004805 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004806 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004807 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004808 if (RHSPT->getPointeeType()->isVoidType())
4809 return Compatible;
4810 }
4811 // Treat block pointers as objects.
4812 if (rhsType->isBlockPointerType())
4813 return Compatible;
4814 return Incompatible;
4815 }
Chris Lattnerec646832008-04-07 06:49:41 +00004816 if (isa<PointerType>(rhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00004817 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman3360d892008-05-30 18:07:22 +00004818 if (lhsType == Context.BoolTy)
4819 return Compatible;
4820
4821 if (lhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00004822 return PointerToInt;
Steve Naroff98cf3e92007-06-06 18:38:38 +00004823
Mike Stump4e1f26a2009-02-19 03:04:26 +00004824 if (isa<PointerType>(lhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004825 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004826
4827 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004828 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004829 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004830 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004831 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004832 if (isa<ObjCObjectPointerType>(rhsType)) {
4833 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4834 if (lhsType == Context.BoolTy)
4835 return Compatible;
4836
4837 if (lhsType->isIntegerType())
4838 return PointerToInt;
4839
Steve Naroffaccc4882009-07-20 17:56:53 +00004840 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004841 if (isa<PointerType>(lhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004842 if (lhsType->isVoidPointerType()) // an exception to the rule.
4843 return Compatible;
4844 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004845 }
4846 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004847 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004848 return Compatible;
4849 return Incompatible;
4850 }
Eli Friedman3360d892008-05-30 18:07:22 +00004851
Chris Lattnera52c2f22008-01-04 23:18:45 +00004852 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattnerec646832008-04-07 06:49:41 +00004853 if (Context.typesAreCompatible(lhsType, rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004854 return Compatible;
Bill Wendling216423b2007-05-30 06:30:29 +00004855 }
Steve Naroff98cf3e92007-06-06 18:38:38 +00004856 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00004857}
4858
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004859/// \brief Constructs a transparent union from an expression that is
4860/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00004861static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004862 QualType UnionType, FieldDecl *Field) {
4863 // Build an initializer list that designates the appropriate member
4864 // of the transparent union.
Ted Kremenekac034612010-04-13 23:39:13 +00004865 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00004866 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004867 SourceLocation());
4868 Initializer->setType(UnionType);
4869 Initializer->setInitializedFieldInUnion(Field);
4870
4871 // Build a compound literal constructing a value of the transparent
4872 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00004873 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall5d7aa7f2010-01-19 22:33:45 +00004874 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCalle15bbff2010-01-18 19:35:47 +00004875 Initializer, false);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004876}
4877
4878Sema::AssignConvertType
4879Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4880 QualType FromType = rExpr->getType();
4881
Mike Stump11289f42009-09-09 15:08:12 +00004882 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004883 // transparent_union GCC extension.
4884 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004885 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004886 return Incompatible;
4887
4888 // The field to initialize within the transparent union.
4889 RecordDecl *UD = UT->getDecl();
4890 FieldDecl *InitField = 0;
4891 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004892 for (RecordDecl::field_iterator it = UD->field_begin(),
4893 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004894 it != itend; ++it) {
4895 if (it->getType()->isPointerType()) {
4896 // If the transparent union contains a pointer type, we allow:
4897 // 1) void pointer
4898 // 2) null pointer constant
4899 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004900 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004901 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004902 InitField = *it;
4903 break;
4904 }
Mike Stump11289f42009-09-09 15:08:12 +00004905
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004906 if (rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00004907 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004908 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004909 InitField = *it;
4910 break;
4911 }
4912 }
4913
4914 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4915 == Compatible) {
4916 InitField = *it;
4917 break;
4918 }
4919 }
4920
4921 if (!InitField)
4922 return Incompatible;
4923
4924 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4925 return Compatible;
4926}
4927
Chris Lattner9bad62c2008-01-04 18:04:52 +00004928Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004929Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00004930 if (getLangOptions().CPlusPlus) {
4931 if (!lhsType->isRecordType()) {
4932 // C++ 5.17p3: If the left operand is not of class type, the
4933 // expression is implicitly converted (C++ 4) to the
4934 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00004935 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00004936 AA_Assigning))
Douglas Gregor9a657932008-10-21 23:43:52 +00004937 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00004938 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00004939 }
4940
4941 // FIXME: Currently, we fall through and treat C++ classes like C
4942 // structures.
4943 }
4944
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004945 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4946 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00004947 if ((lhsType->isPointerType() ||
4948 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00004949 lhsType->isBlockPointerType())
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004950 && rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00004951 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004952 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004953 return Compatible;
4954 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004955
Chris Lattnere6dcd502007-10-16 02:55:40 +00004956 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004957 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00004958 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00004959 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00004960 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00004961 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00004962 if (!lhsType->isReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +00004963 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004964
Chris Lattner9bad62c2008-01-04 18:04:52 +00004965 Sema::AssignConvertType result =
4966 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00004967
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004968 // C99 6.5.16.1p2: The value of the right operand is converted to the
4969 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00004970 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4971 // so that we can use references in built-in functions even in C.
4972 // The getNonReferenceType() call makes sure that the resulting expression
4973 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004974 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregora8a089b2010-07-13 18:40:04 +00004975 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context),
Eli Friedman06ed2a52009-10-20 08:27:19 +00004976 CastExpr::CK_Unknown);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004977 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004978}
4979
Chris Lattner326f7572008-11-18 01:30:42 +00004980QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00004981 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00004982 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004983 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00004984 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00004985}
4986
Chris Lattnerfaa54172010-01-12 21:23:57 +00004987QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00004988 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004989 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00004990 QualType lhsType =
4991 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4992 QualType rhsType =
4993 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004994
Nate Begeman191a6b12008-07-14 18:02:46 +00004995 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004996 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00004997 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00004998
Nate Begeman191a6b12008-07-14 18:02:46 +00004999 // Handle the case of a vector & extvector type of the same size and element
5000 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005001 if (getLangOptions().LaxVectorConversions) {
5002 // FIXME: Should we warn here?
John McCall9dd450b2009-09-21 23:43:11 +00005003 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
5004 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begeman191a6b12008-07-14 18:02:46 +00005005 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005006 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005007 if (lhsType->isExtVectorType()) {
5008 ImpCastExprToType(rex, lhsType, CastExpr::CK_BitCast);
5009 return lhsType;
5010 }
5011
5012 ImpCastExprToType(lex, rhsType, CastExpr::CK_BitCast);
5013 return rhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005014 }
5015 }
5016 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005017
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005018 // Handle the case of equivalent AltiVec and GCC vector types
5019 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5020 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5021 ImpCastExprToType(lex, rhsType, CastExpr::CK_BitCast);
5022 return rhsType;
5023 }
5024
Nate Begemanbd956c42009-06-28 02:36:38 +00005025 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5026 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5027 bool swapped = false;
5028 if (rhsType->isExtVectorType()) {
5029 swapped = true;
5030 std::swap(rex, lex);
5031 std::swap(rhsType, lhsType);
5032 }
Mike Stump11289f42009-09-09 15:08:12 +00005033
Nate Begeman886448d2009-06-28 19:12:57 +00005034 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00005035 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005036 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005037 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005038 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005039 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00005040 if (swapped) std::swap(rex, lex);
5041 return lhsType;
5042 }
5043 }
5044 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5045 rhsType->isRealFloatingType()) {
5046 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005047 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00005048 if (swapped) std::swap(rex, lex);
5049 return lhsType;
5050 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005051 }
5052 }
Mike Stump11289f42009-09-09 15:08:12 +00005053
Nate Begeman886448d2009-06-28 19:12:57 +00005054 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00005055 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005056 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00005057 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005058 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005059}
5060
Chris Lattnerfaa54172010-01-12 21:23:57 +00005061QualType Sema::CheckMultiplyDivideOperands(
5062 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00005063 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005064 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005065
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005066 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005067
Chris Lattnerfaa54172010-01-12 21:23:57 +00005068 if (!lex->getType()->isArithmeticType() ||
5069 !rex->getType()->isArithmeticType())
5070 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005071
Chris Lattnerfaa54172010-01-12 21:23:57 +00005072 // Check for division by zero.
5073 if (isDiv &&
5074 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005075 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
Chris Lattner70117952010-01-12 21:30:55 +00005076 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005077
Chris Lattnerfaa54172010-01-12 21:23:57 +00005078 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005079}
5080
Chris Lattnerfaa54172010-01-12 21:23:57 +00005081QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00005082 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005083 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005084 if (lex->getType()->hasIntegerRepresentation() &&
5085 rex->getType()->hasIntegerRepresentation())
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005086 return CheckVectorOperands(Loc, lex, rex);
5087 return InvalidOperands(Loc, lex, rex);
5088 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005089
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005090 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005091
Chris Lattnerfaa54172010-01-12 21:23:57 +00005092 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
5093 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005094
Chris Lattnerfaa54172010-01-12 21:23:57 +00005095 // Check for remainder by zero.
5096 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattner70117952010-01-12 21:30:55 +00005097 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
5098 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005099
Chris Lattnerfaa54172010-01-12 21:23:57 +00005100 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005101}
5102
Chris Lattnerfaa54172010-01-12 21:23:57 +00005103QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00005104 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005105 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5106 QualType compType = CheckVectorOperands(Loc, lex, rex);
5107 if (CompLHSTy) *CompLHSTy = compType;
5108 return compType;
5109 }
Steve Naroff7a5af782007-07-13 16:58:59 +00005110
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005111 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00005112
Steve Naroffe4718892007-04-27 18:30:00 +00005113 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005114 if (lex->getType()->isArithmeticType() &&
5115 rex->getType()->isArithmeticType()) {
5116 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005117 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005118 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00005119
Eli Friedman8e122982008-05-18 18:08:51 +00005120 // Put any potential pointer into PExp
5121 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00005122 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00005123 std::swap(PExp, IExp);
5124
Steve Naroff6b712a72009-07-14 18:25:06 +00005125 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005126
Eli Friedman8e122982008-05-18 18:08:51 +00005127 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005128 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005129
Chris Lattner12bdebb2009-04-24 23:50:08 +00005130 // Check for arithmetic on pointers to incomplete types.
5131 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00005132 if (getLangOptions().CPlusPlus) {
5133 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00005134 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00005135 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00005136 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005137
5138 // GNU extension: arithmetic on pointer to void
5139 Diag(Loc, diag::ext_gnu_void_ptr)
5140 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00005141 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00005142 if (getLangOptions().CPlusPlus) {
5143 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
5144 << lex->getType() << lex->getSourceRange();
5145 return QualType();
5146 }
5147
5148 // GNU extension: arithmetic on pointer to function
5149 Diag(Loc, diag::ext_gnu_ptr_func_arith)
5150 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00005151 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005152 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00005153 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00005154 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005155 PExp->getType()->isObjCObjectPointerType()) &&
5156 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00005157 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5158 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005159 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005160 return QualType();
5161 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00005162 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00005163 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00005164 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5165 << PointeeTy << PExp->getSourceRange();
5166 return QualType();
5167 }
Mike Stump11289f42009-09-09 15:08:12 +00005168
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005169 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00005170 QualType LHSTy = Context.isPromotableBitField(lex);
5171 if (LHSTy.isNull()) {
5172 LHSTy = lex->getType();
5173 if (LHSTy->isPromotableIntegerType())
5174 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005175 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005176 *CompLHSTy = LHSTy;
5177 }
Eli Friedman8e122982008-05-18 18:08:51 +00005178 return PExp->getType();
5179 }
5180 }
5181
Chris Lattner326f7572008-11-18 01:30:42 +00005182 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005183}
5184
Chris Lattner2a3569b2008-04-07 05:30:13 +00005185// C99 6.5.6
5186QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005187 SourceLocation Loc, QualType* CompLHSTy) {
5188 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5189 QualType compType = CheckVectorOperands(Loc, lex, rex);
5190 if (CompLHSTy) *CompLHSTy = compType;
5191 return compType;
5192 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005193
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005194 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005195
Chris Lattner4d62f422007-12-09 21:53:25 +00005196 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005197
Chris Lattner4d62f422007-12-09 21:53:25 +00005198 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00005199 if (lex->getType()->isArithmeticType()
5200 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005201 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005202 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005203 }
Mike Stump11289f42009-09-09 15:08:12 +00005204
Chris Lattner4d62f422007-12-09 21:53:25 +00005205 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00005206 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00005207 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005208
Douglas Gregorac1fb652009-03-24 19:52:54 +00005209 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005210
Douglas Gregorac1fb652009-03-24 19:52:54 +00005211 bool ComplainAboutVoid = false;
5212 Expr *ComplainAboutFunc = 0;
5213 if (lpointee->isVoidType()) {
5214 if (getLangOptions().CPlusPlus) {
5215 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5216 << lex->getSourceRange() << rex->getSourceRange();
5217 return QualType();
5218 }
5219
5220 // GNU C extension: arithmetic on pointer to void
5221 ComplainAboutVoid = true;
5222 } else if (lpointee->isFunctionType()) {
5223 if (getLangOptions().CPlusPlus) {
5224 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005225 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00005226 return QualType();
5227 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005228
5229 // GNU C extension: arithmetic on pointer to function
5230 ComplainAboutFunc = lex;
5231 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00005232 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00005233 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00005234 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005235 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00005236 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005237
Chris Lattner12bdebb2009-04-24 23:50:08 +00005238 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00005239 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00005240 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5241 << lpointee << lex->getSourceRange();
5242 return QualType();
5243 }
Mike Stump11289f42009-09-09 15:08:12 +00005244
Chris Lattner4d62f422007-12-09 21:53:25 +00005245 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00005246 if (rex->getType()->isIntegerType()) {
5247 if (ComplainAboutVoid)
5248 Diag(Loc, diag::ext_gnu_void_ptr)
5249 << lex->getSourceRange() << rex->getSourceRange();
5250 if (ComplainAboutFunc)
5251 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00005252 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00005253 << ComplainAboutFunc->getSourceRange();
5254
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005255 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005256 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005257 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005258
Chris Lattner4d62f422007-12-09 21:53:25 +00005259 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005260 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00005261 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005262
Douglas Gregorac1fb652009-03-24 19:52:54 +00005263 // RHS must be a completely-type object type.
5264 // Handle the GNU void* extension.
5265 if (rpointee->isVoidType()) {
5266 if (getLangOptions().CPlusPlus) {
5267 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5268 << lex->getSourceRange() << rex->getSourceRange();
5269 return QualType();
5270 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005271
Douglas Gregorac1fb652009-03-24 19:52:54 +00005272 ComplainAboutVoid = true;
5273 } else if (rpointee->isFunctionType()) {
5274 if (getLangOptions().CPlusPlus) {
5275 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005276 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00005277 return QualType();
5278 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005279
5280 // GNU extension: arithmetic on pointer to function
5281 if (!ComplainAboutFunc)
5282 ComplainAboutFunc = rex;
5283 } else if (!rpointee->isDependentType() &&
5284 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00005285 PDiag(diag::err_typecheck_sub_ptr_object)
5286 << rex->getSourceRange()
5287 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00005288 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005289
Eli Friedman168fe152009-05-16 13:54:38 +00005290 if (getLangOptions().CPlusPlus) {
5291 // Pointee types must be the same: C++ [expr.add]
5292 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5293 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5294 << lex->getType() << rex->getType()
5295 << lex->getSourceRange() << rex->getSourceRange();
5296 return QualType();
5297 }
5298 } else {
5299 // Pointee types must be compatible C99 6.5.6p3
5300 if (!Context.typesAreCompatible(
5301 Context.getCanonicalType(lpointee).getUnqualifiedType(),
5302 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5303 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5304 << lex->getType() << rex->getType()
5305 << lex->getSourceRange() << rex->getSourceRange();
5306 return QualType();
5307 }
Chris Lattner4d62f422007-12-09 21:53:25 +00005308 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005309
Douglas Gregorac1fb652009-03-24 19:52:54 +00005310 if (ComplainAboutVoid)
5311 Diag(Loc, diag::ext_gnu_void_ptr)
5312 << lex->getSourceRange() << rex->getSourceRange();
5313 if (ComplainAboutFunc)
5314 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00005315 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00005316 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005317
5318 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005319 return Context.getPointerDiffType();
5320 }
5321 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005322
Chris Lattner326f7572008-11-18 01:30:42 +00005323 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00005324}
5325
Chris Lattner2a3569b2008-04-07 05:30:13 +00005326// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00005327QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattner2a3569b2008-04-07 05:30:13 +00005328 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00005329 // C99 6.5.7p2: Each of the operands shall have integer type.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005330 if (!lex->getType()->hasIntegerRepresentation() ||
5331 !rex->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00005332 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005333
Nate Begemane46ee9a2009-10-25 02:26:48 +00005334 // Vector shifts promote their scalar inputs to vector type.
5335 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5336 return CheckVectorOperands(Loc, lex, rex);
5337
Chris Lattner5c11c412007-12-12 05:47:28 +00005338 // Shifts don't perform usual arithmetic conversions, they just do integer
5339 // promotions on each operand. C99 6.5.7p3
Eli Friedman629ffb92009-08-20 04:21:42 +00005340 QualType LHSTy = Context.isPromotableBitField(lex);
5341 if (LHSTy.isNull()) {
5342 LHSTy = lex->getType();
5343 if (LHSTy->isPromotableIntegerType())
5344 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005345 }
Chris Lattner3c133402007-12-13 07:28:16 +00005346 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +00005347 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005348
Chris Lattner5c11c412007-12-12 05:47:28 +00005349 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005350
Ryan Flynnf53fab82009-08-07 16:20:20 +00005351 // Sanity-check shift operands
5352 llvm::APSInt Right;
5353 // Check right/shifter operand
Daniel Dunbar687fa862009-09-17 06:31:27 +00005354 if (!rex->isValueDependent() &&
5355 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn2f085712009-08-08 19:18:23 +00005356 if (Right.isNegative())
Ryan Flynnf53fab82009-08-07 16:20:20 +00005357 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
5358 else {
5359 llvm::APInt LeftBits(Right.getBitWidth(),
5360 Context.getTypeSize(lex->getType()));
5361 if (Right.uge(LeftBits))
5362 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
5363 }
5364 }
5365
Chris Lattner5c11c412007-12-12 05:47:28 +00005366 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005367 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005368}
5369
Chandler Carruth17773fc2010-07-10 12:30:03 +00005370static bool IsWithinTemplateSpecialization(Decl *D) {
5371 if (DeclContext *DC = D->getDeclContext()) {
5372 if (isa<ClassTemplateSpecializationDecl>(DC))
5373 return true;
5374 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
5375 return FD->isFunctionTemplateSpecialization();
5376 }
5377 return false;
5378}
5379
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005380// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00005381QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005382 unsigned OpaqueOpc, bool isRelational) {
5383 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5384
Chris Lattner9a152e22009-12-05 05:40:13 +00005385 // Handle vector comparisons separately.
Nate Begeman191a6b12008-07-14 18:02:46 +00005386 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005387 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005388
Steve Naroff31090012007-07-16 21:54:35 +00005389 QualType lType = lex->getType();
5390 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005391
Douglas Gregor4ffbad12010-06-22 22:12:46 +00005392 if (!lType->hasFloatingRepresentation() &&
5393 !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00005394 // For non-floating point types, check for self-comparisons of the form
5395 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5396 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00005397 //
5398 // NOTE: Don't warn about comparison expressions resulting from macro
5399 // expansion. Also don't warn about comparisons which are only self
5400 // comparisons within a template specialization. The warnings should catch
5401 // obvious cases in the definition of the template anyways. The idea is to
5402 // warn when the typed comparison operator will always evaluate to the same
5403 // result.
Chris Lattner222b8bd2009-03-08 19:39:53 +00005404 Expr *LHSStripped = lex->IgnoreParens();
5405 Expr *RHSStripped = rex->IgnoreParens();
Chandler Carruth17773fc2010-07-10 12:30:03 +00005406 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00005407 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Chandler Carruth65a38182010-07-12 06:23:38 +00005408 if (DRL->getDecl() == DRR->getDecl() && !Loc.isMacroID() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00005409 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Douglas Gregorec170db2010-06-08 19:50:34 +00005410 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
5411 << 0 // self-
5412 << (Opc == BinaryOperator::EQ
5413 || Opc == BinaryOperator::LE
5414 || Opc == BinaryOperator::GE));
5415 } else if (lType->isArrayType() && rType->isArrayType() &&
5416 !DRL->getDecl()->getType()->isReferenceType() &&
5417 !DRR->getDecl()->getType()->isReferenceType()) {
5418 // what is it always going to eval to?
5419 char always_evals_to;
5420 switch(Opc) {
5421 case BinaryOperator::EQ: // e.g. array1 == array2
5422 always_evals_to = 0; // false
5423 break;
5424 case BinaryOperator::NE: // e.g. array1 != array2
5425 always_evals_to = 1; // true
5426 break;
5427 default:
5428 // best we can say is 'a constant'
5429 always_evals_to = 2; // e.g. array1 <= array2
5430 break;
5431 }
5432 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
5433 << 1 // array
5434 << always_evals_to);
5435 }
5436 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00005437 }
Mike Stump11289f42009-09-09 15:08:12 +00005438
Chris Lattner222b8bd2009-03-08 19:39:53 +00005439 if (isa<CastExpr>(LHSStripped))
5440 LHSStripped = LHSStripped->IgnoreParenCasts();
5441 if (isa<CastExpr>(RHSStripped))
5442 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005443
Chris Lattner222b8bd2009-03-08 19:39:53 +00005444 // Warn about comparisons against a string constant (unless the other
5445 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005446 Expr *literalString = 0;
5447 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00005448 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005449 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005450 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005451 literalString = lex;
5452 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00005453 } else if ((isa<StringLiteral>(RHSStripped) ||
5454 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005455 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005456 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005457 literalString = rex;
5458 literalStringStripped = RHSStripped;
5459 }
5460
5461 if (literalString) {
5462 std::string resultComparison;
5463 switch (Opc) {
5464 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5465 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5466 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5467 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5468 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5469 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5470 default: assert(false && "Invalid comparison operator");
5471 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005472
Douglas Gregor49862b82010-01-12 23:18:54 +00005473 DiagRuntimeBehavior(Loc,
5474 PDiag(diag::warn_stringcompare)
5475 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00005476 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005477 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00005478 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005479
Douglas Gregorec170db2010-06-08 19:50:34 +00005480 // C99 6.5.8p3 / C99 6.5.9p4
5481 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5482 UsualArithmeticConversions(lex, rex);
5483 else {
5484 UsualUnaryConversions(lex);
5485 UsualUnaryConversions(rex);
5486 }
5487
5488 lType = lex->getType();
5489 rType = rex->getType();
5490
Douglas Gregorca63811b2008-11-19 03:25:36 +00005491 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner9a152e22009-12-05 05:40:13 +00005492 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregorca63811b2008-11-19 03:25:36 +00005493
Chris Lattnerb620c342007-08-26 01:18:55 +00005494 if (isRelational) {
5495 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00005496 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00005497 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00005498 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00005499 if (lType->hasFloatingRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00005500 CheckFloatComparison(Loc,lex,rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005501
Chris Lattnerb620c342007-08-26 01:18:55 +00005502 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00005503 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00005504 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005505
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005506 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005507 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005508 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005509 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005510
Douglas Gregorf267edd2010-06-15 21:38:40 +00005511 // All of the following pointer-related warnings are GCC extensions, except
5512 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00005513 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00005514 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005515 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00005516 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005517 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00005518
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005519 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00005520 if (LCanPointeeTy == RCanPointeeTy)
5521 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00005522 if (!isRelational &&
5523 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5524 // Valid unless comparison between non-null pointer and function pointer
5525 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00005526 // In a SFINAE context, we treat this as a hard error to maintain
5527 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00005528 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5529 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00005530 Diag(Loc,
5531 isSFINAEContext()?
5532 diag::err_typecheck_comparison_of_fptr_to_void
5533 : diag::ext_typecheck_comparison_of_fptr_to_void)
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00005534 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00005535
5536 if (isSFINAEContext())
5537 return QualType();
5538
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00005539 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5540 return ResultTy;
5541 }
5542 }
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005543 // C++ [expr.rel]p2:
5544 // [...] Pointer conversions (4.10) and qualification
5545 // conversions (4.4) are performed on pointer operands (or on
5546 // a pointer operand and a null pointer constant) to bring
5547 // them to their composite pointer type. [...]
5548 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005549 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005550 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005551 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00005552 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005553 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005554 if (T.isNull()) {
5555 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5556 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5557 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005558 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005559 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005560 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005561 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005562 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005563 }
5564
Eli Friedman06ed2a52009-10-20 08:27:19 +00005565 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5566 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005567 return ResultTy;
5568 }
Eli Friedman16c209612009-08-23 00:27:47 +00005569 // C99 6.5.9p2 and C99 6.5.8p2
5570 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5571 RCanPointeeTy.getUnqualifiedType())) {
5572 // Valid unless a relational comparison of function pointers
5573 if (isRelational && LCanPointeeTy->isFunctionType()) {
5574 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5575 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5576 }
5577 } else if (!isRelational &&
5578 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5579 // Valid unless comparison between non-null pointer and function pointer
5580 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5581 && !LHSIsNull && !RHSIsNull) {
5582 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5583 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5584 }
5585 } else {
5586 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00005587 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005588 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00005589 }
Eli Friedman16c209612009-08-23 00:27:47 +00005590 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman06ed2a52009-10-20 08:27:19 +00005591 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005592 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00005593 }
Mike Stump11289f42009-09-09 15:08:12 +00005594
Sebastian Redl576fd422009-05-10 18:38:11 +00005595 if (getLangOptions().CPlusPlus) {
Mike Stump11289f42009-09-09 15:08:12 +00005596 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005597 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00005598 if (RHSIsNull &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005599 (lType->isPointerType() ||
5600 (!isRelational && lType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00005601 ImpCastExprToType(rex, lType,
5602 lType->isMemberPointerType()
5603 ? CastExpr::CK_NullToMemberPointer
5604 : CastExpr::CK_IntegralToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00005605 return ResultTy;
5606 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005607 if (LHSIsNull &&
5608 (rType->isPointerType() ||
5609 (!isRelational && rType->isMemberPointerType()))) {
Douglas Gregorf58ff322010-08-07 13:36:37 +00005610 ImpCastExprToType(lex, rType,
5611 rType->isMemberPointerType()
5612 ? CastExpr::CK_NullToMemberPointer
5613 : CastExpr::CK_IntegralToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00005614 return ResultTy;
5615 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005616
5617 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00005618 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005619 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5620 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005621 // In addition, pointers to members can be compared, or a pointer to
5622 // member and a null pointer constant. Pointer to member conversions
5623 // (4.11) and qualification conversions (4.4) are performed to bring
5624 // them to a common type. If one operand is a null pointer constant,
5625 // the common type is the type of the other operand. Otherwise, the
5626 // common type is a pointer to member type similar (4.4) to the type
5627 // of one of the operands, with a cv-qualification signature (4.4)
5628 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005629 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005630 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00005631 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005632 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005633 if (T.isNull()) {
5634 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005635 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005636 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005637 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005638 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005639 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005640 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005641 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005642 }
Mike Stump11289f42009-09-09 15:08:12 +00005643
Eli Friedman06ed2a52009-10-20 08:27:19 +00005644 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5645 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005646 return ResultTy;
5647 }
Mike Stump11289f42009-09-09 15:08:12 +00005648
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005649 // Comparison of nullptr_t with itself.
Sebastian Redl576fd422009-05-10 18:38:11 +00005650 if (lType->isNullPtrType() && rType->isNullPtrType())
5651 return ResultTy;
5652 }
Mike Stump11289f42009-09-09 15:08:12 +00005653
Steve Naroff081c7422008-09-04 15:10:53 +00005654 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00005655 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005656 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5657 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005658
Steve Naroff081c7422008-09-04 15:10:53 +00005659 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00005660 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005661 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005662 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00005663 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005664 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005665 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00005666 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00005667 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00005668 if (!isRelational
5669 && ((lType->isBlockPointerType() && rType->isPointerType())
5670 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00005671 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005672 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00005673 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005674 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00005675 ->getPointeeType()->isVoidType())))
5676 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5677 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00005678 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005679 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005680 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00005681 }
Steve Naroff081c7422008-09-04 15:10:53 +00005682
Steve Naroff7cae42b2009-07-10 23:34:53 +00005683 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00005684 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005685 const PointerType *LPT = lType->getAs<PointerType>();
5686 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005687 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00005688 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005689 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00005690 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005691
Steve Naroff753567f2008-11-17 19:49:16 +00005692 if (!LPtrToVoid && !RPtrToVoid &&
5693 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005694 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005695 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00005696 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005697 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005698 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00005699 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005700 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005701 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005702 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5703 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00005704 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005705 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00005706 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00005707 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00005708 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
5709 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00005710 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00005711 bool isError = false;
5712 if ((LHSIsNull && lType->isIntegerType()) ||
5713 (RHSIsNull && rType->isIntegerType())) {
5714 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00005715 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00005716 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00005717 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00005718 else if (getLangOptions().CPlusPlus) {
5719 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
5720 isError = true;
5721 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00005722 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00005723
Chris Lattnerd99bd522009-08-23 00:03:44 +00005724 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005725 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00005726 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00005727 if (isError)
5728 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00005729 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00005730
5731 if (lType->isIntegerType())
5732 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00005733 else
Douglas Gregorf267edd2010-06-15 21:38:40 +00005734 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005735 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00005736 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00005737
Steve Naroff4b191572008-09-04 16:56:14 +00005738 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00005739 if (!isRelational && RHSIsNull
5740 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005741 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005742 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00005743 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00005744 if (!isRelational && LHSIsNull
5745 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005746 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005747 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00005748 }
Chris Lattner326f7572008-11-18 01:30:42 +00005749 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005750}
5751
Nate Begeman191a6b12008-07-14 18:02:46 +00005752/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00005753/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00005754/// like a scalar comparison, a vector comparison produces a vector of integer
5755/// types.
5756QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00005757 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00005758 bool isRelational) {
5759 // Check to make sure we're operating on vectors of the same type and width,
5760 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00005761 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00005762 if (vType.isNull())
5763 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005764
Nate Begeman191a6b12008-07-14 18:02:46 +00005765 QualType lType = lex->getType();
5766 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005767
Nate Begeman191a6b12008-07-14 18:02:46 +00005768 // For non-floating point types, check for self-comparisons of the form
5769 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5770 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00005771 if (!lType->hasFloatingRepresentation()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00005772 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5773 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5774 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregorec170db2010-06-08 19:50:34 +00005775 DiagRuntimeBehavior(Loc,
5776 PDiag(diag::warn_comparison_always)
5777 << 0 // self-
5778 << 2 // "a constant"
5779 );
Nate Begeman191a6b12008-07-14 18:02:46 +00005780 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005781
Nate Begeman191a6b12008-07-14 18:02:46 +00005782 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00005783 if (!isRelational && lType->hasFloatingRepresentation()) {
5784 assert (rType->hasFloatingRepresentation());
Chris Lattner326f7572008-11-18 01:30:42 +00005785 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00005786 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005787
Nate Begeman191a6b12008-07-14 18:02:46 +00005788 // Return the type for the comparison, which is the same as vector type for
5789 // integer vectors, or an integer type of identical size and number of
5790 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005791 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00005792 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005793
John McCall9dd450b2009-09-21 23:43:11 +00005794 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00005795 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005796 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00005797 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00005798 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005799 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5800
Mike Stump4e1f26a2009-02-19 03:04:26 +00005801 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005802 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00005803 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5804}
5805
Steve Naroff218bc2b2007-05-04 21:54:46 +00005806inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00005807 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005808 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5809 if (lex->getType()->hasIntegerRepresentation() &&
5810 rex->getType()->hasIntegerRepresentation())
5811 return CheckVectorOperands(Loc, lex, rex);
5812
5813 return InvalidOperands(Loc, lex, rex);
5814 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005815
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005816 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005817
Steve Naroffdbd9e892007-07-17 00:58:39 +00005818 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005819 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00005820 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005821}
5822
Steve Naroff218bc2b2007-05-04 21:54:46 +00005823inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner8406c512010-07-13 19:41:32 +00005824 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
5825
5826 // Diagnose cases where the user write a logical and/or but probably meant a
5827 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
5828 // is a constant.
5829 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
Eli Friedman6b197e02010-07-27 19:14:53 +00005830 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
Chris Lattnerdeee7a32010-07-15 00:26:43 +00005831 // Don't warn in macros.
Chris Lattner938533d2010-07-24 01:10:11 +00005832 !Loc.isMacroID()) {
5833 // If the RHS can be constant folded, and if it constant folds to something
5834 // that isn't 0 or 1 (which indicate a potential logical operation that
5835 // happened to fold to true/false) then warn.
5836 Expr::EvalResult Result;
5837 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
5838 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
5839 Diag(Loc, diag::warn_logical_instead_of_bitwise)
5840 << rex->getSourceRange()
5841 << (Opc == BinaryOperator::LAnd ? "&&" : "||")
5842 << (Opc == BinaryOperator::LAnd ? "&" : "|");
5843 }
5844 }
Chris Lattner8406c512010-07-13 19:41:32 +00005845
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005846 if (!Context.getLangOptions().CPlusPlus) {
5847 UsualUnaryConversions(lex);
5848 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005849
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005850 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5851 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005852
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005853 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00005854 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005855
John McCall4a2429a2010-06-04 00:29:51 +00005856 // The following is safe because we only use this method for
5857 // non-overloadable operands.
5858
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005859 // C++ [expr.log.and]p1
5860 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00005861 // The operands are both contextually converted to type bool.
5862 if (PerformContextuallyConvertToBool(lex) ||
5863 PerformContextuallyConvertToBool(rex))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005864 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005865
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005866 // C++ [expr.log.and]p2
5867 // C++ [expr.log.or]p2
5868 // The result is a bool.
5869 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00005870}
5871
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005872/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5873/// is a read-only property; return true if so. A readonly property expression
5874/// depends on various declarations and thus must be treated specially.
5875///
Mike Stump11289f42009-09-09 15:08:12 +00005876static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005877 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5878 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5879 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5880 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005881 if (const ObjCObjectPointerType *OPT =
Steve Naroff7cae42b2009-07-10 23:34:53 +00005882 BaseType->getAsObjCInterfacePointerType())
5883 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5884 if (S.isPropertyReadonly(PDecl, IFace))
5885 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005886 }
5887 }
5888 return false;
5889}
5890
Chris Lattner30bd3272008-11-18 01:22:49 +00005891/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5892/// emit an error and return true. If so, return false.
5893static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005894 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00005895 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005896 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005897 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5898 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00005899 if (IsLV == Expr::MLV_Valid)
5900 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005901
Chris Lattner30bd3272008-11-18 01:22:49 +00005902 unsigned Diag = 0;
5903 bool NeedType = false;
5904 switch (IsLV) { // C99 6.5.16p2
Chris Lattner30bd3272008-11-18 01:22:49 +00005905 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005906 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00005907 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5908 NeedType = true;
5909 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005910 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00005911 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5912 NeedType = true;
5913 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00005914 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00005915 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5916 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00005917 case Expr::MLV_Valid:
5918 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00005919 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00005920 case Expr::MLV_MemberFunction:
5921 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00005922 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5923 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005924 case Expr::MLV_IncompleteType:
5925 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00005926 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00005927 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00005928 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00005929 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00005930 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5931 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00005932 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00005933 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5934 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00005935 case Expr::MLV_ReadonlyProperty:
5936 Diag = diag::error_readonly_property_assignment;
5937 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00005938 case Expr::MLV_NoSetterProperty:
5939 Diag = diag::error_nosetter_property_assignment;
5940 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00005941 case Expr::MLV_SubObjCPropertySetting:
5942 Diag = diag::error_no_subobject_property_setting;
5943 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005944 }
Steve Naroffad373bd2007-07-31 12:34:36 +00005945
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005946 SourceRange Assign;
5947 if (Loc != OrigLoc)
5948 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00005949 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005950 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00005951 else
Mike Stump11289f42009-09-09 15:08:12 +00005952 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00005953 return true;
5954}
5955
5956
5957
5958// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00005959QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5960 SourceLocation Loc,
5961 QualType CompoundType) {
5962 // Verify that LHS is a modifiable lvalue, and emit error if not.
5963 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00005964 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00005965
5966 QualType LHSType = LHS->getType();
5967 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005968 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00005969 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00005970 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00005971 // Simple assignment "x = y".
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00005972 if (const ObjCImplicitSetterGetterRefExpr *OISGE =
5973 dyn_cast<ObjCImplicitSetterGetterRefExpr>(LHS)) {
5974 // If using property-dot syntax notation for assignment, and there is a
5975 // setter, RHS expression is being passed to the setter argument. So,
5976 // type conversion (and comparison) is RHS to setter's argument type.
5977 if (const ObjCMethodDecl *SetterMD = OISGE->getSetterMethod()) {
5978 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
5979 LHSTy = (*P)->getType();
5980 }
5981 }
5982
5983 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005984 // Special case of NSObject attributes on c-style pointer types.
5985 if (ConvTy == IncompatiblePointer &&
5986 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00005987 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005988 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00005989 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005990 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005991
Chris Lattnerea714382008-08-21 18:04:13 +00005992 // If the RHS is a unary plus or minus, check to see if they = and + are
5993 // right next to each other. If so, the user may have typo'd "x =+ 4"
5994 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00005995 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00005996 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5997 RHSCheck = ICE->getSubExpr();
5998 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5999 if ((UO->getOpcode() == UnaryOperator::Plus ||
6000 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00006001 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00006002 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00006003 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
6004 // And there is a space or other character before the subexpr of the
6005 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00006006 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
6007 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00006008 Diag(Loc, diag::warn_not_compound_assign)
6009 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
6010 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00006011 }
Chris Lattnerea714382008-08-21 18:04:13 +00006012 }
6013 } else {
6014 // Compound assignment "x += y"
Eli Friedmanb05c41e2009-05-16 05:56:02 +00006015 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006016 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00006017
Chris Lattner326f7572008-11-18 01:30:42 +00006018 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006019 RHS, AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00006020 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006021
Chris Lattner39561062010-07-07 06:14:23 +00006022
6023 // Check to see if the destination operand is a dereferenced null pointer. If
6024 // so, and if not volatile-qualified, this is undefined behavior that the
6025 // optimizer will delete, so warn about it. People sometimes try to use this
6026 // to get a deterministic trap and are surprised by clang's behavior. This
6027 // only handles the pattern "*null = whatever", which is a very syntactic
6028 // check.
6029 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
6030 if (UO->getOpcode() == UnaryOperator::Deref &&
6031 UO->getSubExpr()->IgnoreParenCasts()->
6032 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
6033 !UO->getType().isVolatileQualified()) {
6034 Diag(UO->getOperatorLoc(), diag::warn_indirection_through_null)
6035 << UO->getSubExpr()->getSourceRange();
6036 Diag(UO->getOperatorLoc(), diag::note_indirection_through_null);
6037 }
6038
Steve Naroff98cf3e92007-06-06 18:38:38 +00006039 // C99 6.5.16p3: The type of an assignment expression is the type of the
6040 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00006041 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00006042 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
6043 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00006044 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00006045 // operand.
Chris Lattner326f7572008-11-18 01:30:42 +00006046 return LHSType.getUnqualifiedType();
Steve Naroffae4143e2007-04-26 20:39:23 +00006047}
6048
Chris Lattner326f7572008-11-18 01:30:42 +00006049// C99 6.5.17
6050QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00006051 DiagnoseUnusedExprResult(LHS);
6052
Chris Lattnerf6e1e302008-07-25 20:54:07 +00006053 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Douglas Gregorb92a1562010-02-03 00:27:59 +00006054 // C++ does not perform this conversion (C++ [expr.comma]p1).
6055 if (!getLangOptions().CPlusPlus)
6056 DefaultFunctionArrayLvalueConversion(RHS);
Eli Friedmanba961a92009-03-23 00:24:07 +00006057
6058 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
6059 // incomplete in C++).
6060
Chris Lattner326f7572008-11-18 01:30:42 +00006061 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00006062}
6063
Steve Naroff7a5af782007-07-13 16:58:59 +00006064/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
6065/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle10c2c32008-12-20 09:35:34 +00006066QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
Alexis Huntc46382e2010-04-28 23:02:27 +00006067 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006068 if (Op->isTypeDependent())
6069 return Context.DependentTy;
6070
Chris Lattner6b0cf142008-11-21 07:05:48 +00006071 QualType ResType = Op->getType();
6072 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00006073
Sebastian Redle10c2c32008-12-20 09:35:34 +00006074 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
6075 // Decrement of bool is not allowed.
6076 if (!isInc) {
6077 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
6078 return QualType();
6079 }
6080 // Increment of bool sets it to true, but is deprecated.
6081 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
6082 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00006083 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00006084 } else if (ResType->isAnyPointerType()) {
6085 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006086
Chris Lattner6b0cf142008-11-21 07:05:48 +00006087 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00006088 if (PointeeTy->isVoidType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006089 if (getLangOptions().CPlusPlus) {
6090 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
6091 << Op->getSourceRange();
6092 return QualType();
6093 }
6094
6095 // Pointer to void is a GNU extension in C.
Chris Lattner6b0cf142008-11-21 07:05:48 +00006096 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006097 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006098 if (getLangOptions().CPlusPlus) {
6099 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
6100 << Op->getType() << Op->getSourceRange();
6101 return QualType();
6102 }
6103
6104 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006105 << ResType << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006106 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlsson029fc692009-08-26 22:59:12 +00006107 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00006108 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006109 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00006110 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00006111 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006112 else if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Fariborz Jahanianca75db72009-07-16 17:59:14 +00006113 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6114 << PointeeTy << Op->getSourceRange();
6115 return QualType();
6116 }
Eli Friedman090addd2010-01-03 00:20:48 +00006117 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00006118 // C99 does not support ++/-- on complex types, we allow as an extension.
6119 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006120 << ResType << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00006121 } else {
6122 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00006123 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00006124 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00006125 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006126 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00006127 // Now make sure the operand is a modifiable lvalue.
Chris Lattner6b0cf142008-11-21 07:05:48 +00006128 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Steve Naroff35d85152007-05-07 00:24:15 +00006129 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00006130 // In C++, a prefix increment is the same type as the operand. Otherwise
6131 // (in C or with postfix), the increment is the unqualified type of the
6132 // operand.
6133 return isPrefix && getLangOptions().CPlusPlus
6134 ? ResType : ResType.getUnqualifiedType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00006135}
6136
Anders Carlsson806700f2008-02-01 07:15:58 +00006137/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00006138/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00006139/// where the declaration is needed for type checking. We only need to
6140/// handle cases when the expression references a function designator
6141/// or is an lvalue. Here are some examples:
6142/// - &(x) => x
6143/// - &*****f => f for f a function designator.
6144/// - &s.xx => s
6145/// - &s.zz[1].yy -> s, if zz is an array
6146/// - *(x + 1) -> x, if x is an array
6147/// - &"123"[2] -> 0
6148/// - & __real__ x -> x
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006149static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00006150 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00006151 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00006152 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00006153 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00006154 // If this is an arrow operator, the address is an offset from
6155 // the base's value, so the object the base refers to is
6156 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00006157 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00006158 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00006159 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00006160 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00006161 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00006162 // FIXME: This code shouldn't be necessary! We should catch the implicit
6163 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00006164 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
6165 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
6166 if (ICE->getSubExpr()->getType()->isArrayType())
6167 return getPrimaryDecl(ICE->getSubExpr());
6168 }
6169 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00006170 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00006171 case Stmt::UnaryOperatorClass: {
6172 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006173
Daniel Dunbarb692ef42008-08-04 20:02:37 +00006174 switch(UO->getOpcode()) {
Daniel Dunbarb692ef42008-08-04 20:02:37 +00006175 case UnaryOperator::Real:
6176 case UnaryOperator::Imag:
6177 case UnaryOperator::Extension:
6178 return getPrimaryDecl(UO->getSubExpr());
6179 default:
6180 return 0;
6181 }
6182 }
Steve Naroff47500512007-04-19 23:00:49 +00006183 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00006184 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00006185 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00006186 // If the result of an implicit cast is an l-value, we care about
6187 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00006188 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00006189 default:
6190 return 0;
6191 }
6192}
6193
6194/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00006195/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00006196/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006197/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00006198/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006199/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00006200/// we allow the '&' but retain the overloaded-function type.
Steve Naroff35d85152007-05-07 00:24:15 +00006201QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00006202 // Make sure to ignore parentheses in subsequent checks
6203 op = op->IgnoreParens();
6204
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00006205 if (op->isTypeDependent())
6206 return Context.DependentTy;
6207
Steve Naroff826e91a2008-01-13 17:10:08 +00006208 if (getLangOptions().C99) {
6209 // Implement C99-only parts of addressof rules.
6210 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
6211 if (uOp->getOpcode() == UnaryOperator::Deref)
6212 // Per C99 6.5.3.2, the address of a deref always returns a valid result
6213 // (assuming the deref expression is valid).
6214 return uOp->getSubExpr()->getType();
6215 }
6216 // Technically, there should be a check for array subscript
6217 // expressions here, but the result of one is always an lvalue anyway.
6218 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006219 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner67315442008-07-26 21:30:36 +00006220 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00006221
Sebastian Redl9a8dd0d2010-01-11 15:56:56 +00006222 MemberExpr *ME = dyn_cast<MemberExpr>(op);
6223 if (lval == Expr::LV_MemberFunction && ME &&
6224 isa<CXXMethodDecl>(ME->getMemberDecl())) {
6225 ValueDecl *dcl = cast<MemberExpr>(op)->getMemberDecl();
6226 // &f where f is a member of the current object, or &o.f, or &p->f
6227 // All these are not allowed, and we need to catch them before the dcl
6228 // branch of the if, below.
6229 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
6230 << dcl;
6231 // FIXME: Improve this diagnostic and provide a fixit.
6232
6233 // Now recover by acting as if the function had been accessed qualified.
6234 return Context.getMemberPointerType(op->getType(),
6235 Context.getTypeDeclType(cast<RecordDecl>(dcl->getDeclContext()))
6236 .getTypePtr());
Chris Lattner9156f1b2010-07-05 19:17:26 +00006237 }
6238
6239 if (lval == Expr::LV_ClassTemporary) {
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006240 Diag(OpLoc, isSFINAEContext()? diag::err_typecheck_addrof_class_temporary
6241 : diag::ext_typecheck_addrof_class_temporary)
6242 << op->getType() << op->getSourceRange();
6243 if (isSFINAEContext())
6244 return QualType();
Chris Lattner93b28362010-07-05 19:36:34 +00006245 } else if (isa<ObjCSelectorExpr>(op))
Chris Lattner9156f1b2010-07-05 19:17:26 +00006246 return Context.getPointerType(op->getType());
Chris Lattner93b28362010-07-05 19:36:34 +00006247 else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00006248 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00006249 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00006250 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00006251 // FIXME: emit more specific diag...
Chris Lattnerf490e152008-11-19 05:27:50 +00006252 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
6253 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00006254 return QualType();
6255 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00006256 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00006257 // The operand cannot be a bit-field
6258 Diag(OpLoc, diag::err_typecheck_address_of)
6259 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00006260 return QualType();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00006261 } else if (op->refersToVectorElement()) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00006262 // The operand cannot be an element of a vector
Chris Lattner29e812b2008-11-20 06:06:08 +00006263 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00006264 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00006265 return QualType();
Fariborz Jahanian385db802009-07-07 18:50:52 +00006266 } else if (isa<ObjCPropertyRefExpr>(op)) {
6267 // cannot take address of a property expression.
6268 Diag(OpLoc, diag::err_typecheck_address_of)
6269 << "property expression" << op->getSourceRange();
6270 return QualType();
Anders Carlsson3fa58d12009-09-14 23:15:26 +00006271 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
6272 // FIXME: Can LHS ever be null here?
Anders Carlsson01ccf992009-09-15 16:03:44 +00006273 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
6274 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
Eli Friedman7fd55442010-08-24 05:23:20 +00006275 } else if (isa<OverloadExpr>(op)) {
John McCalld14a8642009-11-21 08:51:07 +00006276 return Context.OverloadTy;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00006277 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00006278 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00006279 // with the register storage-class specifier.
6280 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Steve Naroff35d85152007-05-07 00:24:15 +00006281 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner29e812b2008-11-20 06:06:08 +00006282 Diag(OpLoc, diag::err_typecheck_address_of)
6283 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00006284 return QualType();
6285 }
John McCalld14a8642009-11-21 08:51:07 +00006286 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006287 return Context.OverloadTy;
Anders Carlsson0b675f52009-07-08 21:45:58 +00006288 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00006289 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00006290 // Could be a pointer to member, though, if there is an explicit
6291 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006292 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00006293 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00006294 if (Ctx && Ctx->isRecord()) {
6295 if (FD->getType()->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006296 Diag(OpLoc,
Anders Carlsson0b675f52009-07-08 21:45:58 +00006297 diag::err_cannot_form_pointer_to_member_of_reference_type)
6298 << FD->getDeclName() << FD->getType();
6299 return QualType();
6300 }
Mike Stump11289f42009-09-09 15:08:12 +00006301
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00006302 return Context.getMemberPointerType(op->getType(),
6303 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00006304 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00006305 }
Anders Carlsson5b535762009-05-16 21:43:42 +00006306 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes5773a1b2008-12-16 22:58:26 +00006307 // Okay: we can take the address of a function.
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006308 // As above.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006309 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
6310 MD->isInstance())
Anders Carlsson5b535762009-05-16 21:43:42 +00006311 return Context.getMemberPointerType(op->getType(),
6312 Context.getTypeDeclType(MD->getParent()).getTypePtr());
6313 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00006314 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00006315 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006316
Eli Friedmance7f9002009-05-16 23:27:50 +00006317 if (lval == Expr::LV_IncompleteVoidType) {
6318 // Taking the address of a void variable is technically illegal, but we
6319 // allow it in cases which are otherwise valid.
6320 // Example: "extern void x; void* y = &x;".
6321 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
6322 }
6323
Steve Naroff47500512007-04-19 23:00:49 +00006324 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00006325 if (op->getType()->isObjCObjectType())
6326 return Context.getObjCObjectPointerType(op->getType());
Steve Naroff35d85152007-05-07 00:24:15 +00006327 return Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00006328}
6329
Chris Lattner9156f1b2010-07-05 19:17:26 +00006330/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006331QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006332 if (Op->isTypeDependent())
6333 return Context.DependentTy;
6334
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006335 UsualUnaryConversions(Op);
Chris Lattner9156f1b2010-07-05 19:17:26 +00006336 QualType OpTy = Op->getType();
6337 QualType Result;
6338
6339 // Note that per both C89 and C99, indirection is always legal, even if OpTy
6340 // is an incomplete type or void. It would be possible to warn about
6341 // dereferencing a void pointer, but it's completely well-defined, and such a
6342 // warning is unlikely to catch any mistakes.
6343 if (const PointerType *PT = OpTy->getAs<PointerType>())
6344 Result = PT->getPointeeType();
6345 else if (const ObjCObjectPointerType *OPT =
6346 OpTy->getAs<ObjCObjectPointerType>())
6347 Result = OPT->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006348
Chris Lattner9156f1b2010-07-05 19:17:26 +00006349 if (Result.isNull()) {
6350 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
6351 << OpTy << Op->getSourceRange();
6352 return QualType();
6353 }
6354
6355 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00006356}
Steve Naroff218bc2b2007-05-04 21:54:46 +00006357
6358static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
6359 tok::TokenKind Kind) {
6360 BinaryOperator::Opcode Opc;
6361 switch (Kind) {
6362 default: assert(0 && "Unknown binop!");
Sebastian Redl112a97662009-02-07 00:15:38 +00006363 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
6364 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006365 case tok::star: Opc = BinaryOperator::Mul; break;
6366 case tok::slash: Opc = BinaryOperator::Div; break;
6367 case tok::percent: Opc = BinaryOperator::Rem; break;
6368 case tok::plus: Opc = BinaryOperator::Add; break;
6369 case tok::minus: Opc = BinaryOperator::Sub; break;
6370 case tok::lessless: Opc = BinaryOperator::Shl; break;
6371 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
6372 case tok::lessequal: Opc = BinaryOperator::LE; break;
6373 case tok::less: Opc = BinaryOperator::LT; break;
6374 case tok::greaterequal: Opc = BinaryOperator::GE; break;
6375 case tok::greater: Opc = BinaryOperator::GT; break;
6376 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
6377 case tok::equalequal: Opc = BinaryOperator::EQ; break;
6378 case tok::amp: Opc = BinaryOperator::And; break;
6379 case tok::caret: Opc = BinaryOperator::Xor; break;
6380 case tok::pipe: Opc = BinaryOperator::Or; break;
6381 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
6382 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
6383 case tok::equal: Opc = BinaryOperator::Assign; break;
6384 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
6385 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
6386 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
6387 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
6388 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
6389 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
6390 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
6391 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
6392 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
6393 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
6394 case tok::comma: Opc = BinaryOperator::Comma; break;
6395 }
6396 return Opc;
6397}
6398
Steve Naroff35d85152007-05-07 00:24:15 +00006399static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
6400 tok::TokenKind Kind) {
6401 UnaryOperator::Opcode Opc;
6402 switch (Kind) {
6403 default: assert(0 && "Unknown unary op!");
6404 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
6405 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
6406 case tok::amp: Opc = UnaryOperator::AddrOf; break;
6407 case tok::star: Opc = UnaryOperator::Deref; break;
6408 case tok::plus: Opc = UnaryOperator::Plus; break;
6409 case tok::minus: Opc = UnaryOperator::Minus; break;
6410 case tok::tilde: Opc = UnaryOperator::Not; break;
6411 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Steve Naroff35d85152007-05-07 00:24:15 +00006412 case tok::kw___real: Opc = UnaryOperator::Real; break;
6413 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
Chris Lattnerd0f76512007-06-08 22:16:53 +00006414 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00006415 }
6416 return Opc;
6417}
6418
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006419/// CreateBuiltinBinOp - Creates a new built-in binary operation with
6420/// operator @p Opc at location @c TokLoc. This routine only supports
6421/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00006422ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Sebastian Redlb5d49352009-01-19 22:31:54 +00006423 unsigned Op,
6424 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006425 QualType ResultTy; // Result type of the binary operator.
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006426 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006427 // The following two variables are used for compound assignment operators
6428 QualType CompLHSTy; // Type of LHS after promotions for computation
6429 QualType CompResultTy; // Type of computation result
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006430
6431 switch (Opc) {
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006432 case BinaryOperator::Assign:
6433 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
6434 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00006435 case BinaryOperator::PtrMemD:
6436 case BinaryOperator::PtrMemI:
6437 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
6438 Opc == BinaryOperator::PtrMemI);
6439 break;
6440 case BinaryOperator::Mul:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006441 case BinaryOperator::Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00006442 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
6443 Opc == BinaryOperator::Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006444 break;
6445 case BinaryOperator::Rem:
6446 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
6447 break;
6448 case BinaryOperator::Add:
6449 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
6450 break;
6451 case BinaryOperator::Sub:
6452 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
6453 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00006454 case BinaryOperator::Shl:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006455 case BinaryOperator::Shr:
6456 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
6457 break;
6458 case BinaryOperator::LE:
6459 case BinaryOperator::LT:
6460 case BinaryOperator::GE:
6461 case BinaryOperator::GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006462 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006463 break;
6464 case BinaryOperator::EQ:
6465 case BinaryOperator::NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006466 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006467 break;
6468 case BinaryOperator::And:
6469 case BinaryOperator::Xor:
6470 case BinaryOperator::Or:
6471 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
6472 break;
6473 case BinaryOperator::LAnd:
6474 case BinaryOperator::LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00006475 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006476 break;
6477 case BinaryOperator::MulAssign:
6478 case BinaryOperator::DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00006479 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
6480 Opc == BinaryOperator::DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006481 CompLHSTy = CompResultTy;
6482 if (!CompResultTy.isNull())
6483 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006484 break;
6485 case BinaryOperator::RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006486 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
6487 CompLHSTy = CompResultTy;
6488 if (!CompResultTy.isNull())
6489 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006490 break;
6491 case BinaryOperator::AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006492 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6493 if (!CompResultTy.isNull())
6494 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006495 break;
6496 case BinaryOperator::SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006497 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6498 if (!CompResultTy.isNull())
6499 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006500 break;
6501 case BinaryOperator::ShlAssign:
6502 case BinaryOperator::ShrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006503 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6504 CompLHSTy = CompResultTy;
6505 if (!CompResultTy.isNull())
6506 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006507 break;
6508 case BinaryOperator::AndAssign:
6509 case BinaryOperator::XorAssign:
6510 case BinaryOperator::OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006511 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6512 CompLHSTy = CompResultTy;
6513 if (!CompResultTy.isNull())
6514 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006515 break;
6516 case BinaryOperator::Comma:
6517 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6518 break;
6519 }
6520 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00006521 return ExprError();
Fariborz Jahanian99311ba2010-08-16 21:51:12 +00006522 if (ResultTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
6523 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
6524 Diag(OpLoc, diag::err_assignment_requires_nonfragile_object)
6525 << ResultTy;
6526 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006527 if (CompResultTy.isNull())
Steve Narofff6009ed2009-01-21 00:14:39 +00006528 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6529 else
6530 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006531 CompLHSTy, CompResultTy,
6532 OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006533}
6534
Sebastian Redl44615072009-10-27 12:10:02 +00006535/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6536/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006537static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6538 const PartialDiagnostic &PD,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00006539 const PartialDiagnostic &FirstNote,
6540 SourceRange FirstParenRange,
6541 const PartialDiagnostic &SecondNote,
Douglas Gregor89336232010-03-29 23:34:08 +00006542 SourceRange SecondParenRange) {
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00006543 Self.Diag(Loc, PD);
6544
6545 if (!FirstNote.getDiagID())
6546 return;
6547
6548 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
6549 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6550 // We can't display the parentheses, so just return.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006551 return;
6552 }
6553
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00006554 Self.Diag(Loc, FirstNote)
6555 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregora771f462010-03-31 17:46:05 +00006556 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006557
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00006558 if (!SecondNote.getDiagID())
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006559 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006560
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006561 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
6562 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6563 // We can't display the parentheses, so just dig the
6564 // warning/error and return.
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00006565 Self.Diag(Loc, SecondNote);
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006566 return;
6567 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006568
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00006569 Self.Diag(Loc, SecondNote)
Douglas Gregora771f462010-03-31 17:46:05 +00006570 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
6571 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006572}
6573
Sebastian Redl44615072009-10-27 12:10:02 +00006574/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6575/// operators are mixed in a way that suggests that the programmer forgot that
6576/// comparison operators have higher precedence. The most typical example of
6577/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl43028242009-10-26 15:24:15 +00006578static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6579 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00006580 typedef BinaryOperator BinOp;
6581 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6582 rhsopc = static_cast<BinOp::Opcode>(-1);
6583 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00006584 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00006585 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00006586 rhsopc = BO->getOpcode();
6587
6588 // Subs are not binary operators.
6589 if (lhsopc == -1 && rhsopc == -1)
6590 return;
6591
6592 // Bitwise operations are sometimes used as eager logical ops.
6593 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00006594 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6595 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00006596 return;
6597
Sebastian Redl44615072009-10-27 12:10:02 +00006598 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006599 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00006600 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00006601 << SourceRange(lhs->getLocStart(), OpLoc)
6602 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00006603 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006604 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00006605 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
6606 Self.PDiag(diag::note_precedence_bitwise_silence)
6607 << BinOp::getOpcodeStr(lhsopc),
6608 lhs->getSourceRange());
Sebastian Redl44615072009-10-27 12:10:02 +00006609 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006610 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00006611 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00006612 << SourceRange(OpLoc, rhs->getLocEnd())
6613 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00006614 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006615 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00006616 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
6617 Self.PDiag(diag::note_precedence_bitwise_silence)
6618 << BinOp::getOpcodeStr(rhsopc),
6619 rhs->getSourceRange());
Sebastian Redl43028242009-10-26 15:24:15 +00006620}
6621
6622/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6623/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6624/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6625static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6626 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00006627 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl43028242009-10-26 15:24:15 +00006628 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6629}
6630
Steve Naroff218bc2b2007-05-04 21:54:46 +00006631// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00006632ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
Sebastian Redlb5d49352009-01-19 22:31:54 +00006633 tok::TokenKind Kind,
John McCallb268a282010-08-23 23:25:46 +00006634 Expr *lhs, Expr *rhs) {
Steve Naroff218bc2b2007-05-04 21:54:46 +00006635 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00006636 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6637 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00006638
Sebastian Redl43028242009-10-26 15:24:15 +00006639 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6640 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6641
Douglas Gregor5287f092009-11-05 00:51:44 +00006642 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6643}
6644
John McCalldadc5752010-08-24 06:29:42 +00006645ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
Douglas Gregor5287f092009-11-05 00:51:44 +00006646 BinaryOperator::Opcode Opc,
6647 Expr *lhs, Expr *rhs) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006648 if (getLangOptions().CPlusPlus &&
Mike Stump11289f42009-09-09 15:08:12 +00006649 (lhs->getType()->isOverloadableType() ||
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006650 rhs->getType()->isOverloadableType())) {
6651 // Find all of the overloaded operators visible from this
6652 // point. We perform both an operator-name lookup from the local
6653 // scope and an argument-dependent lookup based on the types of
6654 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00006655 UnresolvedSet<16> Functions;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006656 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00006657 if (S && OverOp != OO_None)
6658 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6659 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006660
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006661 // Build the (potentially-overloaded, potentially-dependent)
6662 // binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00006663 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb5d49352009-01-19 22:31:54 +00006664 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006665
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006666 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00006667 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006668}
6669
John McCalldadc5752010-08-24 06:29:42 +00006670ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006671 unsigned OpcIn,
John McCallb268a282010-08-23 23:25:46 +00006672 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006673 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregord08452f2008-11-19 15:42:04 +00006674
Steve Naroff35d85152007-05-07 00:24:15 +00006675 QualType resultType;
6676 switch (Opc) {
Steve Naroff35d85152007-05-07 00:24:15 +00006677 case UnaryOperator::PreInc:
6678 case UnaryOperator::PreDec:
Eli Friedman6aea5752009-07-22 22:25:00 +00006679 case UnaryOperator::PostInc:
6680 case UnaryOperator::PostDec:
Sebastian Redle10c2c32008-12-20 09:35:34 +00006681 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman6aea5752009-07-22 22:25:00 +00006682 Opc == UnaryOperator::PreInc ||
Alexis Huntc46382e2010-04-28 23:02:27 +00006683 Opc == UnaryOperator::PostInc,
6684 Opc == UnaryOperator::PreInc ||
6685 Opc == UnaryOperator::PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00006686 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006687 case UnaryOperator::AddrOf:
Chris Lattner86554282007-06-08 22:32:33 +00006688 resultType = CheckAddressOfOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00006689 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006690 case UnaryOperator::Deref:
Douglas Gregorb92a1562010-02-03 00:27:59 +00006691 DefaultFunctionArrayLvalueConversion(Input);
Chris Lattner86554282007-06-08 22:32:33 +00006692 resultType = CheckIndirectionOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00006693 break;
6694 case UnaryOperator::Plus:
6695 case UnaryOperator::Minus:
Steve Naroff31090012007-07-16 21:54:35 +00006696 UsualUnaryConversions(Input);
6697 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006698 if (resultType->isDependentType())
6699 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00006700 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
6701 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00006702 break;
6703 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6704 resultType->isEnumeralType())
6705 break;
6706 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6707 Opc == UnaryOperator::Plus &&
6708 resultType->isPointerType())
6709 break;
6710
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006711 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6712 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00006713 case UnaryOperator::Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00006714 UsualUnaryConversions(Input);
6715 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006716 if (resultType->isDependentType())
6717 break;
Chris Lattner0d707612008-07-25 23:52:49 +00006718 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6719 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6720 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00006721 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006722 << resultType << Input->getSourceRange();
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006723 else if (!resultType->hasIntegerRepresentation())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006724 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6725 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00006726 break;
6727 case UnaryOperator::LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00006728 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregorb92a1562010-02-03 00:27:59 +00006729 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroff31090012007-07-16 21:54:35 +00006730 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006731 if (resultType->isDependentType())
6732 break;
Steve Naroff35d85152007-05-07 00:24:15 +00006733 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006734 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6735 << resultType << Input->getSourceRange());
Chris Lattnerbe31ed82007-06-02 19:11:33 +00006736 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006737 // In C++, it's bool. C++ 5.3.1p8
6738 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Steve Naroff35d85152007-05-07 00:24:15 +00006739 break;
Chris Lattner30b5dd02007-08-24 21:16:53 +00006740 case UnaryOperator::Real:
Chris Lattner30b5dd02007-08-24 21:16:53 +00006741 case UnaryOperator::Imag:
Chris Lattner709322b2009-02-17 08:12:06 +00006742 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner30b5dd02007-08-24 21:16:53 +00006743 break;
Chris Lattner86554282007-06-08 22:32:33 +00006744 case UnaryOperator::Extension:
Chris Lattner86554282007-06-08 22:32:33 +00006745 resultType = Input->getType();
Steve Naroff043d45d2007-05-15 02:32:35 +00006746 break;
Steve Naroff35d85152007-05-07 00:24:15 +00006747 }
6748 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006749 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00006750
Steve Narofff6009ed2009-01-21 00:14:39 +00006751 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00006752}
Chris Lattnereefa10e2007-05-28 06:56:27 +00006753
John McCalldadc5752010-08-24 06:29:42 +00006754ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Douglas Gregor5287f092009-11-05 00:51:44 +00006755 UnaryOperator::Opcode Opc,
John McCallb268a282010-08-23 23:25:46 +00006756 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00006757 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6758 Opc != UnaryOperator::Extension) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006759 // Find all of the overloaded operators visible from this
6760 // point. We perform both an operator-name lookup from the local
6761 // scope and an argument-dependent lookup based on the types of
6762 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00006763 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00006764 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00006765 if (S && OverOp != OO_None)
6766 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6767 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006768
John McCallb268a282010-08-23 23:25:46 +00006769 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00006770 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006771
John McCallb268a282010-08-23 23:25:46 +00006772 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00006773}
6774
Douglas Gregor5287f092009-11-05 00:51:44 +00006775// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00006776ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00006777 tok::TokenKind Op, Expr *Input) {
6778 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00006779}
6780
Steve Naroff66356bd2007-09-16 14:56:35 +00006781/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
John McCalldadc5752010-08-24 06:29:42 +00006782ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006783 SourceLocation LabLoc,
6784 IdentifierInfo *LabelII) {
Chris Lattnereefa10e2007-05-28 06:56:27 +00006785 // Look up the record for this label identifier.
Chris Lattner3318e862009-04-18 20:01:55 +00006786 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump4e1f26a2009-02-19 03:04:26 +00006787
Daniel Dunbar88402ce2008-08-04 16:51:22 +00006788 // If we haven't seen this label yet, create a forward reference. It
6789 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff846b1ec2009-03-13 15:38:40 +00006790 if (LabelDecl == 0)
Steve Narofff6009ed2009-01-21 00:14:39 +00006791 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006792
Chris Lattnereefa10e2007-05-28 06:56:27 +00006793 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006794 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6795 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00006796}
6797
John McCalldadc5752010-08-24 06:29:42 +00006798ExprResult
John McCallb268a282010-08-23 23:25:46 +00006799Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006800 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00006801 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6802 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6803
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00006804 bool isFileScope
6805 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00006806 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006807 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00006808
Chris Lattner366727f2007-07-24 16:58:17 +00006809 // FIXME: there are a variety of strange constraints to enforce here, for
6810 // example, it is not possible to goto into a stmt expression apparently.
6811 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006812
Chris Lattner366727f2007-07-24 16:58:17 +00006813 // If there are sub stmts in the compound stmt, take the type of the last one
6814 // as the type of the stmtexpr.
6815 QualType Ty = Context.VoidTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006816
Chris Lattner944d3062008-07-26 19:51:01 +00006817 if (!Compound->body_empty()) {
6818 Stmt *LastStmt = Compound->body_back();
6819 // If LastStmt is a label, skip down through into the body.
6820 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6821 LastStmt = Label->getSubStmt();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006822
Chris Lattner944d3062008-07-26 19:51:01 +00006823 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner366727f2007-07-24 16:58:17 +00006824 Ty = LastExpr->getType();
Chris Lattner944d3062008-07-26 19:51:01 +00006825 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006826
Eli Friedmanba961a92009-03-23 00:24:07 +00006827 // FIXME: Check that expression type is complete/non-abstract; statement
6828 // expressions are not lvalues.
6829
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006830 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner366727f2007-07-24 16:58:17 +00006831}
Steve Naroff78864672007-08-01 22:05:33 +00006832
John McCalldadc5752010-08-24 06:29:42 +00006833ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
Douglas Gregor882211c2010-04-28 22:16:22 +00006834 TypeSourceInfo *TInfo,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006835 OffsetOfComponent *CompPtr,
6836 unsigned NumComponents,
Douglas Gregor882211c2010-04-28 22:16:22 +00006837 SourceLocation RParenLoc) {
6838 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006839 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006840 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00006841
Chris Lattnerf17bd422007-08-30 17:45:32 +00006842 // We must have at least one component that refers to the type, and the first
6843 // one is known to be a field designator. Verify that the ArgTy represents
6844 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006845 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00006846 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
6847 << ArgTy << TypeRange);
6848
6849 // Type must be complete per C99 7.17p3 because a declaring a variable
6850 // with an incomplete type would be ill-formed.
6851 if (!Dependent
6852 && RequireCompleteType(BuiltinLoc, ArgTy,
6853 PDiag(diag::err_offsetof_incomplete_type)
6854 << TypeRange))
6855 return ExprError();
6856
Chris Lattner78502cf2007-08-31 21:49:13 +00006857 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6858 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00006859 // FIXME: This diagnostic isn't actually visible because the location is in
6860 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00006861 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00006862 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6863 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00006864
6865 bool DidWarnAboutNonPOD = false;
6866 QualType CurrentType = ArgTy;
6867 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
6868 llvm::SmallVector<OffsetOfNode, 4> Comps;
6869 llvm::SmallVector<Expr*, 4> Exprs;
6870 for (unsigned i = 0; i != NumComponents; ++i) {
6871 const OffsetOfComponent &OC = CompPtr[i];
6872 if (OC.isBrackets) {
6873 // Offset of an array sub-field. TODO: Should we allow vector elements?
6874 if (!CurrentType->isDependentType()) {
6875 const ArrayType *AT = Context.getAsArrayType(CurrentType);
6876 if(!AT)
6877 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6878 << CurrentType);
6879 CurrentType = AT->getElementType();
6880 } else
6881 CurrentType = Context.DependentTy;
6882
6883 // The expression must be an integral expression.
6884 // FIXME: An integral constant expression?
6885 Expr *Idx = static_cast<Expr*>(OC.U.E);
6886 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
6887 !Idx->getType()->isIntegerType())
6888 return ExprError(Diag(Idx->getLocStart(),
6889 diag::err_typecheck_subscript_not_integer)
6890 << Idx->getSourceRange());
6891
6892 // Record this array index.
6893 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
6894 Exprs.push_back(Idx);
6895 continue;
6896 }
6897
6898 // Offset of a field.
6899 if (CurrentType->isDependentType()) {
6900 // We have the offset of a field, but we can't look into the dependent
6901 // type. Just record the identifier of the field.
6902 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
6903 CurrentType = Context.DependentTy;
6904 continue;
6905 }
6906
6907 // We need to have a complete type to look into.
6908 if (RequireCompleteType(OC.LocStart, CurrentType,
6909 diag::err_offsetof_incomplete_type))
6910 return ExprError();
6911
6912 // Look for the designated field.
6913 const RecordType *RC = CurrentType->getAs<RecordType>();
6914 if (!RC)
6915 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6916 << CurrentType);
6917 RecordDecl *RD = RC->getDecl();
6918
6919 // C++ [lib.support.types]p5:
6920 // The macro offsetof accepts a restricted set of type arguments in this
6921 // International Standard. type shall be a POD structure or a POD union
6922 // (clause 9).
6923 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6924 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
6925 DiagRuntimeBehavior(BuiltinLoc,
6926 PDiag(diag::warn_offsetof_non_pod_type)
6927 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6928 << CurrentType))
6929 DidWarnAboutNonPOD = true;
6930 }
6931
6932 // Look for the field.
6933 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6934 LookupQualifiedName(R, RD);
6935 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
6936 if (!MemberDecl)
6937 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6938 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
6939 OC.LocEnd));
6940
Douglas Gregor10982ea2010-04-28 22:36:06 +00006941 // C99 7.17p3:
6942 // (If the specified member is a bit-field, the behavior is undefined.)
6943 //
6944 // We diagnose this as an error.
6945 if (MemberDecl->getBitWidth()) {
6946 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
6947 << MemberDecl->getDeclName()
6948 << SourceRange(BuiltinLoc, RParenLoc);
6949 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
6950 return ExprError();
6951 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00006952
6953 RecordDecl *Parent = MemberDecl->getParent();
6954 bool AnonStructUnion = Parent->isAnonymousStructOrUnion();
6955 if (AnonStructUnion) {
6956 do {
6957 Parent = cast<RecordDecl>(Parent->getParent());
6958 } while (Parent->isAnonymousStructOrUnion());
6959 }
6960
Douglas Gregord1702062010-04-29 00:18:15 +00006961 // If the member was found in a base class, introduce OffsetOfNodes for
6962 // the base class indirections.
6963 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
6964 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00006965 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00006966 CXXBasePath &Path = Paths.front();
6967 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
6968 B != BEnd; ++B)
6969 Comps.push_back(OffsetOfNode(B->Base));
6970 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00006971
6972 if (AnonStructUnion) {
Douglas Gregor882211c2010-04-28 22:16:22 +00006973 llvm::SmallVector<FieldDecl*, 4> Path;
6974 BuildAnonymousStructUnionMemberPath(MemberDecl, Path);
6975 unsigned n = Path.size();
6976 for (int j = n - 1; j > -1; --j)
6977 Comps.push_back(OffsetOfNode(OC.LocStart, Path[j], OC.LocEnd));
6978 } else {
6979 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
6980 }
6981 CurrentType = MemberDecl->getType().getNonReferenceType();
6982 }
6983
6984 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
6985 TInfo, Comps.data(), Comps.size(),
6986 Exprs.data(), Exprs.size(), RParenLoc));
6987}
Mike Stump4e1f26a2009-02-19 03:04:26 +00006988
John McCalldadc5752010-08-24 06:29:42 +00006989ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
Douglas Gregor882211c2010-04-28 22:16:22 +00006990 SourceLocation BuiltinLoc,
6991 SourceLocation TypeLoc,
John McCallba7bf592010-08-24 05:47:05 +00006992 ParsedType argty,
Douglas Gregor882211c2010-04-28 22:16:22 +00006993 OffsetOfComponent *CompPtr,
6994 unsigned NumComponents,
6995 SourceLocation RPLoc) {
6996
6997 TypeSourceInfo *ArgTInfo;
6998 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
6999 if (ArgTy.isNull())
7000 return ExprError();
7001
Eli Friedman06dcfd92010-08-05 10:15:45 +00007002 if (!ArgTInfo)
7003 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
7004
7005 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
7006 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00007007}
7008
7009
John McCalldadc5752010-08-24 06:29:42 +00007010ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00007011 ParsedType arg1,ParsedType arg2,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007012 SourceLocation RPLoc) {
Abramo Bagnara092990a2010-08-10 08:50:03 +00007013 TypeSourceInfo *argTInfo1;
7014 QualType argT1 = GetTypeFromParser(arg1, &argTInfo1);
7015 TypeSourceInfo *argTInfo2;
7016 QualType argT2 = GetTypeFromParser(arg2, &argTInfo2);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007017
Steve Naroff78864672007-08-01 22:05:33 +00007018 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump4e1f26a2009-02-19 03:04:26 +00007019
Abramo Bagnara092990a2010-08-10 08:50:03 +00007020 return BuildTypesCompatibleExpr(BuiltinLoc, argTInfo1, argTInfo2, RPLoc);
7021}
7022
John McCalldadc5752010-08-24 06:29:42 +00007023ExprResult
Abramo Bagnara092990a2010-08-10 08:50:03 +00007024Sema::BuildTypesCompatibleExpr(SourceLocation BuiltinLoc,
7025 TypeSourceInfo *argTInfo1,
7026 TypeSourceInfo *argTInfo2,
7027 SourceLocation RPLoc) {
Douglas Gregorf907cbf2009-05-19 22:28:02 +00007028 if (getLangOptions().CPlusPlus) {
7029 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
7030 << SourceRange(BuiltinLoc, RPLoc);
7031 return ExprError();
7032 }
7033
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007034 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
Abramo Bagnara092990a2010-08-10 08:50:03 +00007035 argTInfo1, argTInfo2, RPLoc));
Steve Naroff78864672007-08-01 22:05:33 +00007036}
7037
Abramo Bagnara092990a2010-08-10 08:50:03 +00007038
John McCalldadc5752010-08-24 06:29:42 +00007039ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCallb268a282010-08-23 23:25:46 +00007040 Expr *CondExpr,
7041 Expr *LHSExpr, Expr *RHSExpr,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007042 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00007043 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
7044
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007045 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00007046 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00007047 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007048 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00007049 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007050 } else {
7051 // The conditional expression is required to be a constant expression.
7052 llvm::APSInt condEval(32);
7053 SourceLocation ExpLoc;
7054 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007055 return ExprError(Diag(ExpLoc,
7056 diag::err_typecheck_choose_expr_requires_constant)
7057 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00007058
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007059 // If the condition is > zero, then the AST type is the same as the LSHExpr.
7060 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregor56751b52009-09-25 04:25:58 +00007061 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
7062 : RHSExpr->isValueDependent();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007063 }
7064
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007065 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregor56751b52009-09-25 04:25:58 +00007066 resType, RPLoc,
7067 resType->isDependentType(),
7068 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00007069}
7070
Steve Naroffc540d662008-09-03 18:15:37 +00007071//===----------------------------------------------------------------------===//
7072// Clang Extensions.
7073//===----------------------------------------------------------------------===//
7074
7075/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00007076void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00007077 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
7078 PushBlockScope(BlockScope, Block);
7079 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00007080 if (BlockScope)
7081 PushDeclContext(BlockScope, Block);
7082 else
7083 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00007084}
7085
Mike Stump82f071f2009-02-04 22:31:32 +00007086void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00007087 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Douglas Gregor9a28e842010-03-01 23:15:13 +00007088 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007089
John McCall8cb7bdf2010-06-04 23:28:52 +00007090 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCalla3ccba02010-06-04 11:21:44 +00007091 CurBlock->TheDecl->setSignatureAsWritten(Sig);
John McCall8cb7bdf2010-06-04 23:28:52 +00007092 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00007093
John McCall8e346702010-06-04 19:02:56 +00007094 bool isVariadic;
John McCalla3ccba02010-06-04 11:21:44 +00007095 QualType RetTy;
7096 if (const FunctionType *Fn = T->getAs<FunctionType>()) {
John McCall8e346702010-06-04 19:02:56 +00007097 CurBlock->FunctionType = T;
John McCalla3ccba02010-06-04 11:21:44 +00007098 RetTy = Fn->getResultType();
John McCall8e346702010-06-04 19:02:56 +00007099 isVariadic =
John McCalla3ccba02010-06-04 11:21:44 +00007100 !isa<FunctionProtoType>(Fn) || cast<FunctionProtoType>(Fn)->isVariadic();
7101 } else {
7102 RetTy = T;
John McCall8e346702010-06-04 19:02:56 +00007103 isVariadic = false;
John McCalla3ccba02010-06-04 11:21:44 +00007104 }
Mike Stump11289f42009-09-09 15:08:12 +00007105
John McCall8e346702010-06-04 19:02:56 +00007106 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00007107
John McCalla3ccba02010-06-04 11:21:44 +00007108 // Don't allow returning an array by value.
7109 if (RetTy->isArrayType()) {
7110 Diag(ParamInfo.getSourceRange().getBegin(), diag::err_block_returns_array);
Mike Stump82f071f2009-02-04 22:31:32 +00007111 return;
7112 }
7113
John McCalla3ccba02010-06-04 11:21:44 +00007114 // Don't allow returning a objc interface by value.
7115 if (RetTy->isObjCObjectType()) {
7116 Diag(ParamInfo.getSourceRange().getBegin(),
7117 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
7118 return;
7119 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007120
John McCalla3ccba02010-06-04 11:21:44 +00007121 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00007122 // return type. TODO: what should we do with declarators like:
7123 // ^ * { ... }
7124 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00007125 if (RetTy != Context.DependentTy)
7126 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007127
John McCalla3ccba02010-06-04 11:21:44 +00007128 // Push block parameters from the declarator if we had them.
John McCall8e346702010-06-04 19:02:56 +00007129 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCalla3ccba02010-06-04 11:21:44 +00007130 if (isa<FunctionProtoType>(T)) {
7131 FunctionProtoTypeLoc TL = cast<FunctionProtoTypeLoc>(Sig->getTypeLoc());
7132 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
7133 ParmVarDecl *Param = TL.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00007134 if (Param->getIdentifier() == 0 &&
7135 !Param->isImplicit() &&
7136 !Param->isInvalidDecl() &&
7137 !getLangOptions().CPlusPlus)
7138 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00007139 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00007140 }
John McCalla3ccba02010-06-04 11:21:44 +00007141
7142 // Fake up parameter variables if we have a typedef, like
7143 // ^ fntype { ... }
7144 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
7145 for (FunctionProtoType::arg_type_iterator
7146 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
7147 ParmVarDecl *Param =
7148 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
7149 ParamInfo.getSourceRange().getBegin(),
7150 *I);
John McCall8e346702010-06-04 19:02:56 +00007151 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00007152 }
Steve Naroffc540d662008-09-03 18:15:37 +00007153 }
John McCalla3ccba02010-06-04 11:21:44 +00007154
John McCall8e346702010-06-04 19:02:56 +00007155 // Set the parameters on the block decl.
7156 if (!Params.empty())
7157 CurBlock->TheDecl->setParams(Params.data(), Params.size());
John McCalla3ccba02010-06-04 11:21:44 +00007158
7159 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00007160 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00007161
John McCall8e346702010-06-04 19:02:56 +00007162 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00007163 Diag(ParamInfo.getAttributes()->getLoc(),
7164 diag::warn_attribute_sentinel_not_variadic) << 1;
7165 // FIXME: remove the attribute.
7166 }
7167
7168 // Put the parameter variables in scope. We can bail out immediately
7169 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00007170 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00007171 return;
7172
John McCalldf8b37c2010-03-22 09:20:08 +00007173 bool ShouldCheckShadow =
7174 Diags.getDiagnosticLevel(diag::warn_decl_shadow) != Diagnostic::Ignored;
7175
Steve Naroff1d95e5a2008-10-10 01:28:17 +00007176 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00007177 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
7178 (*AI)->setOwningFunction(CurBlock->TheDecl);
7179
Steve Naroff1d95e5a2008-10-10 01:28:17 +00007180 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00007181 if ((*AI)->getIdentifier()) {
7182 if (ShouldCheckShadow)
7183 CheckShadow(CurBlock->TheScope, *AI);
7184
Steve Naroff1d95e5a2008-10-10 01:28:17 +00007185 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00007186 }
John McCallf7b2fb52010-01-22 00:28:27 +00007187 }
Steve Naroffc540d662008-09-03 18:15:37 +00007188}
7189
7190/// ActOnBlockError - If there is an error parsing a block, this callback
7191/// is invoked to pop the information about the block from the action impl.
7192void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00007193 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00007194 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00007195 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00007196 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroffc540d662008-09-03 18:15:37 +00007197}
7198
7199/// ActOnBlockStmtExpr - This is called when the body of a block statement
7200/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00007201ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
John McCallb268a282010-08-23 23:25:46 +00007202 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00007203 // If blocks are disabled, emit an error.
7204 if (!LangOpts.Blocks)
7205 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00007206
Douglas Gregor9a28e842010-03-01 23:15:13 +00007207 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00007208
Steve Naroff1d95e5a2008-10-10 01:28:17 +00007209 PopDeclContext();
7210
Steve Naroffc540d662008-09-03 18:15:37 +00007211 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00007212 if (!BSI->ReturnType.isNull())
7213 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007214
Mike Stump3bf1ab42009-07-28 22:04:01 +00007215 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00007216 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00007217
7218 // If the user wrote a function type in some form, try to use that.
7219 if (!BSI->FunctionType.isNull()) {
7220 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
7221
7222 FunctionType::ExtInfo Ext = FTy->getExtInfo();
7223 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
7224
7225 // Turn protoless block types into nullary block types.
7226 if (isa<FunctionNoProtoType>(FTy)) {
7227 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0,
7228 false, false, 0, 0, Ext);
7229
7230 // Otherwise, if we don't need to change anything about the function type,
7231 // preserve its sugar structure.
7232 } else if (FTy->getResultType() == RetTy &&
7233 (!NoReturn || FTy->getNoReturnAttr())) {
7234 BlockTy = BSI->FunctionType;
7235
7236 // Otherwise, make the minimal modifications to the function type.
7237 } else {
7238 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
7239 BlockTy = Context.getFunctionType(RetTy,
7240 FPT->arg_type_begin(),
7241 FPT->getNumArgs(),
7242 FPT->isVariadic(),
7243 /*quals*/ 0,
7244 FPT->hasExceptionSpec(),
7245 FPT->hasAnyExceptionSpec(),
7246 FPT->getNumExceptions(),
7247 FPT->exception_begin(),
7248 Ext);
7249 }
7250
7251 // If we don't have a function type, just build one from nothing.
7252 } else {
7253 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0,
7254 false, false, 0, 0,
7255 FunctionType::ExtInfo(NoReturn, 0, CC_Default));
7256 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007257
Eli Friedmanba961a92009-03-23 00:24:07 +00007258 // FIXME: Check that return/parameter types are complete/non-abstract
John McCall8e346702010-06-04 19:02:56 +00007259 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
7260 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00007261 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007262
Chris Lattner45542ea2009-04-19 05:28:12 +00007263 // If needed, diagnose invalid gotos and switches in the block.
Douglas Gregor9a28e842010-03-01 23:15:13 +00007264 if (FunctionNeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00007265 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00007266
John McCallb268a282010-08-23 23:25:46 +00007267 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Mike Stump314825b2010-01-19 23:08:01 +00007268
7269 bool Good = true;
7270 // Check goto/label use.
7271 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
7272 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
7273 LabelStmt *L = I->second;
7274
7275 // Verify that we have no forward references left. If so, there was a goto
7276 // or address of a label taken, but no definition of it.
7277 if (L->getSubStmt() != 0)
7278 continue;
7279
7280 // Emit error.
7281 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
7282 Good = false;
7283 }
Douglas Gregor9a28e842010-03-01 23:15:13 +00007284 if (!Good) {
7285 PopFunctionOrBlockScope();
Mike Stump314825b2010-01-19 23:08:01 +00007286 return ExprError();
Douglas Gregor9a28e842010-03-01 23:15:13 +00007287 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007288
Ted Kremenek918fe842010-03-20 21:06:02 +00007289 // Issue any analysis-based warnings.
Ted Kremenek0b405322010-03-23 00:13:23 +00007290 const sema::AnalysisBasedWarnings::Policy &WP =
7291 AnalysisWarnings.getDefaultPolicy();
7292 AnalysisWarnings.IssueWarnings(WP, BSI->TheDecl, BlockTy);
Ted Kremenek918fe842010-03-20 21:06:02 +00007293
Douglas Gregor9a28e842010-03-01 23:15:13 +00007294 Expr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy,
7295 BSI->hasBlockDeclRefExprs);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007296 PopFunctionOrBlockScope();
Douglas Gregor9a28e842010-03-01 23:15:13 +00007297 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00007298}
7299
John McCalldadc5752010-08-24 06:29:42 +00007300ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00007301 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007302 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00007303 TypeSourceInfo *TInfo;
7304 QualType T = GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00007305 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00007306}
7307
John McCalldadc5752010-08-24 06:29:42 +00007308ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallb268a282010-08-23 23:25:46 +00007309 Expr *E, TypeSourceInfo *TInfo,
Abramo Bagnara27db2392010-08-10 10:06:15 +00007310 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00007311 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00007312
Anders Carlsson7e13ab82007-10-15 20:28:48 +00007313 InitBuiltinVaListType();
Eli Friedman121ba0c2008-08-09 23:32:40 +00007314
7315 // Get the va_list type
7316 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00007317 if (VaListType->isArrayType()) {
7318 // Deal with implicit array decay; for example, on x86-64,
7319 // va_list is an array, but it's supposed to decay to
7320 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00007321 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00007322 // Make sure the input expression also decays appropriately.
7323 UsualUnaryConversions(E);
7324 } else {
7325 // Otherwise, the va_list argument must be an l-value because
7326 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00007327 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00007328 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00007329 return ExprError();
7330 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00007331
Douglas Gregorad3150c2009-05-19 23:10:31 +00007332 if (!E->isTypeDependent() &&
7333 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007334 return ExprError(Diag(E->getLocStart(),
7335 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00007336 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00007337 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007338
Eli Friedmanba961a92009-03-23 00:24:07 +00007339 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00007340 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007341
Abramo Bagnara27db2392010-08-10 10:06:15 +00007342 QualType T = TInfo->getType().getNonLValueExprType(Context);
7343 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00007344}
7345
John McCalldadc5752010-08-24 06:29:42 +00007346ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00007347 // The type of __null will be int or long, depending on the size of
7348 // pointers on the target.
7349 QualType Ty;
7350 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
7351 Ty = Context.IntTy;
7352 else
7353 Ty = Context.LongTy;
7354
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007355 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00007356}
7357
Alexis Huntc46382e2010-04-28 23:02:27 +00007358static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00007359 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00007360 if (!SemaRef.getLangOptions().ObjC1)
7361 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007362
Anders Carlssonace5d072009-11-10 04:46:30 +00007363 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
7364 if (!PT)
7365 return;
7366
7367 // Check if the destination is of type 'id'.
7368 if (!PT->isObjCIdType()) {
7369 // Check if the destination is the 'NSString' interface.
7370 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
7371 if (!ID || !ID->getIdentifier()->isStr("NSString"))
7372 return;
7373 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007374
Anders Carlssonace5d072009-11-10 04:46:30 +00007375 // Strip off any parens and casts.
7376 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
7377 if (!SL || SL->isWide())
7378 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007379
Douglas Gregora771f462010-03-31 17:46:05 +00007380 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00007381}
7382
Chris Lattner9bad62c2008-01-04 18:04:52 +00007383bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
7384 SourceLocation Loc,
7385 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007386 Expr *SrcExpr, AssignmentAction Action,
7387 bool *Complained) {
7388 if (Complained)
7389 *Complained = false;
7390
Chris Lattner9bad62c2008-01-04 18:04:52 +00007391 // Decode the result (notice that AST's are still created for extensions).
7392 bool isInvalid = false;
7393 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00007394 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007395
Chris Lattner9bad62c2008-01-04 18:04:52 +00007396 switch (ConvTy) {
7397 default: assert(0 && "Unknown conversion type");
7398 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00007399 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00007400 DiagKind = diag::ext_typecheck_convert_pointer_int;
7401 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00007402 case IntToPointer:
7403 DiagKind = diag::ext_typecheck_convert_int_pointer;
7404 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007405 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00007406 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00007407 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
7408 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00007409 case IncompatiblePointerSign:
7410 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
7411 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007412 case FunctionVoidPointer:
7413 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
7414 break;
7415 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00007416 // If the qualifiers lost were because we were applying the
7417 // (deprecated) C++ conversion from a string literal to a char*
7418 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
7419 // Ideally, this check would be performed in
7420 // CheckPointerTypesForAssignment. However, that would require a
7421 // bit of refactoring (so that the second argument is an
7422 // expression, rather than a type), which should be done as part
7423 // of a larger effort to fix CheckPointerTypesForAssignment for
7424 // C++ semantics.
7425 if (getLangOptions().CPlusPlus &&
7426 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
7427 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007428 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
7429 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00007430 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00007431 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00007432 break;
Steve Naroff081c7422008-09-04 15:10:53 +00007433 case IntToBlockPointer:
7434 DiagKind = diag::err_int_to_block_pointer;
7435 break;
7436 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00007437 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00007438 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00007439 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00007440 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00007441 // it can give a more specific diagnostic.
7442 DiagKind = diag::warn_incompatible_qualified_id;
7443 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00007444 case IncompatibleVectors:
7445 DiagKind = diag::warn_incompatible_vectors;
7446 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007447 case Incompatible:
7448 DiagKind = diag::err_typecheck_convert_incompatible;
7449 isInvalid = true;
7450 break;
7451 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007452
Douglas Gregorc68e1402010-04-09 00:35:39 +00007453 QualType FirstType, SecondType;
7454 switch (Action) {
7455 case AA_Assigning:
7456 case AA_Initializing:
7457 // The destination type comes first.
7458 FirstType = DstType;
7459 SecondType = SrcType;
7460 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00007461
Douglas Gregorc68e1402010-04-09 00:35:39 +00007462 case AA_Returning:
7463 case AA_Passing:
7464 case AA_Converting:
7465 case AA_Sending:
7466 case AA_Casting:
7467 // The source type comes first.
7468 FirstType = SrcType;
7469 SecondType = DstType;
7470 break;
7471 }
Alexis Huntc46382e2010-04-28 23:02:27 +00007472
Douglas Gregorc68e1402010-04-09 00:35:39 +00007473 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00007474 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007475 if (Complained)
7476 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007477 return isInvalid;
7478}
Anders Carlssone54e8a12008-11-30 19:50:32 +00007479
Chris Lattnerc71d08b2009-04-25 21:59:05 +00007480bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00007481 llvm::APSInt ICEResult;
7482 if (E->isIntegerConstantExpr(ICEResult, Context)) {
7483 if (Result)
7484 *Result = ICEResult;
7485 return false;
7486 }
7487
Anders Carlssone54e8a12008-11-30 19:50:32 +00007488 Expr::EvalResult EvalResult;
7489
Mike Stump4e1f26a2009-02-19 03:04:26 +00007490 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00007491 EvalResult.HasSideEffects) {
7492 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
7493
7494 if (EvalResult.Diag) {
7495 // We only show the note if it's not the usual "invalid subexpression"
7496 // or if it's actually in a subexpression.
7497 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
7498 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
7499 Diag(EvalResult.DiagLoc, EvalResult.Diag);
7500 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007501
Anders Carlssone54e8a12008-11-30 19:50:32 +00007502 return true;
7503 }
7504
Eli Friedmanbb967cc2009-04-25 22:26:58 +00007505 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
7506 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00007507
Eli Friedmanbb967cc2009-04-25 22:26:58 +00007508 if (EvalResult.Diag &&
7509 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
7510 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007511
Anders Carlssone54e8a12008-11-30 19:50:32 +00007512 if (Result)
7513 *Result = EvalResult.Val.getInt();
7514 return false;
7515}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007516
Douglas Gregorff790f12009-11-26 00:44:06 +00007517void
Mike Stump11289f42009-09-09 15:08:12 +00007518Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00007519 ExprEvalContexts.push_back(
7520 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007521}
7522
Mike Stump11289f42009-09-09 15:08:12 +00007523void
Douglas Gregorff790f12009-11-26 00:44:06 +00007524Sema::PopExpressionEvaluationContext() {
7525 // Pop the current expression evaluation context off the stack.
7526 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
7527 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007528
Douglas Gregorfab31f42009-12-12 07:57:52 +00007529 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
7530 if (Rec.PotentiallyReferenced) {
7531 // Mark any remaining declarations in the current position of the stack
7532 // as "referenced". If they were not meant to be referenced, semantic
7533 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007534 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00007535 I = Rec.PotentiallyReferenced->begin(),
7536 IEnd = Rec.PotentiallyReferenced->end();
7537 I != IEnd; ++I)
7538 MarkDeclarationReferenced(I->first, I->second);
7539 }
7540
7541 if (Rec.PotentiallyDiagnosed) {
7542 // Emit any pending diagnostics.
7543 for (PotentiallyEmittedDiagnostics::iterator
7544 I = Rec.PotentiallyDiagnosed->begin(),
7545 IEnd = Rec.PotentiallyDiagnosed->end();
7546 I != IEnd; ++I)
7547 Diag(I->first, I->second);
7548 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007549 }
Douglas Gregorff790f12009-11-26 00:44:06 +00007550
7551 // When are coming out of an unevaluated context, clear out any
7552 // temporaries that we may have created as part of the evaluation of
7553 // the expression in that context: they aren't relevant because they
7554 // will never be constructed.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007555 if (Rec.Context == Unevaluated &&
Douglas Gregorff790f12009-11-26 00:44:06 +00007556 ExprTemporaries.size() > Rec.NumTemporaries)
7557 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
7558 ExprTemporaries.end());
7559
7560 // Destroy the popped expression evaluation record.
7561 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007562}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007563
7564/// \brief Note that the given declaration was referenced in the source code.
7565///
7566/// This routine should be invoke whenever a given declaration is referenced
7567/// in the source code, and where that reference occurred. If this declaration
7568/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
7569/// C99 6.9p3), then the declaration will be marked as used.
7570///
7571/// \param Loc the location where the declaration was referenced.
7572///
7573/// \param D the declaration that has been referenced by the source code.
7574void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
7575 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00007576
Douglas Gregorebada0772010-06-17 23:14:26 +00007577 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00007578 return;
Mike Stump11289f42009-09-09 15:08:12 +00007579
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00007580 // Mark a parameter or variable declaration "used", regardless of whether we're in a
7581 // template or not. The reason for this is that unevaluated expressions
7582 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
7583 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007584 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00007585 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007586 D->setUsed(true);
Douglas Gregorfd27fed2010-04-07 20:29:57 +00007587 return;
7588 }
Alexis Huntc46382e2010-04-28 23:02:27 +00007589
Douglas Gregorfd27fed2010-04-07 20:29:57 +00007590 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
7591 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00007592
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007593 // Do not mark anything as "used" within a dependent context; wait for
7594 // an instantiation.
7595 if (CurContext->isDependentContext())
7596 return;
Mike Stump11289f42009-09-09 15:08:12 +00007597
Douglas Gregorff790f12009-11-26 00:44:06 +00007598 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007599 case Unevaluated:
7600 // We are in an expression that is not potentially evaluated; do nothing.
7601 return;
Mike Stump11289f42009-09-09 15:08:12 +00007602
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007603 case PotentiallyEvaluated:
7604 // We are in a potentially-evaluated expression, so this declaration is
7605 // "used"; handle this below.
7606 break;
Mike Stump11289f42009-09-09 15:08:12 +00007607
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007608 case PotentiallyPotentiallyEvaluated:
7609 // We are in an expression that may be potentially evaluated; queue this
7610 // declaration reference until we know whether the expression is
7611 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00007612 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007613 return;
7614 }
Mike Stump11289f42009-09-09 15:08:12 +00007615
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007616 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00007617 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007618 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00007619 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruthc9262402010-08-23 07:55:51 +00007620 if (Constructor->getParent()->hasTrivialConstructor())
7621 return;
7622 if (!Constructor->isUsed(false))
7623 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00007624 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00007625 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00007626 if (!Constructor->isUsed(false))
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007627 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7628 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007629
Douglas Gregor88d292c2010-05-13 16:44:06 +00007630 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007631 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00007632 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007633 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00007634 if (Destructor->isVirtual())
7635 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007636 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7637 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7638 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00007639 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00007640 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00007641 } else if (MethodDecl->isVirtual())
7642 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007643 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00007644 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00007645 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00007646 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00007647 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00007648 bool AlreadyInstantiated = false;
7649 if (FunctionTemplateSpecializationInfo *SpecInfo
7650 = Function->getTemplateSpecializationInfo()) {
7651 if (SpecInfo->getPointOfInstantiation().isInvalid())
7652 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007653 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00007654 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00007655 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007656 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00007657 = Function->getMemberSpecializationInfo()) {
7658 if (MSInfo->getPointOfInstantiation().isInvalid())
7659 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007660 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00007661 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00007662 AlreadyInstantiated = true;
7663 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007664
Douglas Gregor7f792cf2010-01-16 22:29:39 +00007665 if (!AlreadyInstantiated) {
7666 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
7667 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
7668 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
7669 Loc));
7670 else
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007671 PendingImplicitInstantiations.push_back(std::make_pair(Function,
Douglas Gregor7f792cf2010-01-16 22:29:39 +00007672 Loc));
7673 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007674 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007675
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007676 // FIXME: keep track of references to static functions
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007677 Function->setUsed(true);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007678
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007679 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00007680 }
Mike Stump11289f42009-09-09 15:08:12 +00007681
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007682 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007683 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00007684 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00007685 Var->getInstantiatedFromStaticDataMember()) {
7686 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7687 assert(MSInfo && "Missing member specialization information?");
7688 if (MSInfo->getPointOfInstantiation().isInvalid() &&
7689 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7690 MSInfo->setPointOfInstantiation(Loc);
7691 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7692 }
7693 }
Mike Stump11289f42009-09-09 15:08:12 +00007694
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007695 // FIXME: keep track of references to static data?
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007696
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007697 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007698 return;
Sam Weinigbae69142009-09-11 03:29:30 +00007699 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007700}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007701
Douglas Gregor5597ab42010-05-07 23:12:07 +00007702namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00007703 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00007704 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00007705 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00007706 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
7707 Sema &S;
7708 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00007709
Douglas Gregor5597ab42010-05-07 23:12:07 +00007710 public:
7711 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00007712
Douglas Gregor5597ab42010-05-07 23:12:07 +00007713 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00007714
7715 bool TraverseTemplateArgument(const TemplateArgument &Arg);
7716 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00007717 };
7718}
7719
Chandler Carruthaf80f662010-06-09 08:17:30 +00007720bool MarkReferencedDecls::TraverseTemplateArgument(
7721 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00007722 if (Arg.getKind() == TemplateArgument::Declaration) {
7723 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
7724 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00007725
7726 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00007727}
7728
Chandler Carruthaf80f662010-06-09 08:17:30 +00007729bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00007730 if (ClassTemplateSpecializationDecl *Spec
7731 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
7732 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Chandler Carruthaf80f662010-06-09 08:17:30 +00007733 return TraverseTemplateArguments(Args.getFlatArgumentList(),
7734 Args.flat_size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00007735 }
7736
Chandler Carruthc65667c2010-06-10 10:31:57 +00007737 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00007738}
7739
7740void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
7741 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00007742 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00007743}
7744
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007745/// \brief Emit a diagnostic that describes an effect on the run-time behavior
7746/// of the program being compiled.
7747///
7748/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007749/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007750/// possibility that the code will actually be executable. Code in sizeof()
7751/// expressions, code used only during overload resolution, etc., are not
7752/// potentially evaluated. This routine will suppress such diagnostics or,
7753/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007754/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007755/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007756///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007757/// This routine should be used for all diagnostics that describe the run-time
7758/// behavior of a program, such as passing a non-POD value through an ellipsis.
7759/// Failure to do so will likely result in spurious diagnostics or failures
7760/// during overload resolution or within sizeof/alignof/typeof/typeid.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007761bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007762 const PartialDiagnostic &PD) {
7763 switch (ExprEvalContexts.back().Context ) {
7764 case Unevaluated:
7765 // The argument will never be evaluated, so don't complain.
7766 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007767
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007768 case PotentiallyEvaluated:
7769 Diag(Loc, PD);
7770 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007771
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007772 case PotentiallyPotentiallyEvaluated:
7773 ExprEvalContexts.back().addDiagnostic(Loc, PD);
7774 break;
7775 }
7776
7777 return false;
7778}
7779
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007780bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7781 CallExpr *CE, FunctionDecl *FD) {
7782 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7783 return false;
7784
7785 PartialDiagnostic Note =
7786 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7787 << FD->getDeclName() : PDiag();
7788 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007789
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007790 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007791 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007792 PDiag(diag::err_call_function_incomplete_return)
7793 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007794 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007795 << CE->getSourceRange(),
7796 std::make_pair(NoteLoc, Note)))
7797 return true;
7798
7799 return false;
7800}
7801
John McCalld5707ab2009-10-12 21:59:07 +00007802// Diagnose the common s/=/==/ typo. Note that adding parentheses
7803// will prevent this condition from triggering, which is what we want.
7804void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7805 SourceLocation Loc;
7806
John McCall0506e4a2009-11-11 02:41:58 +00007807 unsigned diagnostic = diag::warn_condition_is_assignment;
7808
John McCalld5707ab2009-10-12 21:59:07 +00007809 if (isa<BinaryOperator>(E)) {
7810 BinaryOperator *Op = cast<BinaryOperator>(E);
7811 if (Op->getOpcode() != BinaryOperator::Assign)
7812 return;
7813
John McCallb0e419e2009-11-12 00:06:05 +00007814 // Greylist some idioms by putting them into a warning subcategory.
7815 if (ObjCMessageExpr *ME
7816 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7817 Selector Sel = ME->getSelector();
7818
John McCallb0e419e2009-11-12 00:06:05 +00007819 // self = [<foo> init...]
7820 if (isSelfExpr(Op->getLHS())
7821 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7822 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7823
7824 // <foo> = [<bar> nextObject]
7825 else if (Sel.isUnarySelector() &&
7826 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7827 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7828 }
John McCall0506e4a2009-11-11 02:41:58 +00007829
John McCalld5707ab2009-10-12 21:59:07 +00007830 Loc = Op->getOperatorLoc();
7831 } else if (isa<CXXOperatorCallExpr>(E)) {
7832 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7833 if (Op->getOperator() != OO_Equal)
7834 return;
7835
7836 Loc = Op->getOperatorLoc();
7837 } else {
7838 // Not an assignment.
7839 return;
7840 }
7841
John McCalld5707ab2009-10-12 21:59:07 +00007842 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00007843 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007844
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007845 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007846 Diag(Loc, diag::note_condition_assign_to_comparison)
Douglas Gregora771f462010-03-31 17:46:05 +00007847 << FixItHint::CreateReplacement(Loc, "==");
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007848 Diag(Loc, diag::note_condition_assign_silence)
7849 << FixItHint::CreateInsertion(Open, "(")
7850 << FixItHint::CreateInsertion(Close, ")");
John McCalld5707ab2009-10-12 21:59:07 +00007851}
7852
7853bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7854 DiagnoseAssignmentAsCondition(E);
7855
7856 if (!E->isTypeDependent()) {
Douglas Gregorb92a1562010-02-03 00:27:59 +00007857 DefaultFunctionArrayLvalueConversion(E);
John McCalld5707ab2009-10-12 21:59:07 +00007858
7859 QualType T = E->getType();
7860
7861 if (getLangOptions().CPlusPlus) {
7862 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7863 return true;
7864 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7865 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7866 << T << E->getSourceRange();
7867 return true;
7868 }
7869 }
7870
7871 return false;
7872}
Douglas Gregore60e41a2010-05-06 17:25:47 +00007873
John McCalldadc5752010-08-24 06:29:42 +00007874ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
7875 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00007876 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00007877 return ExprError();
7878
Douglas Gregorb412e172010-07-25 18:17:45 +00007879 if (CheckBooleanCondition(Sub, Loc))
Douglas Gregore60e41a2010-05-06 17:25:47 +00007880 return ExprError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00007881
7882 return Owned(Sub);
7883}