blob: 1ca47a40aa828e409c846eecd8cd844368d7df8c [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
14#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000017#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000018#include "clang/AST/DeclTemplate.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000019#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000020#include "clang/AST/ExprObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000021#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000023#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000024#include "clang/Lex/LiteralSupport.h"
25#include "clang/Lex/Preprocessor.h"
Steve Naroffc540d662008-09-03 18:15:37 +000026#include "clang/Parse/DeclSpec.h"
Chris Lattner07d754a2008-10-26 23:43:26 +000027#include "clang/Parse/Designator.h"
Steve Naroffc540d662008-09-03 18:15:37 +000028#include "clang/Parse/Scope.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000029#include "clang/Parse/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000030using namespace clang;
31
David Chisnall9f57c292009-08-17 16:35:33 +000032
Douglas Gregor171c45a2009-02-18 21:56:37 +000033/// \brief Determine whether the use of this declaration is valid, and
34/// emit any corresponding diagnostics.
35///
36/// This routine diagnoses various problems with referencing
37/// declarations that can occur when using a declaration. For example,
38/// it might warn if a deprecated or unavailable declaration is being
39/// used, or produce an error (and return true) if a C++0x deleted
40/// function is being used.
41///
Chris Lattnerb7df3c62009-10-25 22:31:57 +000042/// If IgnoreDeprecated is set to true, this should not want about deprecated
43/// decls.
44///
Douglas Gregor171c45a2009-02-18 21:56:37 +000045/// \returns true if there was an error (this declaration cannot be
46/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000047///
John McCall28a6aea2009-11-04 02:18:39 +000048bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner4bf74fd2009-02-15 22:43:40 +000049 // See if the decl is deprecated.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000050 if (D->getAttr<DeprecatedAttr>()) {
John McCall28a6aea2009-11-04 02:18:39 +000051 EmitDeprecationWarning(D, Loc);
Chris Lattner4bf74fd2009-02-15 22:43:40 +000052 }
53
Chris Lattnera27dd592009-10-25 17:21:40 +000054 // See if the decl is unavailable
55 if (D->getAttr<UnavailableAttr>()) {
56 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
57 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
58 }
59
Douglas Gregor171c45a2009-02-18 21:56:37 +000060 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000061 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000062 if (FD->isDeleted()) {
63 Diag(Loc, diag::err_deleted_function_use);
64 Diag(D->getLocation(), diag::note_unavailable_here) << true;
65 return true;
66 }
Douglas Gregorde681d42009-02-24 04:26:15 +000067 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000068
Douglas Gregor171c45a2009-02-18 21:56:37 +000069 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +000070}
71
Fariborz Jahanian027b8862009-05-13 18:09:35 +000072/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +000073/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +000074/// attribute. It warns if call does not have the sentinel argument.
75///
76void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +000077 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000078 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +000079 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +000080 return;
Fariborz Jahanian9e877212009-05-13 23:20:50 +000081 int sentinelPos = attr->getSentinel();
82 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +000083
Mike Stump87c57ac2009-05-16 07:39:55 +000084 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
85 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +000086 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +000087 bool warnNotEnoughArgs = false;
88 int isMethod = 0;
89 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
90 // skip over named parameters.
91 ObjCMethodDecl::param_iterator P, E = MD->param_end();
92 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
93 if (nullPos)
94 --nullPos;
95 else
96 ++i;
97 }
98 warnNotEnoughArgs = (P != E || i >= NumArgs);
99 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000100 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000101 // skip over named parameters.
102 ObjCMethodDecl::param_iterator P, E = FD->param_end();
103 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
104 if (nullPos)
105 --nullPos;
106 else
107 ++i;
108 }
109 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000110 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000111 // block or function pointer call.
112 QualType Ty = V->getType();
113 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000114 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000115 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
116 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000117 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
118 unsigned NumArgsInProto = Proto->getNumArgs();
119 unsigned k;
120 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
121 if (nullPos)
122 --nullPos;
123 else
124 ++i;
125 }
126 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
127 }
128 if (Ty->isBlockPointerType())
129 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000130 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000131 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000132 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000133 return;
134
135 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000136 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000137 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000138 return;
139 }
140 int sentinel = i;
141 while (sentinelPos > 0 && i < NumArgs-1) {
142 --sentinelPos;
143 ++i;
144 }
145 if (sentinelPos > 0) {
146 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 while (i < NumArgs-1) {
151 ++i;
152 ++sentinel;
153 }
154 Expr *sentinelExpr = Args[sentinel];
Anders Carlsson0b11a3e2009-11-24 17:24:21 +0000155 if (sentinelExpr && (!isa<GNUNullExpr>(sentinelExpr) &&
156 (!sentinelExpr->getType()->isPointerType() ||
157 !sentinelExpr->isNullPointerConstant(Context,
158 Expr::NPC_ValueDependentIsNull)))) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000159 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000160 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000161 }
162 return;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000163}
164
Douglas Gregor87f95b02009-02-26 21:00:50 +0000165SourceRange Sema::getExprRange(ExprTy *E) const {
166 Expr *Ex = (Expr *)E;
167 return Ex? Ex->getSourceRange() : SourceRange();
168}
169
Chris Lattner513165e2008-07-25 21:10:04 +0000170//===----------------------------------------------------------------------===//
171// Standard Promotions and Conversions
172//===----------------------------------------------------------------------===//
173
Chris Lattner513165e2008-07-25 21:10:04 +0000174/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
175void Sema::DefaultFunctionArrayConversion(Expr *&E) {
176 QualType Ty = E->getType();
177 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
178
Chris Lattner513165e2008-07-25 21:10:04 +0000179 if (Ty->isFunctionType())
Mike Stump11289f42009-09-09 15:08:12 +0000180 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlsson6904f642009-09-01 20:37:18 +0000181 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000182 else if (Ty->isArrayType()) {
183 // In C90 mode, arrays only promote to pointers if the array expression is
184 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
185 // type 'array of type' is converted to an expression that has type 'pointer
186 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
187 // that has type 'array of type' ...". The relevant change is "an lvalue"
188 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000189 //
190 // C++ 4.2p1:
191 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
192 // T" can be converted to an rvalue of type "pointer to T".
193 //
194 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
195 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson8fc489d2009-08-07 23:48:20 +0000196 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
197 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000198 }
Chris Lattner513165e2008-07-25 21:10:04 +0000199}
200
201/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000202/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner513165e2008-07-25 21:10:04 +0000203/// sometimes surpressed. For example, the array->pointer conversion doesn't
204/// apply if the array is an argument to the sizeof or address (&) operators.
205/// In these instances, this routine should *not* be called.
206Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
207 QualType Ty = Expr->getType();
208 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000209
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000210 // C99 6.3.1.1p2:
211 //
212 // The following may be used in an expression wherever an int or
213 // unsigned int may be used:
214 // - an object or expression with an integer type whose integer
215 // conversion rank is less than or equal to the rank of int
216 // and unsigned int.
217 // - A bit-field of type _Bool, int, signed int, or unsigned int.
218 //
219 // If an int can represent all values of the original type, the
220 // value is converted to an int; otherwise, it is converted to an
221 // unsigned int. These are called the integer promotions. All
222 // other types are unchanged by the integer promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000223 QualType PTy = Context.isPromotableBitField(Expr);
224 if (!PTy.isNull()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +0000225 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman629ffb92009-08-20 04:21:42 +0000226 return Expr;
227 }
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000228 if (Ty->isPromotableIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000229 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman06ed2a52009-10-20 08:27:19 +0000230 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000231 return Expr;
Eli Friedman629ffb92009-08-20 04:21:42 +0000232 }
233
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000234 DefaultFunctionArrayConversion(Expr);
Chris Lattner513165e2008-07-25 21:10:04 +0000235 return Expr;
236}
237
Chris Lattner2ce500f2008-07-25 22:25:12 +0000238/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000239/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000240/// double. All other argument types are converted by UsualUnaryConversions().
241void Sema::DefaultArgumentPromotion(Expr *&Expr) {
242 QualType Ty = Expr->getType();
243 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000244
Chris Lattner2ce500f2008-07-25 22:25:12 +0000245 // If this is a 'float' (CVR qualified or typedef) promote to double.
John McCall9dd450b2009-09-21 23:43:11 +0000246 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
Chris Lattner2ce500f2008-07-25 22:25:12 +0000247 if (BT->getKind() == BuiltinType::Float)
Eli Friedman06ed2a52009-10-20 08:27:19 +0000248 return ImpCastExprToType(Expr, Context.DoubleTy,
249 CastExpr::CK_FloatingCast);
Mike Stump11289f42009-09-09 15:08:12 +0000250
Chris Lattner2ce500f2008-07-25 22:25:12 +0000251 UsualUnaryConversions(Expr);
252}
253
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000254/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
255/// will warn if the resulting type is not a POD type, and rejects ObjC
256/// interfaces passed by value. This returns true if the argument type is
257/// completely illegal.
258bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssona7d069d2009-01-16 16:48:51 +0000259 DefaultArgumentPromotion(Expr);
Mike Stump11289f42009-09-09 15:08:12 +0000260
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000261 if (Expr->getType()->isObjCInterfaceType()) {
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000262 switch (ExprEvalContexts.back().Context ) {
263 case Unevaluated:
264 // The argument will never be evaluated, so don't complain.
265 break;
266
267 case PotentiallyEvaluated:
268 Diag(Expr->getLocStart(),
269 diag::err_cannot_pass_objc_interface_to_vararg)
270 << Expr->getType() << CT;
271 return true;
272
273 case PotentiallyPotentiallyEvaluated:
274 // FIXME: queue it!
275 break;
276 }
Anders Carlssona7d069d2009-01-16 16:48:51 +0000277 }
Mike Stump11289f42009-09-09 15:08:12 +0000278
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000279 if (!Expr->getType()->isPODType()) {
280 switch (ExprEvalContexts.back().Context ) {
281 case Unevaluated:
282 // The argument will never be evaluated, so don't complain.
283 break;
284
285 case PotentiallyEvaluated:
286 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
287 << Expr->getType() << CT;
288 break;
289
290 case PotentiallyPotentiallyEvaluated:
291 // FIXME: queue it!
292 break;
293 }
294 }
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000295
296 return false;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000297}
298
299
Chris Lattner513165e2008-07-25 21:10:04 +0000300/// UsualArithmeticConversions - Performs various conversions that are common to
301/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000302/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000303/// responsible for emitting appropriate error diagnostics.
304/// FIXME: verify the conversion rules for "complex int" are consistent with
305/// GCC.
306QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
307 bool isCompAssign) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000308 if (!isCompAssign)
Chris Lattner513165e2008-07-25 21:10:04 +0000309 UsualUnaryConversions(lhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000310
311 UsualUnaryConversions(rhsExpr);
Douglas Gregora11693b2008-11-12 17:17:38 +0000312
Mike Stump11289f42009-09-09 15:08:12 +0000313 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000314 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000315 QualType lhs =
316 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000317 QualType rhs =
Chris Lattner574dee62008-07-26 22:17:49 +0000318 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000319
320 // If both types are identical, no conversion is needed.
321 if (lhs == rhs)
322 return lhs;
323
324 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
325 // The caller can deal with this (e.g. pointer + int).
326 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
327 return lhs;
328
Douglas Gregord2c2d172009-05-02 00:36:19 +0000329 // Perform bitfield promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000330 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000331 if (!LHSBitfieldPromoteTy.isNull())
332 lhs = LHSBitfieldPromoteTy;
Eli Friedman629ffb92009-08-20 04:21:42 +0000333 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000334 if (!RHSBitfieldPromoteTy.isNull())
335 rhs = RHSBitfieldPromoteTy;
336
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000337 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000338 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +0000339 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
340 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregora11693b2008-11-12 17:17:38 +0000341 return destType;
342}
343
Chris Lattner513165e2008-07-25 21:10:04 +0000344//===----------------------------------------------------------------------===//
345// Semantic Analysis for various Expression Types
346//===----------------------------------------------------------------------===//
347
348
Steve Naroff83895f72007-09-16 03:34:24 +0000349/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000350/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
351/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
352/// multiple tokens. However, the common case is that StringToks points to one
353/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000354///
355Action::OwningExprResult
Steve Naroff83895f72007-09-16 03:34:24 +0000356Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000357 assert(NumStringToks && "Must have at least one string!");
358
Chris Lattner8a24e582009-01-16 18:51:42 +0000359 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000360 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000361 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000362
Chris Lattner23b7eb62007-06-15 23:05:46 +0000363 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000364 for (unsigned i = 0; i != NumStringToks; ++i)
365 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000366
Chris Lattner36fc8792008-02-11 00:02:17 +0000367 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidiscbad7252008-08-09 17:20:01 +0000368 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattner36fc8792008-02-11 00:02:17 +0000369 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000370
371 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
372 if (getLangOptions().CPlusPlus)
373 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000374
Chris Lattner36fc8792008-02-11 00:02:17 +0000375 // Get an array type for the string, according to C99 6.4.5. This includes
376 // the nul terminator character as well as the string length for pascal
377 // strings.
378 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000379 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000380 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000381
Chris Lattner5b183d82006-11-10 05:03:26 +0000382 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump11289f42009-09-09 15:08:12 +0000383 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000384 Literal.GetStringLength(),
385 Literal.AnyWide, StrTy,
386 &StringTokLocs[0],
387 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000388}
389
Chris Lattner2a9d9892008-10-20 05:16:36 +0000390/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
391/// CurBlock to VD should cause it to be snapshotted (as we do for auto
392/// variables defined outside the block) or false if this is not needed (e.g.
393/// for values inside the block or for globals).
394///
Chris Lattner497d7b02009-04-21 22:26:47 +0000395/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
396/// up-to-date.
397///
Chris Lattner2a9d9892008-10-20 05:16:36 +0000398static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
399 ValueDecl *VD) {
400 // If the value is defined inside the block, we couldn't snapshot it even if
401 // we wanted to.
402 if (CurBlock->TheDecl == VD->getDeclContext())
403 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000404
Chris Lattner2a9d9892008-10-20 05:16:36 +0000405 // If this is an enum constant or function, it is constant, don't snapshot.
406 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
407 return false;
408
409 // If this is a reference to an extern, static, or global variable, no need to
410 // snapshot it.
411 // FIXME: What about 'const' variables in C++?
412 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner497d7b02009-04-21 22:26:47 +0000413 if (!Var->hasLocalStorage())
414 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000415
Chris Lattner497d7b02009-04-21 22:26:47 +0000416 // Blocks that have these can't be constant.
417 CurBlock->hasBlockDeclRefExprs = true;
418
419 // If we have nested blocks, the decl may be declared in an outer block (in
420 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
421 // be defined outside all of the current blocks (in which case the blocks do
422 // all get the bit). Walk the nesting chain.
423 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
424 NextBlock = NextBlock->PrevBlockInfo) {
425 // If we found the defining block for the variable, don't mark the block as
426 // having a reference outside it.
427 if (NextBlock->TheDecl == VD->getDeclContext())
428 break;
Mike Stump11289f42009-09-09 15:08:12 +0000429
Chris Lattner497d7b02009-04-21 22:26:47 +0000430 // Otherwise, the DeclRef from the inner block causes the outer one to need
431 // a snapshot as well.
432 NextBlock->hasBlockDeclRefExprs = true;
433 }
Mike Stump11289f42009-09-09 15:08:12 +0000434
Chris Lattner2a9d9892008-10-20 05:16:36 +0000435 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000436}
437
Chris Lattner2a9d9892008-10-20 05:16:36 +0000438
439
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000440/// BuildDeclRefExpr - Build a DeclRefExpr.
Anders Carlsson946b86d2009-06-24 00:10:43 +0000441Sema::OwningExprResult
John McCallce546572009-12-08 09:08:17 +0000442Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc,
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000443 const CXXScopeSpec *SS) {
Anders Carlsson364035d12009-06-26 19:16:07 +0000444 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
445 Diag(Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000446 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlsson364035d12009-06-26 19:16:07 +0000447 << D->getDeclName();
448 return ExprError();
449 }
Mike Stump11289f42009-09-09 15:08:12 +0000450
Anders Carlsson946b86d2009-06-24 00:10:43 +0000451 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
452 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
453 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
454 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Mike Stump11289f42009-09-09 15:08:12 +0000455 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000456 << D->getIdentifier() << FD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +0000457 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000458 << D->getIdentifier();
459 return ExprError();
460 }
461 }
462 }
463 }
Mike Stump11289f42009-09-09 15:08:12 +0000464
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000465 MarkDeclarationReferenced(Loc, D);
Mike Stump11289f42009-09-09 15:08:12 +0000466
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000467 return Owned(DeclRefExpr::Create(Context,
468 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
469 SS? SS->getRange() : SourceRange(),
Douglas Gregored6c7442009-11-23 11:41:28 +0000470 D, Loc, Ty));
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000471}
472
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000473/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
474/// variable corresponding to the anonymous union or struct whose type
475/// is Record.
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000476static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
477 RecordDecl *Record) {
Mike Stump11289f42009-09-09 15:08:12 +0000478 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000479 "Record must be an anonymous struct or union!");
Mike Stump11289f42009-09-09 15:08:12 +0000480
Mike Stump87c57ac2009-05-16 07:39:55 +0000481 // FIXME: Once Decls are directly linked together, this will be an O(1)
482 // operation rather than a slow walk through DeclContext's vector (which
483 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000484 DeclContext *Ctx = Record->getDeclContext();
Mike Stump11289f42009-09-09 15:08:12 +0000485 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000486 DEnd = Ctx->decls_end();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000487 D != DEnd; ++D) {
488 if (*D == Record) {
489 // The object for the anonymous struct/union directly
490 // follows its type in the list of declarations.
491 ++D;
492 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000493 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000494 return *D;
495 }
496 }
497
498 assert(false && "Missing object for anonymous record");
499 return 0;
500}
501
Douglas Gregord5846a12009-04-15 06:41:24 +0000502/// \brief Given a field that represents a member of an anonymous
503/// struct/union, build the path from that field's context to the
504/// actual member.
505///
506/// Construct the sequence of field member references we'll have to
507/// perform to get to the field in the anonymous union/struct. The
508/// list of members is built from the field outward, so traverse it
509/// backwards to go from an object in the current context to the field
510/// we found.
511///
512/// \returns The variable from which the field access should begin,
513/// for an anonymous struct/union that is not a member of another
514/// class. Otherwise, returns NULL.
515VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
516 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000517 assert(Field->getDeclContext()->isRecord() &&
518 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
519 && "Field must be stored inside an anonymous struct or union");
520
Douglas Gregord5846a12009-04-15 06:41:24 +0000521 Path.push_back(Field);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000522 VarDecl *BaseObject = 0;
523 DeclContext *Ctx = Field->getDeclContext();
524 do {
525 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000526 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000527 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregord5846a12009-04-15 06:41:24 +0000528 Path.push_back(AnonField);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000529 else {
530 BaseObject = cast<VarDecl>(AnonObject);
531 break;
532 }
533 Ctx = Ctx->getParent();
Mike Stump11289f42009-09-09 15:08:12 +0000534 } while (Ctx->isRecord() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000535 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregord5846a12009-04-15 06:41:24 +0000536
537 return BaseObject;
538}
539
540Sema::OwningExprResult
541Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
542 FieldDecl *Field,
543 Expr *BaseObjectExpr,
544 SourceLocation OpLoc) {
545 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump11289f42009-09-09 15:08:12 +0000546 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregord5846a12009-04-15 06:41:24 +0000547 AnonFields);
548
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000549 // Build the expression that refers to the base object, from
550 // which we will build a sequence of member references to each
551 // of the anonymous union objects and, eventually, the field we
552 // found via name lookup.
553 bool BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000554 Qualifiers BaseQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000555 if (BaseObject) {
556 // BaseObject is an anonymous struct/union variable (and is,
557 // therefore, not part of another non-anonymous record).
Ted Kremenek5a201952009-02-07 01:47:29 +0000558 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000559 MarkDeclarationReferenced(Loc, BaseObject);
Steve Narofff6009ed2009-01-21 00:14:39 +0000560 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump4e1f26a2009-02-19 03:04:26 +0000561 SourceLocation());
John McCall8ccfcb52009-09-24 19:53:00 +0000562 BaseQuals
563 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000564 } else if (BaseObjectExpr) {
565 // The caller provided the base object expression. Determine
566 // whether its a pointer and whether it adds any qualifiers to the
567 // anonymous struct/union fields we're looking into.
568 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000569 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000570 BaseObjectIsPointer = true;
571 ObjectType = ObjectPtr->getPointeeType();
572 }
John McCall8ccfcb52009-09-24 19:53:00 +0000573 BaseQuals
574 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000575 } else {
576 // We've found a member of an anonymous struct/union that is
577 // inside a non-anonymous struct/union, so in a well-formed
578 // program our base object expression is "this".
579 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
580 if (!MD->isStatic()) {
Mike Stump11289f42009-09-09 15:08:12 +0000581 QualType AnonFieldType
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000582 = Context.getTagDeclType(
583 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
584 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump11289f42009-09-09 15:08:12 +0000585 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000586 == Context.getCanonicalType(ThisType)) ||
587 IsDerivedFrom(ThisType, AnonFieldType)) {
588 // Our base object expression is "this".
Steve Narofff6009ed2009-01-21 00:14:39 +0000589 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump4e1f26a2009-02-19 03:04:26 +0000590 MD->getThisType(Context));
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000591 BaseObjectIsPointer = true;
592 }
593 } else {
Sebastian Redlffbcf962009-01-18 18:53:16 +0000594 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
595 << Field->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000596 }
John McCall8ccfcb52009-09-24 19:53:00 +0000597 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000598 }
599
Mike Stump11289f42009-09-09 15:08:12 +0000600 if (!BaseObjectExpr)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000601 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
602 << Field->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000603 }
604
605 // Build the implicit member references to the field of the
606 // anonymous struct/union.
607 Expr *Result = BaseObjectExpr;
John McCall8ccfcb52009-09-24 19:53:00 +0000608 Qualifiers ResultQuals = BaseQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000609 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
610 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
611 FI != FIEnd; ++FI) {
612 QualType MemberType = (*FI)->getType();
John McCall8ccfcb52009-09-24 19:53:00 +0000613 Qualifiers MemberTypeQuals =
614 Context.getCanonicalType(MemberType).getQualifiers();
615
616 // CVR attributes from the base are picked up by members,
617 // except that 'mutable' members don't pick up 'const'.
618 if ((*FI)->isMutable())
619 ResultQuals.removeConst();
620
621 // GC attributes are never picked up by members.
622 ResultQuals.removeObjCGCAttr();
623
624 // TR 18037 does not allow fields to be declared with address spaces.
625 assert(!MemberTypeQuals.hasAddressSpace());
626
627 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
628 if (NewQuals != MemberTypeQuals)
629 MemberType = Context.getQualifiedType(MemberType, NewQuals);
630
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000631 MarkDeclarationReferenced(Loc, *FI);
Eli Friedman78cde142009-12-04 07:18:51 +0000632 PerformObjectMemberConversion(Result, *FI);
Douglas Gregorc1905232009-08-26 22:36:53 +0000633 // FIXME: Might this end up being a qualified name?
Steve Narofff6009ed2009-01-21 00:14:39 +0000634 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
635 OpLoc, MemberType);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000636 BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000637 ResultQuals = NewQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000638 }
639
Sebastian Redlffbcf962009-01-18 18:53:16 +0000640 return Owned(Result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000641}
642
John McCall10eae182009-11-30 22:42:35 +0000643/// Decomposes the given name into a DeclarationName, its location, and
644/// possibly a list of template arguments.
645///
646/// If this produces template arguments, it is permitted to call
647/// DecomposeTemplateName.
648///
649/// This actually loses a lot of source location information for
650/// non-standard name kinds; we should consider preserving that in
651/// some way.
652static void DecomposeUnqualifiedId(Sema &SemaRef,
653 const UnqualifiedId &Id,
654 TemplateArgumentListInfo &Buffer,
655 DeclarationName &Name,
656 SourceLocation &NameLoc,
657 const TemplateArgumentListInfo *&TemplateArgs) {
658 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
659 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
660 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
661
662 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
663 Id.TemplateId->getTemplateArgs(),
664 Id.TemplateId->NumArgs);
665 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
666 TemplateArgsPtr.release();
667
668 TemplateName TName =
669 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
670
671 Name = SemaRef.Context.getNameForTemplate(TName);
672 NameLoc = Id.TemplateId->TemplateNameLoc;
673 TemplateArgs = &Buffer;
674 } else {
675 Name = SemaRef.GetNameFromUnqualifiedId(Id);
676 NameLoc = Id.StartLocation;
677 TemplateArgs = 0;
678 }
679}
680
681/// Decompose the given template name into a list of lookup results.
682///
683/// The unqualified ID must name a non-dependent template, which can
684/// be more easily tested by checking whether DecomposeUnqualifiedId
685/// found template arguments.
686static void DecomposeTemplateName(LookupResult &R, const UnqualifiedId &Id) {
687 assert(Id.getKind() == UnqualifiedId::IK_TemplateId);
688 TemplateName TName =
689 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
690
John McCalle66edc12009-11-24 19:00:30 +0000691 if (TemplateDecl *TD = TName.getAsTemplateDecl())
692 R.addDecl(TD);
John McCalld28ae272009-12-02 08:04:21 +0000693 else if (OverloadedTemplateStorage *OT = TName.getAsOverloadedTemplate())
694 for (OverloadedTemplateStorage::iterator I = OT->begin(), E = OT->end();
695 I != E; ++I)
John McCalle66edc12009-11-24 19:00:30 +0000696 R.addDecl(*I);
John McCalla9ee3252009-11-22 02:49:43 +0000697
John McCalle66edc12009-11-24 19:00:30 +0000698 R.resolveKind();
Douglas Gregora121b752009-11-03 16:56:39 +0000699}
700
John McCall10eae182009-11-30 22:42:35 +0000701static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
702 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
703 E = Record->bases_end(); I != E; ++I) {
704 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
705 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
706 if (!BaseRT) return false;
707
708 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
709 if (!BaseRecord->isDefinition() ||
710 !IsFullyFormedScope(SemaRef, BaseRecord))
711 return false;
712 }
713
714 return true;
715}
716
John McCallf786fb12009-11-30 23:50:49 +0000717/// Determines whether we can lookup this id-expression now or whether
718/// we have to wait until template instantiation is complete.
719static bool IsDependentIdExpression(Sema &SemaRef, const CXXScopeSpec &SS) {
John McCall10eae182009-11-30 22:42:35 +0000720 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
John McCall10eae182009-11-30 22:42:35 +0000721
John McCallf786fb12009-11-30 23:50:49 +0000722 // If the qualifier scope isn't computable, it's definitely dependent.
723 if (!DC) return true;
724
725 // If the qualifier scope doesn't name a record, we can always look into it.
726 if (!isa<CXXRecordDecl>(DC)) return false;
727
728 // We can't look into record types unless they're fully-formed.
729 if (!IsFullyFormedScope(SemaRef, cast<CXXRecordDecl>(DC))) return true;
730
John McCall2d74de92009-12-01 22:10:20 +0000731 return false;
732}
John McCallf786fb12009-11-30 23:50:49 +0000733
John McCall2d74de92009-12-01 22:10:20 +0000734/// Determines if the given class is provably not derived from all of
735/// the prospective base classes.
736static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
737 CXXRecordDecl *Record,
738 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +0000739 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +0000740 return false;
741
John McCalla6d407c2009-12-01 22:28:41 +0000742 RecordDecl *RD = Record->getDefinition(SemaRef.Context);
743 if (!RD) return false;
744 Record = cast<CXXRecordDecl>(RD);
745
John McCall2d74de92009-12-01 22:10:20 +0000746 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
747 E = Record->bases_end(); I != E; ++I) {
748 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
749 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
750 if (!BaseRT) return false;
751
752 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +0000753 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
754 return false;
755 }
756
757 return true;
758}
759
John McCall5af04502009-12-02 20:26:00 +0000760/// Determines if this a C++ class member.
761static bool IsClassMember(NamedDecl *D) {
762 DeclContext *DC = D->getDeclContext();
John McCall1a49e9d2009-12-02 19:59:55 +0000763
John McCall5af04502009-12-02 20:26:00 +0000764 // C++0x [class.mem]p1:
765 // The enumerators of an unscoped enumeration defined in
766 // the class are members of the class.
767 // FIXME: support C++0x scoped enumerations.
768 if (isa<EnumDecl>(DC))
769 DC = DC->getParent();
770
771 return DC->isRecord();
772}
773
774/// Determines if this is an instance member of a class.
775static bool IsInstanceMember(NamedDecl *D) {
776 assert(IsClassMember(D) &&
John McCall2d74de92009-12-01 22:10:20 +0000777 "checking whether non-member is instance member");
778
779 if (isa<FieldDecl>(D)) return true;
780
781 if (isa<CXXMethodDecl>(D))
782 return !cast<CXXMethodDecl>(D)->isStatic();
783
784 if (isa<FunctionTemplateDecl>(D)) {
785 D = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
786 return !cast<CXXMethodDecl>(D)->isStatic();
787 }
788
789 return false;
790}
791
792enum IMAKind {
793 /// The reference is definitely not an instance member access.
794 IMA_Static,
795
796 /// The reference may be an implicit instance member access.
797 IMA_Mixed,
798
799 /// The reference may be to an instance member, but it is invalid if
800 /// so, because the context is not an instance method.
801 IMA_Mixed_StaticContext,
802
803 /// The reference may be to an instance member, but it is invalid if
804 /// so, because the context is from an unrelated class.
805 IMA_Mixed_Unrelated,
806
807 /// The reference is definitely an implicit instance member access.
808 IMA_Instance,
809
810 /// The reference may be to an unresolved using declaration.
811 IMA_Unresolved,
812
813 /// The reference may be to an unresolved using declaration and the
814 /// context is not an instance method.
815 IMA_Unresolved_StaticContext,
816
817 /// The reference is to a member of an anonymous structure in a
818 /// non-class context.
819 IMA_AnonymousMember,
820
821 /// All possible referrents are instance members and the current
822 /// context is not an instance method.
823 IMA_Error_StaticContext,
824
825 /// All possible referrents are instance members of an unrelated
826 /// class.
827 IMA_Error_Unrelated
828};
829
830/// The given lookup names class member(s) and is not being used for
831/// an address-of-member expression. Classify the type of access
832/// according to whether it's possible that this reference names an
833/// instance member. This is best-effort; it is okay to
834/// conservatively answer "yes", in which case some errors will simply
835/// not be caught until template-instantiation.
836static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
837 const LookupResult &R) {
John McCall5af04502009-12-02 20:26:00 +0000838 assert(!R.empty() && IsClassMember(*R.begin()));
John McCall2d74de92009-12-01 22:10:20 +0000839
840 bool isStaticContext =
841 (!isa<CXXMethodDecl>(SemaRef.CurContext) ||
842 cast<CXXMethodDecl>(SemaRef.CurContext)->isStatic());
843
844 if (R.isUnresolvableResult())
845 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
846
847 // Collect all the declaring classes of instance members we find.
848 bool hasNonInstance = false;
849 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
850 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
851 NamedDecl *D = (*I)->getUnderlyingDecl();
852 if (IsInstanceMember(D)) {
853 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
854
855 // If this is a member of an anonymous record, move out to the
856 // innermost non-anonymous struct or union. If there isn't one,
857 // that's a special case.
858 while (R->isAnonymousStructOrUnion()) {
859 R = dyn_cast<CXXRecordDecl>(R->getParent());
860 if (!R) return IMA_AnonymousMember;
861 }
862 Classes.insert(R->getCanonicalDecl());
863 }
864 else
865 hasNonInstance = true;
866 }
867
868 // If we didn't find any instance members, it can't be an implicit
869 // member reference.
870 if (Classes.empty())
871 return IMA_Static;
872
873 // If the current context is not an instance method, it can't be
874 // an implicit member reference.
875 if (isStaticContext)
876 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
877
878 // If we can prove that the current context is unrelated to all the
879 // declaring classes, it can't be an implicit member reference (in
880 // which case it's an error if any of those members are selected).
881 if (IsProvablyNotDerivedFrom(SemaRef,
882 cast<CXXMethodDecl>(SemaRef.CurContext)->getParent(),
883 Classes))
884 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
885
886 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
887}
888
889/// Diagnose a reference to a field with no object available.
890static void DiagnoseInstanceReference(Sema &SemaRef,
891 const CXXScopeSpec &SS,
892 const LookupResult &R) {
893 SourceLocation Loc = R.getNameLoc();
894 SourceRange Range(Loc);
895 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
896
897 if (R.getAsSingle<FieldDecl>()) {
898 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
899 if (MD->isStatic()) {
900 // "invalid use of member 'x' in static member function"
901 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
902 << Range << R.getLookupName();
903 return;
904 }
905 }
906
907 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
908 << R.getLookupName() << Range;
909 return;
910 }
911
912 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +0000913}
914
John McCalle66edc12009-11-24 19:00:30 +0000915Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
916 const CXXScopeSpec &SS,
917 UnqualifiedId &Id,
918 bool HasTrailingLParen,
919 bool isAddressOfOperand) {
920 assert(!(isAddressOfOperand && HasTrailingLParen) &&
921 "cannot be direct & operand and have a trailing lparen");
922
923 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +0000924 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +0000925
John McCall10eae182009-11-30 22:42:35 +0000926 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +0000927
928 // Decompose the UnqualifiedId into the following data.
929 DeclarationName Name;
930 SourceLocation NameLoc;
931 const TemplateArgumentListInfo *TemplateArgs;
John McCall10eae182009-11-30 22:42:35 +0000932 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
933 Name, NameLoc, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +0000934
Douglas Gregor4ea80432008-11-18 15:03:34 +0000935 IdentifierInfo *II = Name.getAsIdentifierInfo();
John McCalld14a8642009-11-21 08:51:07 +0000936
John McCalle66edc12009-11-24 19:00:30 +0000937 // C++ [temp.dep.expr]p3:
938 // An id-expression is type-dependent if it contains:
939 // -- a nested-name-specifier that contains a class-name that
940 // names a dependent type.
941 // Determine whether this is a member of an unknown specialization;
942 // we need to handle these differently.
John McCallf786fb12009-11-30 23:50:49 +0000943 if (SS.isSet() && IsDependentIdExpression(*this, SS)) {
John McCalle66edc12009-11-24 19:00:30 +0000944 return ActOnDependentIdExpression(SS, Name, NameLoc,
John McCallcd4b4772009-12-02 03:53:29 +0000945 isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000946 TemplateArgs);
947 }
John McCalld14a8642009-11-21 08:51:07 +0000948
John McCalle66edc12009-11-24 19:00:30 +0000949 // Perform the required lookup.
950 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
951 if (TemplateArgs) {
John McCalle66edc12009-11-24 19:00:30 +0000952 // Just re-use the lookup done by isTemplateName.
John McCall10eae182009-11-30 22:42:35 +0000953 DecomposeTemplateName(R, Id);
John McCalle66edc12009-11-24 19:00:30 +0000954 } else {
955 LookupParsedName(R, S, &SS, true);
Mike Stump11289f42009-09-09 15:08:12 +0000956
John McCalle66edc12009-11-24 19:00:30 +0000957 // If this reference is in an Objective-C method, then we need to do
958 // some special Objective-C lookup, too.
959 if (!SS.isSet() && II && getCurMethodDecl()) {
960 OwningExprResult E(LookupInObjCMethod(R, S, II));
961 if (E.isInvalid())
962 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000963
John McCalle66edc12009-11-24 19:00:30 +0000964 Expr *Ex = E.takeAs<Expr>();
965 if (Ex) return Owned(Ex);
Steve Naroffebf4cb42008-06-02 23:03:37 +0000966 }
Chris Lattner59a25942008-03-31 00:36:02 +0000967 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +0000968
John McCalle66edc12009-11-24 19:00:30 +0000969 if (R.isAmbiguous())
970 return ExprError();
971
Douglas Gregor171c45a2009-02-18 21:56:37 +0000972 // Determine whether this name might be a candidate for
973 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +0000974 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +0000975
John McCalle66edc12009-11-24 19:00:30 +0000976 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +0000977 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +0000978 // in C90, extension in C99, forbidden in C++).
979 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
980 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
981 if (D) R.addDecl(D);
982 }
983
984 // If this name wasn't predeclared and if this is not a function
985 // call, diagnose the problem.
986 if (R.empty()) {
987 if (!SS.isEmpty())
988 return ExprError(Diag(NameLoc, diag::err_no_member)
989 << Name << computeDeclContext(SS, false)
990 << SS.getRange());
Douglas Gregore40876a2009-10-13 21:16:44 +0000991 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
Alexis Hunt3d221f22009-11-29 07:34:05 +0000992 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor4ea80432008-11-18 15:03:34 +0000993 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
John McCalle66edc12009-11-24 19:00:30 +0000994 return ExprError(Diag(NameLoc, diag::err_undeclared_use)
995 << Name);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000996 else
John McCalle66edc12009-11-24 19:00:30 +0000997 return ExprError(Diag(NameLoc, diag::err_undeclared_var_use) << Name);
Steve Naroff92e30f82007-04-02 22:35:25 +0000998 }
Chris Lattner17ed4872006-11-20 04:58:19 +0000999 }
Mike Stump11289f42009-09-09 15:08:12 +00001000
John McCalle66edc12009-11-24 19:00:30 +00001001 // This is guaranteed from this point on.
1002 assert(!R.empty() || ADL);
1003
1004 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001005 // Warn about constructs like:
1006 // if (void *X = foo()) { ... } else { X }.
1007 // In the else block, the pointer is always false.
Mike Stump11289f42009-09-09 15:08:12 +00001008
Douglas Gregor3256d042009-06-30 15:47:41 +00001009 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
1010 Scope *CheckS = S;
Douglas Gregor13a2c032009-11-05 17:49:26 +00001011 while (CheckS && CheckS->getControlParent()) {
Mike Stump11289f42009-09-09 15:08:12 +00001012 if (CheckS->isWithinElse() &&
Douglas Gregor3256d042009-06-30 15:47:41 +00001013 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
John McCalle66edc12009-11-24 19:00:30 +00001014 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
Douglas Gregor13a2c032009-11-05 17:49:26 +00001015 << Var->getDeclName()
1016 << (Var->getType()->isPointerType()? 2 :
1017 Var->getType()->isBooleanType()? 1 : 0));
Douglas Gregor3256d042009-06-30 15:47:41 +00001018 break;
1019 }
Mike Stump11289f42009-09-09 15:08:12 +00001020
Douglas Gregor13a2c032009-11-05 17:49:26 +00001021 // Move to the parent of this scope.
1022 CheckS = CheckS->getParent();
Douglas Gregor3256d042009-06-30 15:47:41 +00001023 }
1024 }
John McCalle66edc12009-11-24 19:00:30 +00001025 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001026 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1027 // C99 DR 316 says that, if a function type comes from a
1028 // function definition (without a prototype), that type is only
1029 // used for checking compatibility. Therefore, when referencing
1030 // the function, we pretend that we don't have the full function
1031 // type.
John McCalle66edc12009-11-24 19:00:30 +00001032 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor3256d042009-06-30 15:47:41 +00001033 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001034
Douglas Gregor3256d042009-06-30 15:47:41 +00001035 QualType T = Func->getType();
1036 QualType NoProtoType = T;
John McCall9dd450b2009-09-21 23:43:11 +00001037 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor3256d042009-06-30 15:47:41 +00001038 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
John McCalle66edc12009-11-24 19:00:30 +00001039 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor3256d042009-06-30 15:47:41 +00001040 }
1041 }
Mike Stump11289f42009-09-09 15:08:12 +00001042
John McCall2d74de92009-12-01 22:10:20 +00001043 // Check whether this might be a C++ implicit instance member access.
1044 // C++ [expr.prim.general]p6:
1045 // Within the definition of a non-static member function, an
1046 // identifier that names a non-static member is transformed to a
1047 // class member access expression.
1048 // But note that &SomeClass::foo is grammatically distinct, even
1049 // though we don't parse it that way.
John McCall5af04502009-12-02 20:26:00 +00001050 if (!R.empty() && IsClassMember(*R.begin())) {
John McCalle66edc12009-11-24 19:00:30 +00001051 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCallb53bbd42009-11-22 01:44:31 +00001052
John McCall2d74de92009-12-01 22:10:20 +00001053 if (!isAbstractMemberPointer) {
1054 switch (ClassifyImplicitMemberAccess(*this, R)) {
1055 case IMA_Instance:
1056 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1057
1058 case IMA_AnonymousMember:
1059 assert(R.isSingleResult());
1060 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1061 R.getAsSingle<FieldDecl>());
1062
1063 case IMA_Mixed:
1064 case IMA_Mixed_Unrelated:
1065 case IMA_Unresolved:
1066 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1067
1068 case IMA_Static:
1069 case IMA_Mixed_StaticContext:
1070 case IMA_Unresolved_StaticContext:
1071 break;
1072
1073 case IMA_Error_StaticContext:
1074 case IMA_Error_Unrelated:
1075 DiagnoseInstanceReference(*this, SS, R);
1076 return ExprError();
1077 }
John McCallb53bbd42009-11-22 01:44:31 +00001078 }
1079 }
1080
John McCalle66edc12009-11-24 19:00:30 +00001081 if (TemplateArgs)
1082 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001083
John McCalle66edc12009-11-24 19:00:30 +00001084 return BuildDeclarationNameExpr(SS, R, ADL);
1085}
1086
John McCall10eae182009-11-30 22:42:35 +00001087/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1088/// declaration name, generally during template instantiation.
1089/// There's a large number of things which don't need to be done along
1090/// this path.
John McCalle66edc12009-11-24 19:00:30 +00001091Sema::OwningExprResult
1092Sema::BuildQualifiedDeclarationNameExpr(const CXXScopeSpec &SS,
1093 DeclarationName Name,
1094 SourceLocation NameLoc) {
1095 DeclContext *DC;
1096 if (!(DC = computeDeclContext(SS, false)) ||
1097 DC->isDependentContext() ||
1098 RequireCompleteDeclContext(SS))
1099 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
1100
1101 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1102 LookupQualifiedName(R, DC);
1103
1104 if (R.isAmbiguous())
1105 return ExprError();
1106
1107 if (R.empty()) {
1108 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
1109 return ExprError();
1110 }
1111
1112 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1113}
1114
1115/// LookupInObjCMethod - The parser has read a name in, and Sema has
1116/// detected that we're currently inside an ObjC method. Perform some
1117/// additional lookup.
1118///
1119/// Ideally, most of this would be done by lookup, but there's
1120/// actually quite a lot of extra work involved.
1121///
1122/// Returns a null sentinel to indicate trivial success.
1123Sema::OwningExprResult
1124Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1125 IdentifierInfo *II) {
1126 SourceLocation Loc = Lookup.getNameLoc();
1127
1128 // There are two cases to handle here. 1) scoped lookup could have failed,
1129 // in which case we should look for an ivar. 2) scoped lookup could have
1130 // found a decl, but that decl is outside the current instance method (i.e.
1131 // a global variable). In these two cases, we do a lookup for an ivar with
1132 // this name, if the lookup sucedes, we replace it our current decl.
1133
1134 // If we're in a class method, we don't normally want to look for
1135 // ivars. But if we don't find anything else, and there's an
1136 // ivar, that's an error.
1137 bool IsClassMethod = getCurMethodDecl()->isClassMethod();
1138
1139 bool LookForIvars;
1140 if (Lookup.empty())
1141 LookForIvars = true;
1142 else if (IsClassMethod)
1143 LookForIvars = false;
1144 else
1145 LookForIvars = (Lookup.isSingleResult() &&
1146 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1147
1148 if (LookForIvars) {
1149 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1150 ObjCInterfaceDecl *ClassDeclared;
1151 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1152 // Diagnose using an ivar in a class method.
1153 if (IsClassMethod)
1154 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1155 << IV->getDeclName());
1156
1157 // If we're referencing an invalid decl, just return this as a silent
1158 // error node. The error diagnostic was already emitted on the decl.
1159 if (IV->isInvalidDecl())
1160 return ExprError();
1161
1162 // Check if referencing a field with __attribute__((deprecated)).
1163 if (DiagnoseUseOfDecl(IV, Loc))
1164 return ExprError();
1165
1166 // Diagnose the use of an ivar outside of the declaring class.
1167 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1168 ClassDeclared != IFace)
1169 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1170
1171 // FIXME: This should use a new expr for a direct reference, don't
1172 // turn this into Self->ivar, just return a BareIVarExpr or something.
1173 IdentifierInfo &II = Context.Idents.get("self");
1174 UnqualifiedId SelfName;
1175 SelfName.setIdentifier(&II, SourceLocation());
1176 CXXScopeSpec SelfScopeSpec;
1177 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1178 SelfName, false, false);
1179 MarkDeclarationReferenced(Loc, IV);
1180 return Owned(new (Context)
1181 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1182 SelfExpr.takeAs<Expr>(), true, true));
1183 }
1184 } else if (getCurMethodDecl()->isInstanceMethod()) {
1185 // We should warn if a local variable hides an ivar.
1186 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1187 ObjCInterfaceDecl *ClassDeclared;
1188 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1189 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1190 IFace == ClassDeclared)
1191 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1192 }
1193 }
1194
1195 // Needed to implement property "super.method" notation.
1196 if (Lookup.empty() && II->isStr("super")) {
1197 QualType T;
1198
1199 if (getCurMethodDecl()->isInstanceMethod())
1200 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
1201 getCurMethodDecl()->getClassInterface()));
1202 else
1203 T = Context.getObjCClassType();
1204 return Owned(new (Context) ObjCSuperExpr(Loc, T));
1205 }
1206
1207 // Sentinel value saying that we didn't do anything special.
1208 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001209}
John McCalld14a8642009-11-21 08:51:07 +00001210
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001211/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001212bool
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001213Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
1214 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump11289f42009-09-09 15:08:12 +00001215 if (CXXRecordDecl *RD =
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001216 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump11289f42009-09-09 15:08:12 +00001217 QualType DestType =
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001218 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001219 if (DestType->isDependentType() || From->getType()->isDependentType())
1220 return false;
1221 QualType FromRecordType = From->getType();
1222 QualType DestRecordType = DestType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001223 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001224 DestType = Context.getPointerType(DestType);
1225 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001226 }
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001227 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
1228 CheckDerivedToBaseConversion(FromRecordType,
1229 DestRecordType,
1230 From->getSourceRange().getBegin(),
1231 From->getSourceRange()))
1232 return true;
Anders Carlssona076d142009-07-31 01:23:52 +00001233 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
1234 /*isLvalue=*/true);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001235 }
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001236 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001237}
Douglas Gregor3256d042009-06-30 15:47:41 +00001238
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001239/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00001240static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00001241 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalle66edc12009-11-24 19:00:30 +00001242 SourceLocation Loc, QualType Ty,
1243 const TemplateArgumentListInfo *TemplateArgs = 0) {
1244 NestedNameSpecifier *Qualifier = 0;
1245 SourceRange QualifierRange;
John McCall10eae182009-11-30 22:42:35 +00001246 if (SS.isSet()) {
1247 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1248 QualifierRange = SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001249 }
Mike Stump11289f42009-09-09 15:08:12 +00001250
John McCalle66edc12009-11-24 19:00:30 +00001251 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
1252 Member, Loc, TemplateArgs, Ty);
Douglas Gregorc1905232009-08-26 22:36:53 +00001253}
1254
John McCall2d74de92009-12-01 22:10:20 +00001255/// Builds an implicit member access expression. The current context
1256/// is known to be an instance method, and the given unqualified lookup
1257/// set is known to contain only instance members, at least one of which
1258/// is from an appropriate type.
John McCallb53bbd42009-11-22 01:44:31 +00001259Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00001260Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1261 LookupResult &R,
1262 const TemplateArgumentListInfo *TemplateArgs,
1263 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00001264 assert(!R.empty() && !R.isAmbiguous());
1265
John McCalld14a8642009-11-21 08:51:07 +00001266 SourceLocation Loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00001267
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001268 // We may have found a field within an anonymous union or struct
1269 // (C++ [class.union]).
Douglas Gregor6493d9c2009-10-22 07:08:30 +00001270 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCalle66edc12009-11-24 19:00:30 +00001271 // FIXME: template-ids inside anonymous structs?
John McCall10eae182009-11-30 22:42:35 +00001272 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001273 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCallb53bbd42009-11-22 01:44:31 +00001274 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001275
John McCall2d74de92009-12-01 22:10:20 +00001276 // If this is known to be an instance access, go ahead and build a
1277 // 'this' expression now.
1278 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
1279 Expr *This = 0; // null signifies implicit access
1280 if (IsKnownInstance) {
1281 This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00001282 }
1283
John McCall2d74de92009-12-01 22:10:20 +00001284 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1285 /*OpLoc*/ SourceLocation(),
1286 /*IsArrow*/ true,
1287 SS, R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00001288}
1289
John McCalle66edc12009-11-24 19:00:30 +00001290bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001291 const LookupResult &R,
1292 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00001293 // Only when used directly as the postfix-expression of a call.
1294 if (!HasTrailingLParen)
1295 return false;
1296
1297 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00001298 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00001299 return false;
1300
1301 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00001302 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00001303 return false;
1304
1305 // Turn off ADL when we find certain kinds of declarations during
1306 // normal lookup:
1307 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1308 NamedDecl *D = *I;
1309
1310 // C++0x [basic.lookup.argdep]p3:
1311 // -- a declaration of a class member
1312 // Since using decls preserve this property, we check this on the
1313 // original decl.
John McCall5af04502009-12-02 20:26:00 +00001314 if (IsClassMember(D))
John McCalld14a8642009-11-21 08:51:07 +00001315 return false;
1316
1317 // C++0x [basic.lookup.argdep]p3:
1318 // -- a block-scope function declaration that is not a
1319 // using-declaration
1320 // NOTE: we also trigger this for function templates (in fact, we
1321 // don't check the decl type at all, since all other decl types
1322 // turn off ADL anyway).
1323 if (isa<UsingShadowDecl>(D))
1324 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1325 else if (D->getDeclContext()->isFunctionOrMethod())
1326 return false;
1327
1328 // C++0x [basic.lookup.argdep]p3:
1329 // -- a declaration that is neither a function or a function
1330 // template
1331 // And also for builtin functions.
1332 if (isa<FunctionDecl>(D)) {
1333 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1334
1335 // But also builtin functions.
1336 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1337 return false;
1338 } else if (!isa<FunctionTemplateDecl>(D))
1339 return false;
1340 }
1341
1342 return true;
1343}
1344
1345
John McCalld14a8642009-11-21 08:51:07 +00001346/// Diagnoses obvious problems with the use of the given declaration
1347/// as an expression. This is only actually called for lookups that
1348/// were not overloaded, and it doesn't promise that the declaration
1349/// will in fact be used.
1350static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1351 if (isa<TypedefDecl>(D)) {
1352 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1353 return true;
1354 }
1355
1356 if (isa<ObjCInterfaceDecl>(D)) {
1357 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1358 return true;
1359 }
1360
1361 if (isa<NamespaceDecl>(D)) {
1362 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1363 return true;
1364 }
1365
1366 return false;
1367}
1368
1369Sema::OwningExprResult
John McCalle66edc12009-11-24 19:00:30 +00001370Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001371 LookupResult &R,
1372 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00001373 // If this is a single, fully-resolved result and we don't need ADL,
1374 // just build an ordinary singleton decl ref.
1375 if (!NeedsADL && R.isSingleResult())
John McCallb53bbd42009-11-22 01:44:31 +00001376 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00001377
1378 // We only need to check the declaration if there's exactly one
1379 // result, because in the overloaded case the results can only be
1380 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00001381 if (R.isSingleResult() &&
1382 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00001383 return ExprError();
1384
John McCalle66edc12009-11-24 19:00:30 +00001385 bool Dependent
1386 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCalld14a8642009-11-21 08:51:07 +00001387 UnresolvedLookupExpr *ULE
John McCalle66edc12009-11-24 19:00:30 +00001388 = UnresolvedLookupExpr::Create(Context, Dependent,
1389 (NestedNameSpecifier*) SS.getScopeRep(),
1390 SS.getRange(),
John McCallb53bbd42009-11-22 01:44:31 +00001391 R.getLookupName(), R.getNameLoc(),
1392 NeedsADL, R.isOverloadedResult());
1393 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1394 ULE->addDecl(*I);
John McCalld14a8642009-11-21 08:51:07 +00001395
1396 return Owned(ULE);
1397}
1398
1399
1400/// \brief Complete semantic analysis for a reference to the given declaration.
1401Sema::OwningExprResult
John McCalle66edc12009-11-24 19:00:30 +00001402Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCalld14a8642009-11-21 08:51:07 +00001403 SourceLocation Loc, NamedDecl *D) {
1404 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00001405 assert(!isa<FunctionTemplateDecl>(D) &&
1406 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00001407 DeclarationName Name = D->getDeclName();
1408
1409 if (CheckDeclInExpr(*this, Loc, D))
1410 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00001411
Douglas Gregore7488b92009-12-01 16:58:18 +00001412 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1413 // Specifically diagnose references to class templates that are missing
1414 // a template argument list.
1415 Diag(Loc, diag::err_template_decl_ref)
1416 << Template << SS.getRange();
1417 Diag(Template->getLocation(), diag::note_template_decl_here);
1418 return ExprError();
1419 }
1420
1421 // Make sure that we're referring to a value.
1422 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1423 if (!VD) {
1424 Diag(Loc, diag::err_ref_non_value)
1425 << D << SS.getRange();
1426 Diag(D->getLocation(), diag::note_previous_decl);
1427 return ExprError();
1428 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001429
Douglas Gregor171c45a2009-02-18 21:56:37 +00001430 // Check whether this declaration can be used. Note that we suppress
1431 // this check when we're going to perform argument-dependent lookup
1432 // on this function name, because this might not be the function
1433 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00001434 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00001435 return ExprError();
1436
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001437 // Only create DeclRefExpr's for valid Decl's.
1438 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001439 return ExprError();
1440
Chris Lattner2a9d9892008-10-20 05:16:36 +00001441 // If the identifier reference is inside a block, and it refers to a value
1442 // that is outside the block, create a BlockDeclRefExpr instead of a
1443 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1444 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001445 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00001446 // We do not do this for things like enum constants, global variables, etc,
1447 // as they do not get snapshotted.
1448 //
1449 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001450 MarkDeclarationReferenced(Loc, VD);
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001451 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001452 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001453 if (VD->getAttr<BlocksAttr>())
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001454 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001455 // This is to record that a 'const' was actually synthesize and added.
1456 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001457 // Variable will be bound by-copy, make it const within the closure.
Mike Stump11289f42009-09-09 15:08:12 +00001458
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001459 ExprTy.addConst();
Mike Stump11289f42009-09-09 15:08:12 +00001460 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001461 constAdded));
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001462 }
1463 // If this reference is not in a block or if the referenced variable is
1464 // within the block, create a normal DeclRefExpr.
Douglas Gregor4619e432008-12-05 23:32:09 +00001465
John McCalle66edc12009-11-24 19:00:30 +00001466 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
Chris Lattner17ed4872006-11-20 04:58:19 +00001467}
Chris Lattnere168f762006-11-10 05:29:30 +00001468
Sebastian Redlffbcf962009-01-18 18:53:16 +00001469Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1470 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00001471 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001472
Chris Lattnere168f762006-11-10 05:29:30 +00001473 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00001474 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00001475 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1476 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1477 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00001478 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00001479
Chris Lattnera81a0272008-01-12 08:14:25 +00001480 // Pre-defined identifiers are of type char[x], where x is the length of the
1481 // string.
Mike Stump11289f42009-09-09 15:08:12 +00001482
Anders Carlsson2fb08242009-09-08 18:24:21 +00001483 Decl *currentDecl = getCurFunctionOrMethodDecl();
1484 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001485 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00001486 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001487 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001488
Anders Carlsson0b209a82009-09-11 01:22:35 +00001489 QualType ResTy;
1490 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1491 ResTy = Context.DependentTy;
1492 } else {
1493 unsigned Length =
1494 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001495
Anders Carlsson0b209a82009-09-11 01:22:35 +00001496 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00001497 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00001498 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1499 }
Steve Narofff6009ed2009-01-21 00:14:39 +00001500 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00001501}
1502
Sebastian Redlffbcf962009-01-18 18:53:16 +00001503Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001504 llvm::SmallString<16> CharBuffer;
Steve Naroffae4143e2007-04-26 20:39:23 +00001505 CharBuffer.resize(Tok.getLength());
1506 const char *ThisTokBegin = &CharBuffer[0];
1507 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001508
Steve Naroffae4143e2007-04-26 20:39:23 +00001509 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1510 Tok.getLocation(), PP);
1511 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001512 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00001513
1514 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1515
Sebastian Redl20614a72009-01-20 22:23:13 +00001516 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1517 Literal.isWide(),
1518 type, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00001519}
1520
Sebastian Redlffbcf962009-01-18 18:53:16 +00001521Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1522 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00001523 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1524 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00001525 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00001526 unsigned IntSize = Context.Target.getIntWidth();
Steve Narofff6009ed2009-01-21 00:14:39 +00001527 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00001528 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00001529 }
Ted Kremeneke9814182009-01-13 23:19:12 +00001530
Chris Lattner23b7eb62007-06-15 23:05:46 +00001531 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00001532 // Add padding so that NumericLiteralParser can overread by one character.
1533 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00001534 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00001535
Chris Lattner67ca9252007-05-21 01:08:44 +00001536 // Get the spelling of the token, which eliminates trigraphs, etc.
Steve Naroff8160ea22007-03-06 01:09:46 +00001537 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001538
Mike Stump11289f42009-09-09 15:08:12 +00001539 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00001540 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00001541 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001542 return ExprError();
1543
Chris Lattner1c20a172007-08-26 03:42:43 +00001544 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001545
Chris Lattner1c20a172007-08-26 03:42:43 +00001546 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001547 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001548 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001549 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001550 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001551 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001552 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00001553 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001554
1555 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1556
Ted Kremenek3a2c9502007-11-29 00:56:49 +00001557 // isExact will be set by GetFloatValue().
1558 bool isExact = false;
Chris Lattnere4edb8e2009-06-29 17:34:55 +00001559 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1560 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00001561
Chris Lattner1c20a172007-08-26 03:42:43 +00001562 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00001563 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00001564 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001565 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00001566
Neil Boothac582c52007-08-29 22:00:19 +00001567 // long long is a C99 feature.
1568 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00001569 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00001570 Diag(Tok.getLocation(), diag::ext_longlong);
1571
Chris Lattner67ca9252007-05-21 01:08:44 +00001572 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00001573 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001574
Chris Lattner67ca9252007-05-21 01:08:44 +00001575 if (Literal.GetIntegerValue(ResultVal)) {
1576 // If this value didn't fit into uintmax_t, warn and force to ull.
1577 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001578 Ty = Context.UnsignedLongLongTy;
1579 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00001580 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00001581 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00001582 // If this value fits into a ULL, try to figure out what else it fits into
1583 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001584
Chris Lattner67ca9252007-05-21 01:08:44 +00001585 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1586 // be an unsigned int.
1587 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1588
1589 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00001590 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00001591 if (!Literal.isLong && !Literal.isLongLong) {
1592 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00001593 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001594
Chris Lattner67ca9252007-05-21 01:08:44 +00001595 // Does it fit in a unsigned int?
1596 if (ResultVal.isIntN(IntSize)) {
1597 // Does it fit in a signed int?
1598 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001599 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001600 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001601 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001602 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001603 }
Chris Lattner67ca9252007-05-21 01:08:44 +00001604 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001605
Chris Lattner67ca9252007-05-21 01:08:44 +00001606 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001607 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001608 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001609
Chris Lattner67ca9252007-05-21 01:08:44 +00001610 // Does it fit in a unsigned long?
1611 if (ResultVal.isIntN(LongSize)) {
1612 // Does it fit in a signed long?
1613 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001614 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001615 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001616 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001617 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001618 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001619 }
1620
Chris Lattner67ca9252007-05-21 01:08:44 +00001621 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001622 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001623 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001624
Chris Lattner67ca9252007-05-21 01:08:44 +00001625 // Does it fit in a unsigned long long?
1626 if (ResultVal.isIntN(LongLongSize)) {
1627 // Does it fit in a signed long long?
1628 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001629 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001630 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001631 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001632 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001633 }
1634 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001635
Chris Lattner67ca9252007-05-21 01:08:44 +00001636 // If we still couldn't decide a type, we probably have something that
1637 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001638 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00001639 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001640 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001641 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00001642 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001643
Chris Lattner55258cf2008-05-09 05:59:00 +00001644 if (ResultVal.getBitWidth() != Width)
1645 ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00001646 }
Sebastian Redl20614a72009-01-20 22:23:13 +00001647 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00001648 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001649
Chris Lattner1c20a172007-08-26 03:42:43 +00001650 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1651 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00001652 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00001653 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00001654
1655 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00001656}
1657
Sebastian Redlffbcf962009-01-18 18:53:16 +00001658Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1659 SourceLocation R, ExprArg Val) {
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001660 Expr *E = Val.takeAs<Expr>();
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001661 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00001662 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00001663}
1664
Steve Naroff71b59a92007-06-04 22:22:31 +00001665/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00001666/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001667bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl6f282892008-11-11 17:56:53 +00001668 SourceLocation OpLoc,
1669 const SourceRange &ExprRange,
1670 bool isSizeof) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001671 if (exprType->isDependentType())
1672 return false;
1673
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001674 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1675 // the result is the size of the referenced type."
1676 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1677 // result shall be the alignment of the referenced type."
1678 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
1679 exprType = Ref->getPointeeType();
1680
Steve Naroff043d45d2007-05-15 02:32:35 +00001681 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00001682 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00001683 // alignof(function) is allowed as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001684 if (isSizeof)
1685 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1686 return false;
1687 }
Mike Stump11289f42009-09-09 15:08:12 +00001688
Chris Lattner62975a72009-04-24 00:30:45 +00001689 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001690 if (exprType->isVoidType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001691 Diag(OpLoc, diag::ext_sizeof_void_type)
1692 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00001693 return false;
1694 }
Mike Stump11289f42009-09-09 15:08:12 +00001695
Chris Lattner62975a72009-04-24 00:30:45 +00001696 if (RequireCompleteType(OpLoc, exprType,
Mike Stump11289f42009-09-09 15:08:12 +00001697 isSizeof ? diag::err_sizeof_incomplete_type :
Anders Carlssond624e162009-08-26 23:45:07 +00001698 PDiag(diag::err_alignof_incomplete_type)
1699 << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00001700 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001701
Chris Lattner62975a72009-04-24 00:30:45 +00001702 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanian1dcb3222009-04-24 17:34:33 +00001703 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00001704 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnercd2a8c52009-04-24 22:30:50 +00001705 << exprType << isSizeof << ExprRange;
1706 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00001707 }
Mike Stump11289f42009-09-09 15:08:12 +00001708
Chris Lattner62975a72009-04-24 00:30:45 +00001709 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00001710}
1711
Chris Lattner8dff0172009-01-24 20:17:12 +00001712bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1713 const SourceRange &ExprRange) {
1714 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001715
Mike Stump11289f42009-09-09 15:08:12 +00001716 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00001717 if (isa<DeclRefExpr>(E))
1718 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001719
1720 // Cannot know anything else if the expression is dependent.
1721 if (E->isTypeDependent())
1722 return false;
1723
Douglas Gregor71235ec2009-05-02 02:18:30 +00001724 if (E->getBitField()) {
1725 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1726 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00001727 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00001728
1729 // Alignment of a field access is always okay, so long as it isn't a
1730 // bit-field.
1731 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00001732 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00001733 return false;
1734
Chris Lattner8dff0172009-01-24 20:17:12 +00001735 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1736}
1737
Douglas Gregor0950e412009-03-13 21:01:28 +00001738/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump11289f42009-09-09 15:08:12 +00001739Action::OwningExprResult
John McCallbcd03502009-12-07 02:54:59 +00001740Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall4c98fd82009-11-04 07:28:41 +00001741 SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001742 bool isSizeOf, SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00001743 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00001744 return ExprError();
1745
John McCallbcd03502009-12-07 02:54:59 +00001746 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00001747
Douglas Gregor0950e412009-03-13 21:01:28 +00001748 if (!T->isDependentType() &&
1749 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1750 return ExprError();
1751
1752 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCallbcd03502009-12-07 02:54:59 +00001753 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregor0950e412009-03-13 21:01:28 +00001754 Context.getSizeType(), OpLoc,
1755 R.getEnd()));
1756}
1757
1758/// \brief Build a sizeof or alignof expression given an expression
1759/// operand.
Mike Stump11289f42009-09-09 15:08:12 +00001760Action::OwningExprResult
1761Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001762 bool isSizeOf, SourceRange R) {
1763 // Verify that the operand is valid.
1764 bool isInvalid = false;
1765 if (E->isTypeDependent()) {
1766 // Delay type-checking for type-dependent expressions.
1767 } else if (!isSizeOf) {
1768 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00001769 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00001770 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1771 isInvalid = true;
1772 } else {
1773 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1774 }
1775
1776 if (isInvalid)
1777 return ExprError();
1778
1779 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1780 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1781 Context.getSizeType(), OpLoc,
1782 R.getEnd()));
1783}
1784
Sebastian Redl6f282892008-11-11 17:56:53 +00001785/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1786/// the same for @c alignof and @c __alignof
1787/// Note that the ArgRange is invalid if isType is false.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001788Action::OwningExprResult
Sebastian Redl6f282892008-11-11 17:56:53 +00001789Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1790 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00001791 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001792 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00001793
Sebastian Redl6f282892008-11-11 17:56:53 +00001794 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00001795 TypeSourceInfo *TInfo;
1796 (void) GetTypeFromParser(TyOrEx, &TInfo);
1797 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00001798 }
Sebastian Redl6f282892008-11-11 17:56:53 +00001799
Douglas Gregor0950e412009-03-13 21:01:28 +00001800 Expr *ArgEx = (Expr *)TyOrEx;
1801 Action::OwningExprResult Result
1802 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1803
1804 if (Result.isInvalid())
1805 DeleteExpr(ArgEx);
1806
1807 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00001808}
1809
Chris Lattner709322b2009-02-17 08:12:06 +00001810QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001811 if (V->isTypeDependent())
1812 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00001813
Chris Lattnere267f5d2007-08-26 05:39:26 +00001814 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00001815 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00001816 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00001817
Chris Lattnere267f5d2007-08-26 05:39:26 +00001818 // Otherwise they pass through real integer and floating point types here.
1819 if (V->getType()->isArithmeticType())
1820 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001821
Chris Lattnere267f5d2007-08-26 05:39:26 +00001822 // Reject anything else.
Chris Lattner709322b2009-02-17 08:12:06 +00001823 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1824 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00001825 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00001826}
1827
1828
Chris Lattnere168f762006-11-10 05:29:30 +00001829
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001830Action::OwningExprResult
1831Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1832 tok::TokenKind Kind, ExprArg Input) {
Chris Lattnere168f762006-11-10 05:29:30 +00001833 UnaryOperator::Opcode Opc;
1834 switch (Kind) {
1835 default: assert(0 && "Unknown unary op!");
1836 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1837 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1838 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001839
Eli Friedmancfdd40c2009-11-18 03:38:04 +00001840 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Chris Lattnere168f762006-11-10 05:29:30 +00001841}
1842
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001843Action::OwningExprResult
1844Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1845 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00001846 // Since this might be a postfix expression, get rid of ParenListExprs.
1847 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1848
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001849 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1850 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump11289f42009-09-09 15:08:12 +00001851
Douglas Gregor40412ac2008-11-19 17:17:41 +00001852 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00001853 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1854 Base.release();
1855 Idx.release();
1856 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1857 Context.DependentTy, RLoc));
1858 }
1859
Mike Stump11289f42009-09-09 15:08:12 +00001860 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001861 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00001862 LHSExp->getType()->isEnumeralType() ||
1863 RHSExp->getType()->isRecordType() ||
1864 RHSExp->getType()->isEnumeralType())) {
Sebastian Redladba46e2009-10-29 20:17:01 +00001865 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor40412ac2008-11-19 17:17:41 +00001866 }
1867
Sebastian Redladba46e2009-10-29 20:17:01 +00001868 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
1869}
1870
1871
1872Action::OwningExprResult
1873Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
1874 ExprArg Idx, SourceLocation RLoc) {
1875 Expr *LHSExp = static_cast<Expr*>(Base.get());
1876 Expr *RHSExp = static_cast<Expr*>(Idx.get());
1877
Chris Lattner36d572b2007-07-16 00:14:47 +00001878 // Perform default conversions.
1879 DefaultFunctionArrayConversion(LHSExp);
1880 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001881
Chris Lattner36d572b2007-07-16 00:14:47 +00001882 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Steve Narofff1e53692007-03-23 22:27:02 +00001883
Steve Naroffc1aadb12007-03-28 21:49:40 +00001884 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00001885 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00001886 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00001887 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00001888 Expr *BaseExpr, *IndexExpr;
1889 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001890 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1891 BaseExpr = LHSExp;
1892 IndexExpr = RHSExp;
1893 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001894 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00001895 BaseExpr = LHSExp;
1896 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00001897 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001898 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00001899 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00001900 BaseExpr = RHSExp;
1901 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00001902 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00001903 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00001904 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001905 BaseExpr = LHSExp;
1906 IndexExpr = RHSExp;
1907 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00001908 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00001909 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001910 // Handle the uncommon case of "123[Ptr]".
1911 BaseExpr = RHSExp;
1912 IndexExpr = LHSExp;
1913 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00001914 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00001915 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00001916 IndexExpr = RHSExp;
Nate Begemanc1bf0612009-01-18 00:45:31 +00001917
Chris Lattner36d572b2007-07-16 00:14:47 +00001918 // FIXME: need to deal with const...
1919 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00001920 } else if (LHSTy->isArrayType()) {
1921 // If we see an array that wasn't promoted by
1922 // DefaultFunctionArrayConversion, it must be an array that
1923 // wasn't promoted because of the C90 rule that doesn't
1924 // allow promoting non-lvalue arrays. Warn, then
1925 // force the promotion here.
1926 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1927 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00001928 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
1929 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00001930 LHSTy = LHSExp->getType();
1931
1932 BaseExpr = LHSExp;
1933 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001934 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00001935 } else if (RHSTy->isArrayType()) {
1936 // Same as previous, except for 123[f().a] case
1937 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1938 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00001939 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
1940 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00001941 RHSTy = RHSExp->getType();
1942
1943 BaseExpr = RHSExp;
1944 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001945 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00001946 } else {
Chris Lattner003af242009-04-25 22:50:55 +00001947 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1948 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001949 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00001950 // C99 6.5.2.1p1
Nate Begeman5ec4b312009-08-10 23:49:36 +00001951 if (!(IndexExpr->getType()->isIntegerType() &&
1952 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00001953 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1954 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00001955
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00001956 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00001957 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
1958 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00001959 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
1960
Douglas Gregorac1fb652009-03-24 19:52:54 +00001961 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00001962 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1963 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00001964 // incomplete types are not object types.
1965 if (ResultType->isFunctionType()) {
1966 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1967 << ResultType << BaseExpr->getSourceRange();
1968 return ExprError();
1969 }
Mike Stump11289f42009-09-09 15:08:12 +00001970
Douglas Gregorac1fb652009-03-24 19:52:54 +00001971 if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00001972 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00001973 PDiag(diag::err_subscript_incomplete_type)
1974 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00001975 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001976
Chris Lattner62975a72009-04-24 00:30:45 +00001977 // Diagnose bad cases where we step over interface counts.
1978 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1979 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1980 << ResultType << BaseExpr->getSourceRange();
1981 return ExprError();
1982 }
Mike Stump11289f42009-09-09 15:08:12 +00001983
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001984 Base.release();
1985 Idx.release();
Mike Stump4e1f26a2009-02-19 03:04:26 +00001986 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Narofff6009ed2009-01-21 00:14:39 +00001987 ResultType, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00001988}
1989
Steve Narofff8fd09e2007-07-27 22:15:19 +00001990QualType Sema::
Nate Begemance4d7fc2008-04-18 23:10:10 +00001991CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001992 const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00001993 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00001994 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
1995 // see FIXME there.
1996 //
1997 // FIXME: This logic can be greatly simplified by splitting it along
1998 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00001999 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00002000
Steve Narofff8fd09e2007-07-27 22:15:19 +00002001 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002002 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002003
Mike Stump4e1f26a2009-02-19 03:04:26 +00002004 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00002005 // special names that indicate a subset of exactly half the elements are
2006 // to be selected.
2007 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00002008
Nate Begemanbb70bf62009-01-18 01:47:54 +00002009 // This flag determines whether or not CompName has an 's' char prefix,
2010 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00002011 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00002012
2013 // Check that we've found one of the special components, or that the component
2014 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002015 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00002016 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2017 HalvingSwizzle = true;
Nate Begemanf322eab2008-05-09 06:41:27 +00002018 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00002019 do
2020 compStr++;
2021 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begemanbb70bf62009-01-18 01:47:54 +00002022 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00002023 do
2024 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002025 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner7e152db2007-08-02 22:33:49 +00002026 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00002027
Mike Stump4e1f26a2009-02-19 03:04:26 +00002028 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00002029 // We didn't get to the end of the string. This means the component names
2030 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner3b054132008-11-19 05:08:23 +00002031 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2032 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00002033 return QualType();
2034 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002035
Nate Begemanbb70bf62009-01-18 01:47:54 +00002036 // Ensure no component accessor exceeds the width of the vector type it
2037 // operates on.
2038 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002039 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002040
2041 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00002042 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002043
2044 while (*compStr) {
2045 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2046 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2047 << baseType << SourceRange(CompLoc);
2048 return QualType();
2049 }
2050 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00002051 }
Nate Begemanf322eab2008-05-09 06:41:27 +00002052
Nate Begemanbb70bf62009-01-18 01:47:54 +00002053 // If this is a halving swizzle, verify that the base type has an even
2054 // number of elements.
2055 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner3b054132008-11-19 05:08:23 +00002056 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002057 << baseType << SourceRange(CompLoc);
Nate Begemanf322eab2008-05-09 06:41:27 +00002058 return QualType();
2059 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002060
Steve Narofff8fd09e2007-07-27 22:15:19 +00002061 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002062 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00002063 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00002064 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00002065 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanbb70bf62009-01-18 01:47:54 +00002066 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00002067 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002068 if (HexSwizzle)
2069 CompSize--;
2070
Steve Narofff8fd09e2007-07-27 22:15:19 +00002071 if (CompSize == 1)
2072 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002073
Nate Begemance4d7fc2008-04-18 23:10:10 +00002074 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00002075 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00002076 // diagostics look bad. We want extended vector types to appear built-in.
2077 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2078 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2079 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00002080 }
2081 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00002082}
2083
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002084static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00002085 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002086 const Selector &Sel,
2087 ASTContext &Context) {
Mike Stump11289f42009-09-09 15:08:12 +00002088
Anders Carlssonf571c112009-08-26 18:25:21 +00002089 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002090 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002091 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002092 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00002093
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002094 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2095 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00002096 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002097 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002098 return D;
2099 }
2100 return 0;
2101}
2102
Steve Narofffb4330f2009-06-17 22:40:22 +00002103static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlssonf571c112009-08-26 18:25:21 +00002104 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002105 const Selector &Sel,
2106 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002107 // Check protocols on qualified interfaces.
2108 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00002109 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002110 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002111 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002112 GDecl = PD;
2113 break;
2114 }
2115 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002116 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002117 GDecl = OMD;
2118 break;
2119 }
2120 }
2121 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00002122 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002123 E = QIdTy->qual_end(); I != E; ++I) {
2124 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002125 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002126 if (GDecl)
2127 return GDecl;
2128 }
2129 }
2130 return GDecl;
2131}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00002132
John McCall10eae182009-11-30 22:42:35 +00002133Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002134Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2135 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002136 const CXXScopeSpec &SS,
2137 NamedDecl *FirstQualifierInScope,
2138 DeclarationName Name, SourceLocation NameLoc,
2139 const TemplateArgumentListInfo *TemplateArgs) {
2140 Expr *BaseExpr = Base.takeAs<Expr>();
2141
2142 // Even in dependent contexts, try to diagnose base expressions with
2143 // obviously wrong types, e.g.:
2144 //
2145 // T* t;
2146 // t.f;
2147 //
2148 // In Obj-C++, however, the above expression is valid, since it could be
2149 // accessing the 'f' property if T is an Obj-C interface. The extra check
2150 // allows this, while still reporting an error if T is a struct pointer.
2151 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00002152 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00002153 if (PT && (!getLangOptions().ObjC1 ||
2154 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00002155 assert(BaseExpr && "cannot happen with implicit member accesses");
John McCall10eae182009-11-30 22:42:35 +00002156 Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00002157 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00002158 return ExprError();
2159 }
2160 }
2161
John McCall2d74de92009-12-01 22:10:20 +00002162 assert(BaseType->isDependentType());
John McCall10eae182009-11-30 22:42:35 +00002163
2164 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2165 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00002166 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00002167 IsArrow, OpLoc,
2168 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2169 SS.getRange(),
2170 FirstQualifierInScope,
2171 Name, NameLoc,
2172 TemplateArgs));
2173}
2174
2175/// We know that the given qualified member reference points only to
2176/// declarations which do not belong to the static type of the base
2177/// expression. Diagnose the problem.
2178static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2179 Expr *BaseExpr,
2180 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00002181 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002182 const LookupResult &R) {
John McCallcd4b4772009-12-02 03:53:29 +00002183 // If this is an implicit member access, use a different set of
2184 // diagnostics.
2185 if (!BaseExpr)
2186 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall10eae182009-11-30 22:42:35 +00002187
2188 // FIXME: this is an exceedingly lame diagnostic for some of the more
2189 // complicated cases here.
John McCallcd4b4772009-12-02 03:53:29 +00002190 DeclContext *DC = R.getRepresentativeDecl()->getDeclContext();
John McCall10eae182009-11-30 22:42:35 +00002191 SemaRef.Diag(R.getNameLoc(), diag::err_not_direct_base_or_virtual)
John McCallcd4b4772009-12-02 03:53:29 +00002192 << SS.getRange() << DC << BaseType;
John McCall10eae182009-11-30 22:42:35 +00002193}
2194
2195// Check whether the declarations we found through a nested-name
2196// specifier in a member expression are actually members of the base
2197// type. The restriction here is:
2198//
2199// C++ [expr.ref]p2:
2200// ... In these cases, the id-expression shall name a
2201// member of the class or of one of its base classes.
2202//
2203// So it's perfectly legitimate for the nested-name specifier to name
2204// an unrelated class, and for us to find an overload set including
2205// decls from classes which are not superclasses, as long as the decl
2206// we actually pick through overload resolution is from a superclass.
2207bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2208 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00002209 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002210 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00002211 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2212 if (!BaseRT) {
2213 // We can't check this yet because the base type is still
2214 // dependent.
2215 assert(BaseType->isDependentType());
2216 return false;
2217 }
2218 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00002219
2220 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00002221 // If this is an implicit member reference and we find a
2222 // non-instance member, it's not an error.
2223 if (!BaseExpr && !IsInstanceMember((*I)->getUnderlyingDecl()))
2224 return false;
John McCall10eae182009-11-30 22:42:35 +00002225
John McCall2d74de92009-12-01 22:10:20 +00002226 // Note that we use the DC of the decl, not the underlying decl.
2227 CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
2228 while (RecordD->isAnonymousStructOrUnion())
2229 RecordD = cast<CXXRecordDecl>(RecordD->getParent());
2230
2231 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
2232 MemberRecord.insert(RecordD->getCanonicalDecl());
2233
2234 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2235 return false;
2236 }
2237
John McCallcd4b4772009-12-02 03:53:29 +00002238 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCall2d74de92009-12-01 22:10:20 +00002239 return true;
2240}
2241
2242static bool
2243LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2244 SourceRange BaseRange, const RecordType *RTy,
2245 SourceLocation OpLoc, const CXXScopeSpec &SS) {
2246 RecordDecl *RDecl = RTy->getDecl();
2247 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
2248 PDiag(diag::err_typecheck_incomplete_tag)
2249 << BaseRange))
2250 return true;
2251
2252 DeclContext *DC = RDecl;
2253 if (SS.isSet()) {
2254 // If the member name was a qualified-id, look into the
2255 // nested-name-specifier.
2256 DC = SemaRef.computeDeclContext(SS, false);
2257
John McCallcd4b4772009-12-02 03:53:29 +00002258 if (SemaRef.RequireCompleteDeclContext(SS)) {
2259 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2260 << SS.getRange() << DC;
2261 return true;
2262 }
2263
John McCall2d74de92009-12-01 22:10:20 +00002264 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2265
2266 if (!isa<TypeDecl>(DC)) {
2267 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2268 << DC << SS.getRange();
2269 return true;
John McCall10eae182009-11-30 22:42:35 +00002270 }
2271 }
2272
John McCall2d74de92009-12-01 22:10:20 +00002273 // The record definition is complete, now look up the member.
2274 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00002275
2276 return false;
2277}
2278
2279Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002280Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00002281 SourceLocation OpLoc, bool IsArrow,
2282 const CXXScopeSpec &SS,
2283 NamedDecl *FirstQualifierInScope,
2284 DeclarationName Name, SourceLocation NameLoc,
2285 const TemplateArgumentListInfo *TemplateArgs) {
2286 Expr *Base = BaseArg.takeAs<Expr>();
2287
John McCallcd4b4772009-12-02 03:53:29 +00002288 if (BaseType->isDependentType() ||
2289 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCall2d74de92009-12-01 22:10:20 +00002290 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
John McCall10eae182009-11-30 22:42:35 +00002291 IsArrow, OpLoc,
2292 SS, FirstQualifierInScope,
2293 Name, NameLoc,
2294 TemplateArgs);
2295
2296 LookupResult R(*this, Name, NameLoc, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00002297
John McCall2d74de92009-12-01 22:10:20 +00002298 // Implicit member accesses.
2299 if (!Base) {
2300 QualType RecordTy = BaseType;
2301 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2302 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2303 RecordTy->getAs<RecordType>(),
2304 OpLoc, SS))
2305 return ExprError();
2306
2307 // Explicit member accesses.
2308 } else {
2309 OwningExprResult Result =
2310 LookupMemberExpr(R, Base, IsArrow, OpLoc,
2311 SS, FirstQualifierInScope,
2312 /*ObjCImpDecl*/ DeclPtrTy());
2313
2314 if (Result.isInvalid()) {
2315 Owned(Base);
2316 return ExprError();
2317 }
2318
2319 if (Result.get())
2320 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00002321 }
2322
John McCall2d74de92009-12-01 22:10:20 +00002323 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
2324 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002325}
2326
2327Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002328Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2329 SourceLocation OpLoc, bool IsArrow,
2330 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002331 LookupResult &R,
2332 const TemplateArgumentListInfo *TemplateArgs) {
2333 Expr *BaseExpr = Base.takeAs<Expr>();
John McCall2d74de92009-12-01 22:10:20 +00002334 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00002335 if (IsArrow) {
2336 assert(BaseType->isPointerType());
2337 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2338 }
2339
2340 NestedNameSpecifier *Qualifier =
2341 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2342 DeclarationName MemberName = R.getLookupName();
2343 SourceLocation MemberLoc = R.getNameLoc();
2344
2345 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00002346 return ExprError();
2347
John McCall10eae182009-11-30 22:42:35 +00002348 if (R.empty()) {
2349 // Rederive where we looked up.
2350 DeclContext *DC = (SS.isSet()
2351 ? computeDeclContext(SS, false)
2352 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00002353
John McCall10eae182009-11-30 22:42:35 +00002354 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00002355 << MemberName << DC
2356 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00002357 return ExprError();
2358 }
2359
John McCallcd4b4772009-12-02 03:53:29 +00002360 // Diagnose qualified lookups that find only declarations from a
2361 // non-base type. Note that it's okay for lookup to find
2362 // declarations from a non-base type as long as those aren't the
2363 // ones picked by overload resolution.
2364 if (SS.isSet() && CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00002365 return ExprError();
2366
2367 // Construct an unresolved result if we in fact got an unresolved
2368 // result.
2369 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall2d74de92009-12-01 22:10:20 +00002370 bool Dependent =
2371 R.isUnresolvableResult() ||
2372 UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002373
2374 UnresolvedMemberExpr *MemExpr
2375 = UnresolvedMemberExpr::Create(Context, Dependent,
2376 R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00002377 BaseExpr, BaseExprType,
2378 IsArrow, OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002379 Qualifier, SS.getRange(),
2380 MemberName, MemberLoc,
2381 TemplateArgs);
2382 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2383 MemExpr->addDecl(*I);
2384
2385 return Owned(MemExpr);
2386 }
2387
2388 assert(R.isSingleResult());
2389 NamedDecl *MemberDecl = R.getFoundDecl();
2390
2391 // FIXME: diagnose the presence of template arguments now.
2392
2393 // If the decl being referenced had an error, return an error for this
2394 // sub-expr without emitting another error, in order to avoid cascading
2395 // error cases.
2396 if (MemberDecl->isInvalidDecl())
2397 return ExprError();
2398
John McCall2d74de92009-12-01 22:10:20 +00002399 // Handle the implicit-member-access case.
2400 if (!BaseExpr) {
2401 // If this is not an instance member, convert to a non-member access.
2402 if (!IsInstanceMember(MemberDecl))
2403 return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
2404
2405 BaseExpr = new (Context) CXXThisExpr(SourceLocation(), BaseExprType);
2406 }
2407
John McCall10eae182009-11-30 22:42:35 +00002408 bool ShouldCheckUse = true;
2409 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2410 // Don't diagnose the use of a virtual member function unless it's
2411 // explicitly qualified.
2412 if (MD->isVirtual() && !SS.isSet())
2413 ShouldCheckUse = false;
2414 }
2415
2416 // Check the use of this member.
2417 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2418 Owned(BaseExpr);
2419 return ExprError();
2420 }
2421
2422 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2423 // We may have found a field within an anonymous union or struct
2424 // (C++ [class.union]).
Eli Friedman78cde142009-12-04 07:18:51 +00002425 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2426 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
John McCall10eae182009-11-30 22:42:35 +00002427 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2428 BaseExpr, OpLoc);
2429
2430 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2431 QualType MemberType = FD->getType();
2432 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2433 MemberType = Ref->getPointeeType();
2434 else {
2435 Qualifiers BaseQuals = BaseType.getQualifiers();
2436 BaseQuals.removeObjCGCAttr();
2437 if (FD->isMutable()) BaseQuals.removeConst();
2438
2439 Qualifiers MemberQuals
2440 = Context.getCanonicalType(MemberType).getQualifiers();
2441
2442 Qualifiers Combined = BaseQuals + MemberQuals;
2443 if (Combined != MemberQuals)
2444 MemberType = Context.getQualifiedType(MemberType, Combined);
2445 }
2446
2447 MarkDeclarationReferenced(MemberLoc, FD);
2448 if (PerformObjectMemberConversion(BaseExpr, FD))
2449 return ExprError();
2450 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2451 FD, MemberLoc, MemberType));
2452 }
2453
2454 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2455 MarkDeclarationReferenced(MemberLoc, Var);
2456 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2457 Var, MemberLoc,
2458 Var->getType().getNonReferenceType()));
2459 }
2460
2461 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2462 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2463 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2464 MemberFn, MemberLoc,
2465 MemberFn->getType()));
2466 }
2467
2468 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2469 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2470 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2471 Enum, MemberLoc, Enum->getType()));
2472 }
2473
2474 Owned(BaseExpr);
2475
2476 if (isa<TypeDecl>(MemberDecl))
2477 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2478 << MemberName << int(IsArrow));
2479
2480 // We found a declaration kind that we didn't expect. This is a
2481 // generic error message that tells the user that she can't refer
2482 // to this member with '.' or '->'.
2483 return ExprError(Diag(MemberLoc,
2484 diag::err_typecheck_member_reference_unknown)
2485 << MemberName << int(IsArrow));
2486}
2487
2488/// Look up the given member of the given non-type-dependent
2489/// expression. This can return in one of two ways:
2490/// * If it returns a sentinel null-but-valid result, the caller will
2491/// assume that lookup was performed and the results written into
2492/// the provided structure. It will take over from there.
2493/// * Otherwise, the returned expression will be produced in place of
2494/// an ordinary member expression.
2495///
2496/// The ObjCImpDecl bit is a gross hack that will need to be properly
2497/// fixed for ObjC++.
2498Sema::OwningExprResult
2499Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00002500 bool &IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002501 const CXXScopeSpec &SS,
2502 NamedDecl *FirstQualifierInScope,
2503 DeclPtrTy ObjCImpDecl) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00002504 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00002505
Steve Naroffeaaae462007-12-16 21:42:28 +00002506 // Perform default conversions.
2507 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002508
Steve Naroff185616f2007-07-26 03:11:44 +00002509 QualType BaseType = BaseExpr->getType();
John McCall10eae182009-11-30 22:42:35 +00002510 assert(!BaseType->isDependentType());
2511
2512 DeclarationName MemberName = R.getLookupName();
2513 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00002514
2515 // If the user is trying to apply -> or . to a function pointer
John McCall10eae182009-11-30 22:42:35 +00002516 // type, it's probably because they forgot parentheses to call that
Douglas Gregord82ae382009-11-06 06:30:47 +00002517 // function. Suggest the addition of those parentheses, build the
2518 // call, and continue on.
2519 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2520 if (const FunctionProtoType *Fun
2521 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2522 QualType ResultTy = Fun->getResultType();
2523 if (Fun->getNumArgs() == 0 &&
John McCall10eae182009-11-30 22:42:35 +00002524 ((!IsArrow && ResultTy->isRecordType()) ||
2525 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregord82ae382009-11-06 06:30:47 +00002526 ResultTy->getAs<PointerType>()->getPointeeType()
2527 ->isRecordType()))) {
2528 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2529 Diag(Loc, diag::err_member_reference_needs_call)
2530 << QualType(Fun, 0)
2531 << CodeModificationHint::CreateInsertion(Loc, "()");
2532
2533 OwningExprResult NewBase
John McCall10eae182009-11-30 22:42:35 +00002534 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
Douglas Gregord82ae382009-11-06 06:30:47 +00002535 MultiExprArg(*this, 0, 0), 0, Loc);
2536 if (NewBase.isInvalid())
John McCall10eae182009-11-30 22:42:35 +00002537 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00002538
2539 BaseExpr = NewBase.takeAs<Expr>();
2540 DefaultFunctionArrayConversion(BaseExpr);
2541 BaseType = BaseExpr->getType();
2542 }
2543 }
2544 }
2545
David Chisnall9f57c292009-08-17 16:35:33 +00002546 // If this is an Objective-C pseudo-builtin and a definition is provided then
2547 // use that.
2548 if (BaseType->isObjCIdType()) {
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00002549 if (IsArrow) {
2550 // Handle the following exceptional case PObj->isa.
2551 if (const ObjCObjectPointerType *OPT =
2552 BaseType->getAs<ObjCObjectPointerType>()) {
2553 if (OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2554 MemberName.getAsIdentifierInfo()->isStr("isa"))
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00002555 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
2556 Context.getObjCClassType()));
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00002557 }
2558 }
David Chisnall9f57c292009-08-17 16:35:33 +00002559 // We have an 'id' type. Rather than fall through, we check if this
2560 // is a reference to 'isa'.
2561 if (BaseType != Context.ObjCIdRedefinitionType) {
2562 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002563 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00002564 }
David Chisnall9f57c292009-08-17 16:35:33 +00002565 }
John McCall10eae182009-11-30 22:42:35 +00002566
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00002567 // If this is an Objective-C pseudo-builtin and a definition is provided then
2568 // use that.
2569 if (Context.isObjCSelType(BaseType)) {
2570 // We have an 'SEL' type. Rather than fall through, we check if this
2571 // is a reference to 'sel_id'.
2572 if (BaseType != Context.ObjCSelRedefinitionType) {
2573 BaseType = Context.ObjCSelRedefinitionType;
2574 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
2575 }
2576 }
John McCall10eae182009-11-30 22:42:35 +00002577
Steve Naroff185616f2007-07-26 03:11:44 +00002578 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002579
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002580 // Handle properties on ObjC 'Class' types.
John McCall10eae182009-11-30 22:42:35 +00002581 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002582 // Also must look for a getter name which uses property syntax.
2583 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2584 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2585 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2586 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2587 ObjCMethodDecl *Getter;
2588 // FIXME: need to also look locally in the implementation.
2589 if ((Getter = IFace->lookupClassMethod(Sel))) {
2590 // Check the use of this method.
2591 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2592 return ExprError();
2593 }
2594 // If we found a getter then this may be a valid dot-reference, we
2595 // will look for the matching setter, in case it is needed.
2596 Selector SetterSel =
2597 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2598 PP.getSelectorTable(), Member);
2599 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2600 if (!Setter) {
2601 // If this reference is in an @implementation, also check for 'private'
2602 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00002603 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002604 }
2605 // Look through local category implementations associated with the class.
2606 if (!Setter)
2607 Setter = IFace->getCategoryClassMethod(SetterSel);
2608
2609 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2610 return ExprError();
2611
2612 if (Getter || Setter) {
2613 QualType PType;
2614
2615 if (Getter)
2616 PType = Getter->getResultType();
2617 else
2618 // Get the expression type from Setter's incoming parameter.
2619 PType = (*(Setter->param_end() -1))->getType();
2620 // FIXME: we must check that the setter has property type.
2621 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
2622 PType,
2623 Setter, MemberLoc, BaseExpr));
2624 }
2625 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2626 << MemberName << BaseType);
2627 }
2628 }
2629
2630 if (BaseType->isObjCClassType() &&
2631 BaseType != Context.ObjCClassRedefinitionType) {
2632 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002633 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002634 }
Mike Stump11289f42009-09-09 15:08:12 +00002635
John McCall10eae182009-11-30 22:42:35 +00002636 if (IsArrow) {
2637 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff185616f2007-07-26 03:11:44 +00002638 BaseType = PT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002639 else if (BaseType->isObjCObjectPointerType())
2640 ;
John McCalla928c652009-12-07 22:46:59 +00002641 else if (BaseType->isRecordType()) {
2642 // Recover from arrow accesses to records, e.g.:
2643 // struct MyRecord foo;
2644 // foo->bar
2645 // This is actually well-formed in C++ if MyRecord has an
2646 // overloaded operator->, but that should have been dealt with
2647 // by now.
2648 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2649 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2650 << CodeModificationHint::CreateReplacement(OpLoc, ".");
2651 IsArrow = false;
2652 } else {
John McCall10eae182009-11-30 22:42:35 +00002653 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
2654 << BaseType << BaseExpr->getSourceRange();
2655 return ExprError();
Anders Carlsson524d5a42009-05-16 20:31:20 +00002656 }
John McCalla928c652009-12-07 22:46:59 +00002657 } else {
2658 // Recover from dot accesses to pointers, e.g.:
2659 // type *foo;
2660 // foo.bar
2661 // This is actually well-formed in two cases:
2662 // - 'type' is an Objective C type
2663 // - 'bar' is a pseudo-destructor name which happens to refer to
2664 // the appropriate pointer type
2665 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
2666 const PointerType *PT = BaseType->getAs<PointerType>();
2667 if (PT && PT->getPointeeType()->isRecordType()) {
2668 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2669 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2670 << CodeModificationHint::CreateReplacement(OpLoc, "->");
2671 BaseType = PT->getPointeeType();
2672 IsArrow = true;
2673 }
2674 }
John McCall10eae182009-11-30 22:42:35 +00002675 }
John McCalla928c652009-12-07 22:46:59 +00002676
John McCall10eae182009-11-30 22:42:35 +00002677 // Handle field access to simple records. This also handles access
2678 // to fields of the ObjC 'id' struct.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002679 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCall2d74de92009-12-01 22:10:20 +00002680 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
2681 RTy, OpLoc, SS))
Douglas Gregordd430f72009-01-19 19:26:10 +00002682 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00002683 return Owned((Expr*) 0);
Chris Lattnerb63a7452008-07-21 04:28:12 +00002684 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002685
Douglas Gregorad8a3362009-09-04 17:36:40 +00002686 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2687 // into a record type was handled above, any destructor we see here is a
2688 // pseudo-destructor.
2689 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2690 // C++ [expr.pseudo]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002691 // The left hand side of the dot operator shall be of scalar type. The
2692 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregorad8a3362009-09-04 17:36:40 +00002693 // type.
2694 if (!BaseType->isScalarType())
2695 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2696 << BaseType << BaseExpr->getSourceRange());
Mike Stump11289f42009-09-09 15:08:12 +00002697
Douglas Gregorad8a3362009-09-04 17:36:40 +00002698 // [...] The type designated by the pseudo-destructor-name shall be the
2699 // same as the object type.
2700 if (!MemberName.getCXXNameType()->isDependentType() &&
2701 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2702 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2703 << BaseType << MemberName.getCXXNameType()
2704 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump11289f42009-09-09 15:08:12 +00002705
2706 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregorad8a3362009-09-04 17:36:40 +00002707 // the form
2708 //
Mike Stump11289f42009-09-09 15:08:12 +00002709 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2710 //
Douglas Gregorad8a3362009-09-04 17:36:40 +00002711 // shall designate the same scalar type.
2712 //
2713 // FIXME: DPG can't see any way to trigger this particular clause, so it
2714 // isn't checked here.
Mike Stump11289f42009-09-09 15:08:12 +00002715
Douglas Gregorad8a3362009-09-04 17:36:40 +00002716 // FIXME: We've lost the precise spelling of the type by going through
2717 // DeclarationName. Can we do better?
2718 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
John McCall10eae182009-11-30 22:42:35 +00002719 IsArrow, OpLoc,
2720 (NestedNameSpecifier *) SS.getScopeRep(),
2721 SS.getRange(),
Douglas Gregorad8a3362009-09-04 17:36:40 +00002722 MemberName.getCXXNameType(),
2723 MemberLoc));
2724 }
Mike Stump11289f42009-09-09 15:08:12 +00002725
Chris Lattnerdc420f42008-07-21 04:59:05 +00002726 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2727 // (*Obj).ivar.
John McCall10eae182009-11-30 22:42:35 +00002728 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
2729 (!IsArrow && BaseType->isObjCInterfaceType())) {
John McCall9dd450b2009-09-21 23:43:11 +00002730 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002731 const ObjCInterfaceType *IFaceT =
John McCall9dd450b2009-09-21 23:43:11 +00002732 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffa057ba92009-07-16 00:25:06 +00002733 if (IFaceT) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002734 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2735
Steve Naroffa057ba92009-07-16 00:25:06 +00002736 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2737 ObjCInterfaceDecl *ClassDeclared;
Anders Carlssonf571c112009-08-26 18:25:21 +00002738 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump11289f42009-09-09 15:08:12 +00002739
Steve Naroffa057ba92009-07-16 00:25:06 +00002740 if (IV) {
2741 // If the decl being referenced had an error, return an error for this
2742 // sub-expr without emitting another error, in order to avoid cascading
2743 // error cases.
2744 if (IV->isInvalidDecl())
2745 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00002746
Steve Naroffa057ba92009-07-16 00:25:06 +00002747 // Check whether we can reference this field.
2748 if (DiagnoseUseOfDecl(IV, MemberLoc))
2749 return ExprError();
2750 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2751 IV->getAccessControl() != ObjCIvarDecl::Package) {
2752 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2753 if (ObjCMethodDecl *MD = getCurMethodDecl())
2754 ClassOfMethodDecl = MD->getClassInterface();
2755 else if (ObjCImpDecl && getCurFunctionDecl()) {
2756 // Case of a c-function declared inside an objc implementation.
2757 // FIXME: For a c-style function nested inside an objc implementation
2758 // class, there is no implementation context available, so we pass
2759 // down the context as argument to this routine. Ideally, this context
2760 // need be passed down in the AST node and somehow calculated from the
2761 // AST for a function decl.
2762 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump11289f42009-09-09 15:08:12 +00002763 if (ObjCImplementationDecl *IMPD =
Steve Naroffa057ba92009-07-16 00:25:06 +00002764 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2765 ClassOfMethodDecl = IMPD->getClassInterface();
2766 else if (ObjCCategoryImplDecl* CatImplClass =
2767 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2768 ClassOfMethodDecl = CatImplClass->getClassInterface();
2769 }
Mike Stump11289f42009-09-09 15:08:12 +00002770
2771 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2772 if (ClassDeclared != IDecl ||
Steve Naroffa057ba92009-07-16 00:25:06 +00002773 ClassOfMethodDecl != ClassDeclared)
Mike Stump11289f42009-09-09 15:08:12 +00002774 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002775 << IV->getDeclName();
Mike Stump12b8ce12009-08-04 21:02:39 +00002776 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2777 // @protected
Mike Stump11289f42009-09-09 15:08:12 +00002778 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002779 << IV->getDeclName();
Steve Naroffd1b64be2009-03-04 18:34:24 +00002780 }
Steve Naroffa057ba92009-07-16 00:25:06 +00002781
2782 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2783 MemberLoc, BaseExpr,
John McCall10eae182009-11-30 22:42:35 +00002784 IsArrow));
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +00002785 }
Steve Naroffa057ba92009-07-16 00:25:06 +00002786 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlssonf571c112009-08-26 18:25:21 +00002787 << IDecl->getDeclName() << MemberName
Steve Naroffa057ba92009-07-16 00:25:06 +00002788 << BaseExpr->getSourceRange());
Fariborz Jahanianb1378f92008-12-13 22:20:28 +00002789 }
Chris Lattnerb63a7452008-07-21 04:28:12 +00002790 }
Steve Naroff1329fa02009-07-15 18:40:39 +00002791 // Handle properties on 'id' and qualified "id".
John McCall10eae182009-11-30 22:42:35 +00002792 if (!IsArrow && (BaseType->isObjCIdType() ||
2793 BaseType->isObjCQualifiedIdType())) {
John McCall9dd450b2009-09-21 23:43:11 +00002794 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlssonf571c112009-08-26 18:25:21 +00002795 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002796
Steve Naroff7cae42b2009-07-10 23:34:53 +00002797 // Check protocols on qualified interfaces.
Anders Carlssonf571c112009-08-26 18:25:21 +00002798 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002799 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2800 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2801 // Check the use of this declaration
2802 if (DiagnoseUseOfDecl(PD, MemberLoc))
2803 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002804
Steve Naroff7cae42b2009-07-10 23:34:53 +00002805 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2806 MemberLoc, BaseExpr));
2807 }
2808 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2809 // Check the use of this method.
2810 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2811 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002812
Steve Naroff7cae42b2009-07-10 23:34:53 +00002813 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump11289f42009-09-09 15:08:12 +00002814 OMD->getResultType(),
2815 OMD, OpLoc, MemberLoc,
Steve Naroff7cae42b2009-07-10 23:34:53 +00002816 NULL, 0));
2817 }
2818 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002819
Steve Naroff7cae42b2009-07-10 23:34:53 +00002820 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00002821 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002822 }
Chris Lattnerdc420f42008-07-21 04:59:05 +00002823 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2824 // pointer to a (potentially qualified) interface type.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002825 const ObjCObjectPointerType *OPT;
John McCall10eae182009-11-30 22:42:35 +00002826 if (!IsArrow && (OPT = BaseType->getAsObjCInterfacePointerType())) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002827 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2828 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlssonf571c112009-08-26 18:25:21 +00002829 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002830
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002831 // Search for a declared property first.
Anders Carlssonf571c112009-08-26 18:25:21 +00002832 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002833 // Check whether we can reference this property.
2834 if (DiagnoseUseOfDecl(PD, MemberLoc))
2835 return ExprError();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00002836 QualType ResTy = PD->getType();
Anders Carlssonf571c112009-08-26 18:25:21 +00002837 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002838 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianfe9e3942009-05-08 20:20:55 +00002839 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2840 ResTy = Getter->getResultType();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00002841 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner43df5562009-02-16 18:35:08 +00002842 MemberLoc, BaseExpr));
2843 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002844 // Check protocols on qualified interfaces.
Steve Naroffaccc4882009-07-20 17:56:53 +00002845 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2846 E = OPT->qual_end(); I != E; ++I)
Anders Carlssonf571c112009-08-26 18:25:21 +00002847 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002848 // Check whether we can reference this property.
2849 if (DiagnoseUseOfDecl(PD, MemberLoc))
2850 return ExprError();
Chris Lattner43df5562009-02-16 18:35:08 +00002851
Steve Narofff6009ed2009-01-21 00:14:39 +00002852 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner43df5562009-02-16 18:35:08 +00002853 MemberLoc, BaseExpr));
2854 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002855 // If that failed, look for an "implicit" property by seeing if the nullary
2856 // selector is implemented.
2857
2858 // FIXME: The logic for looking up nullary and unary selectors should be
2859 // shared with the code in ActOnInstanceMessage.
2860
Anders Carlssonf571c112009-08-26 18:25:21 +00002861 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002862 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002863
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002864 // If this reference is in an @implementation, check for 'private' methods.
2865 if (!Getter)
Steve Naroffbb69c942009-10-01 23:46:04 +00002866 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002867
Steve Naroff1df62692008-10-22 19:16:27 +00002868 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00002869 if (!Getter)
2870 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002871 if (Getter) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002872 // Check if we can reference this property.
2873 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2874 return ExprError();
Steve Naroff1d984fe2009-03-11 13:48:17 +00002875 }
2876 // If we found a getter then this may be a valid dot-reference, we
2877 // will look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00002878 Selector SetterSel =
2879 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlssonf571c112009-08-26 18:25:21 +00002880 PP.getSelectorTable(), Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002881 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00002882 if (!Setter) {
2883 // If this reference is in an @implementation, also check for 'private'
2884 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00002885 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00002886 }
2887 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00002888 if (!Setter)
2889 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002890
Steve Naroff1d984fe2009-03-11 13:48:17 +00002891 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2892 return ExprError();
2893
2894 if (Getter || Setter) {
2895 QualType PType;
2896
2897 if (Getter)
2898 PType = Getter->getResultType();
Fariborz Jahanian88cc2342009-08-18 20:50:23 +00002899 else
2900 // Get the expression type from Setter's incoming parameter.
2901 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1d984fe2009-03-11 13:48:17 +00002902 // FIXME: we must check that the setter has property type.
Fariborz Jahanian9a846652009-08-20 17:02:02 +00002903 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1d984fe2009-03-11 13:48:17 +00002904 Setter, MemberLoc, BaseExpr));
2905 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002906 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00002907 << MemberName << BaseType);
Fariborz Jahanian21f54ee2007-11-12 22:29:28 +00002908 }
Mike Stump11289f42009-09-09 15:08:12 +00002909
Steve Naroffe87026a2009-07-24 17:54:45 +00002910 // Handle the following exceptional case (*Obj).isa.
John McCall10eae182009-11-30 22:42:35 +00002911 if (!IsArrow &&
Steve Naroffe87026a2009-07-24 17:54:45 +00002912 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlssonf571c112009-08-26 18:25:21 +00002913 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroffe87026a2009-07-24 17:54:45 +00002914 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00002915 Context.getObjCClassType()));
Steve Naroffe87026a2009-07-24 17:54:45 +00002916
Chris Lattnerb63a7452008-07-21 04:28:12 +00002917 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00002918 if (BaseType->isExtVectorType()) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002919 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerb63a7452008-07-21 04:28:12 +00002920 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2921 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002922 return ExprError();
Anders Carlssonf571c112009-08-26 18:25:21 +00002923 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Narofff6009ed2009-01-21 00:14:39 +00002924 MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00002925 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002926
Douglas Gregor0b08ba42009-03-27 06:00:30 +00002927 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2928 << BaseType << BaseExpr->getSourceRange();
2929
Douglas Gregor0b08ba42009-03-27 06:00:30 +00002930 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00002931}
2932
John McCall10eae182009-11-30 22:42:35 +00002933static Sema::OwningExprResult DiagnoseDtorReference(Sema &SemaRef,
2934 SourceLocation NameLoc,
2935 Sema::ExprArg MemExpr) {
2936 Expr *E = (Expr *) MemExpr.get();
2937 SourceLocation ExpectedLParenLoc = SemaRef.PP.getLocForEndOfToken(NameLoc);
2938 SemaRef.Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002939 << isa<CXXPseudoDestructorExpr>(E)
2940 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2941
John McCall10eae182009-11-30 22:42:35 +00002942 return SemaRef.ActOnCallExpr(/*Scope*/ 0,
2943 move(MemExpr),
2944 /*LPLoc*/ ExpectedLParenLoc,
2945 Sema::MultiExprArg(SemaRef, 0, 0),
2946 /*CommaLocs*/ 0,
2947 /*RPLoc*/ ExpectedLParenLoc);
2948}
2949
2950/// The main callback when the parser finds something like
2951/// expression . [nested-name-specifier] identifier
2952/// expression -> [nested-name-specifier] identifier
2953/// where 'identifier' encompasses a fairly broad spectrum of
2954/// possibilities, including destructor and operator references.
2955///
2956/// \param OpKind either tok::arrow or tok::period
2957/// \param HasTrailingLParen whether the next token is '(', which
2958/// is used to diagnose mis-uses of special members that can
2959/// only be called
2960/// \param ObjCImpDecl the current ObjC @implementation decl;
2961/// this is an ugly hack around the fact that ObjC @implementations
2962/// aren't properly put in the context chain
2963Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
2964 SourceLocation OpLoc,
2965 tok::TokenKind OpKind,
2966 const CXXScopeSpec &SS,
2967 UnqualifiedId &Id,
2968 DeclPtrTy ObjCImpDecl,
2969 bool HasTrailingLParen) {
2970 if (SS.isSet() && SS.isInvalid())
2971 return ExprError();
2972
2973 TemplateArgumentListInfo TemplateArgsBuffer;
2974
2975 // Decompose the name into its component parts.
2976 DeclarationName Name;
2977 SourceLocation NameLoc;
2978 const TemplateArgumentListInfo *TemplateArgs;
2979 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
2980 Name, NameLoc, TemplateArgs);
2981
2982 bool IsArrow = (OpKind == tok::arrow);
2983
2984 NamedDecl *FirstQualifierInScope
2985 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
2986 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
2987
2988 // This is a postfix expression, so get rid of ParenListExprs.
2989 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
2990
2991 Expr *Base = BaseArg.takeAs<Expr>();
2992 OwningExprResult Result(*this);
2993 if (Base->getType()->isDependentType()) {
John McCall2d74de92009-12-01 22:10:20 +00002994 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00002995 IsArrow, OpLoc,
2996 SS, FirstQualifierInScope,
2997 Name, NameLoc,
2998 TemplateArgs);
2999 } else {
3000 LookupResult R(*this, Name, NameLoc, LookupMemberName);
3001 if (TemplateArgs) {
3002 // Re-use the lookup done for the template name.
3003 DecomposeTemplateName(R, Id);
3004 } else {
3005 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3006 SS, FirstQualifierInScope,
3007 ObjCImpDecl);
3008
3009 if (Result.isInvalid()) {
3010 Owned(Base);
3011 return ExprError();
3012 }
3013
3014 if (Result.get()) {
3015 // The only way a reference to a destructor can be used is to
3016 // immediately call it, which falls into this case. If the
3017 // next token is not a '(', produce a diagnostic and build the
3018 // call now.
3019 if (!HasTrailingLParen &&
3020 Id.getKind() == UnqualifiedId::IK_DestructorName)
3021 return DiagnoseDtorReference(*this, NameLoc, move(Result));
3022
3023 return move(Result);
3024 }
3025 }
3026
John McCall2d74de92009-12-01 22:10:20 +00003027 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
3028 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003029 }
3030
3031 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00003032}
3033
Anders Carlsson355933d2009-08-25 03:49:14 +00003034Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3035 FunctionDecl *FD,
3036 ParmVarDecl *Param) {
3037 if (Param->hasUnparsedDefaultArg()) {
3038 Diag (CallLoc,
3039 diag::err_use_of_default_argument_to_function_declared_later) <<
3040 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003041 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson355933d2009-08-25 03:49:14 +00003042 diag::note_default_argument_declared_here);
3043 } else {
3044 if (Param->hasUninstantiatedDefaultArg()) {
3045 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3046
3047 // Instantiate the expression.
Douglas Gregor01afeef2009-08-28 20:31:08 +00003048 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson657bad42009-09-05 05:14:19 +00003049
Mike Stump11289f42009-09-09 15:08:12 +00003050 InstantiatingTemplate Inst(*this, CallLoc, Param,
3051 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregor01afeef2009-08-28 20:31:08 +00003052 ArgList.getInnermost().flat_size());
Anders Carlsson355933d2009-08-25 03:49:14 +00003053
John McCall76d824f2009-08-25 22:02:44 +00003054 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump11289f42009-09-09 15:08:12 +00003055 if (Result.isInvalid())
Anders Carlsson355933d2009-08-25 03:49:14 +00003056 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003057
3058 if (SetParamDefaultArgument(Param, move(Result),
Anders Carlsson355933d2009-08-25 03:49:14 +00003059 /*FIXME:EqualLoc*/
3060 UninstExpr->getSourceRange().getBegin()))
3061 return ExprError();
3062 }
Mike Stump11289f42009-09-09 15:08:12 +00003063
Anders Carlsson355933d2009-08-25 03:49:14 +00003064 Expr *DefaultExpr = Param->getDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +00003065
Anders Carlsson355933d2009-08-25 03:49:14 +00003066 // If the default expression creates temporaries, we need to
3067 // push them to the current stack of expression temporaries so they'll
3068 // be properly destroyed.
Mike Stump11289f42009-09-09 15:08:12 +00003069 if (CXXExprWithTemporaries *E
Anders Carlsson355933d2009-08-25 03:49:14 +00003070 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00003071 assert(!E->shouldDestroyTemporaries() &&
Anders Carlsson355933d2009-08-25 03:49:14 +00003072 "Can't destroy temporaries in a default argument expr!");
3073 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
3074 ExprTemporaries.push_back(E->getTemporary(I));
3075 }
3076 }
3077
3078 // We already type-checked the argument, so we know it works.
3079 return Owned(CXXDefaultArgExpr::Create(Context, Param));
3080}
3081
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003082/// ConvertArgumentsForCall - Converts the arguments specified in
3083/// Args/NumArgs to the parameter types of the function FDecl with
3084/// function prototype Proto. Call is the call expression itself, and
3085/// Fn is the function expression. For a C++ member function, this
3086/// routine does not attempt to convert the object argument. Returns
3087/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003088bool
3089Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003090 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003091 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003092 Expr **Args, unsigned NumArgs,
3093 SourceLocation RParenLoc) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003094 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003095 // assignment, to the types of the corresponding parameter, ...
3096 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003097 bool Invalid = false;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003098
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003099 // If too few arguments are available (and we don't have default
3100 // arguments for the remaining parameters), don't make the call.
3101 if (NumArgs < NumArgsInProto) {
3102 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3103 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3104 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00003105 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003106 }
3107
3108 // If too many are passed and not variadic, error on the extras and drop
3109 // them.
3110 if (NumArgs > NumArgsInProto) {
3111 if (!Proto->isVariadic()) {
3112 Diag(Args[NumArgsInProto]->getLocStart(),
3113 diag::err_typecheck_call_too_many_args)
3114 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
3115 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3116 Args[NumArgs-1]->getLocEnd());
3117 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003118 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003119 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003120 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003121 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003122 llvm::SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003123 VariadicCallType CallType =
3124 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3125 if (Fn->getType()->isBlockPointerType())
3126 CallType = VariadicBlock; // Block
3127 else if (isa<MemberExpr>(Fn))
3128 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003129 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003130 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003131 if (Invalid)
3132 return true;
3133 unsigned TotalNumArgs = AllArgs.size();
3134 for (unsigned i = 0; i < TotalNumArgs; ++i)
3135 Call->setArg(i, AllArgs[i]);
3136
3137 return false;
3138}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003139
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003140bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3141 FunctionDecl *FDecl,
3142 const FunctionProtoType *Proto,
3143 unsigned FirstProtoArg,
3144 Expr **Args, unsigned NumArgs,
3145 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003146 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003147 unsigned NumArgsInProto = Proto->getNumArgs();
3148 unsigned NumArgsToCheck = NumArgs;
3149 bool Invalid = false;
3150 if (NumArgs != NumArgsInProto)
3151 // Use default arguments for missing arguments
3152 NumArgsToCheck = NumArgsInProto;
3153 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003154 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003155 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003156 QualType ProtoArgType = Proto->getArgType(i);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003157
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003158 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003159 if (ArgIx < NumArgs) {
3160 Arg = Args[ArgIx++];
3161
Eli Friedman3164fb12009-03-22 22:00:50 +00003162 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3163 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003164 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003165 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003166 return true;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003167
Douglas Gregor58354032008-12-24 00:01:03 +00003168 // Pass the argument.
3169 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3170 return true;
Anders Carlsson78cfaa92009-11-13 04:34:45 +00003171
Anders Carlsson97df0b42009-11-13 17:04:35 +00003172 if (!ProtoArgType->isReferenceType())
3173 Arg = MaybeBindToTemporary(Arg).takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003174 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003175 ParmVarDecl *Param = FDecl->getParamDecl(i);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003176
Mike Stump11289f42009-09-09 15:08:12 +00003177 OwningExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003178 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003179 if (ArgExpr.isInvalid())
3180 return true;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003181
Anders Carlsson355933d2009-08-25 03:49:14 +00003182 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003183 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003184 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003185 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003186
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003187 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003188 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003189 // Promote the arguments (C99 6.5.2.2p7).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003190 for (unsigned i = ArgIx; i < NumArgs; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003191 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00003192 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003193 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003194 }
3195 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003196 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003197}
3198
Douglas Gregorcabea402009-09-22 15:41:20 +00003199/// \brief "Deconstruct" the function argument of a call expression to find
3200/// the underlying declaration (if any), the name of the called function,
3201/// whether argument-dependent lookup is available, whether it has explicit
3202/// template arguments, etc.
3203void Sema::DeconstructCallFunction(Expr *FnExpr,
John McCalld14a8642009-11-21 08:51:07 +00003204 llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregorcabea402009-09-22 15:41:20 +00003205 DeclarationName &Name,
3206 NestedNameSpecifier *&Qualifier,
3207 SourceRange &QualifierRange,
3208 bool &ArgumentDependentLookup,
John McCall283b9012009-11-22 00:44:51 +00003209 bool &Overloaded,
Douglas Gregorcabea402009-09-22 15:41:20 +00003210 bool &HasExplicitTemplateArguments,
John McCall6b51f282009-11-23 01:53:49 +00003211 TemplateArgumentListInfo &ExplicitTemplateArgs) {
Douglas Gregorcabea402009-09-22 15:41:20 +00003212 // Set defaults for all of the output parameters.
Douglas Gregorcabea402009-09-22 15:41:20 +00003213 Name = DeclarationName();
3214 Qualifier = 0;
3215 QualifierRange = SourceRange();
John McCalle66edc12009-11-24 19:00:30 +00003216 ArgumentDependentLookup = false;
John McCall283b9012009-11-22 00:44:51 +00003217 Overloaded = false;
Douglas Gregorcabea402009-09-22 15:41:20 +00003218 HasExplicitTemplateArguments = false;
John McCall283b9012009-11-22 00:44:51 +00003219
Douglas Gregorcabea402009-09-22 15:41:20 +00003220 // If we're directly calling a function, get the appropriate declaration.
3221 // Also, in C++, keep track of whether we should perform argument-dependent
3222 // lookup and whether there were any explicitly-specified template arguments.
3223 while (true) {
3224 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
3225 FnExpr = IcExpr->getSubExpr();
3226 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Douglas Gregorcabea402009-09-22 15:41:20 +00003227 FnExpr = PExpr->getSubExpr();
3228 } else if (isa<UnaryOperator>(FnExpr) &&
3229 cast<UnaryOperator>(FnExpr)->getOpcode()
3230 == UnaryOperator::AddrOf) {
3231 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregorcabea402009-09-22 15:41:20 +00003232 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
John McCalld14a8642009-11-21 08:51:07 +00003233 Fns.push_back(cast<NamedDecl>(DRExpr->getDecl()));
3234 ArgumentDependentLookup = false;
3235 if ((Qualifier = DRExpr->getQualifier()))
Douglas Gregor4bd90e52009-10-23 18:54:35 +00003236 QualifierRange = DRExpr->getQualifierRange();
Douglas Gregorcabea402009-09-22 15:41:20 +00003237 break;
John McCalld14a8642009-11-21 08:51:07 +00003238 } else if (UnresolvedLookupExpr *UnresLookup
3239 = dyn_cast<UnresolvedLookupExpr>(FnExpr)) {
3240 Name = UnresLookup->getName();
3241 Fns.append(UnresLookup->decls_begin(), UnresLookup->decls_end());
3242 ArgumentDependentLookup = UnresLookup->requiresADL();
John McCall283b9012009-11-22 00:44:51 +00003243 Overloaded = UnresLookup->isOverloaded();
John McCalld14a8642009-11-21 08:51:07 +00003244 if ((Qualifier = UnresLookup->getQualifier()))
3245 QualifierRange = UnresLookup->getQualifierRange();
John McCalle66edc12009-11-24 19:00:30 +00003246 if (UnresLookup->hasExplicitTemplateArgs()) {
3247 HasExplicitTemplateArguments = true;
3248 UnresLookup->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Douglas Gregorcabea402009-09-22 15:41:20 +00003249 }
3250 break;
3251 } else {
Douglas Gregorcabea402009-09-22 15:41:20 +00003252 break;
3253 }
3254 }
3255}
3256
Steve Naroff83895f72007-09-16 03:34:24 +00003257/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003258/// This provides the location of the left/right parens and a list of comma
3259/// locations.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003260Action::OwningExprResult
3261Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3262 MultiExprArg args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003263 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003264 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003265
3266 // Since this might be a postfix expression, get rid of ParenListExprs.
3267 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump11289f42009-09-09 15:08:12 +00003268
Anders Carlsson3cbc8592009-05-01 19:30:39 +00003269 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003270 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner38dbdb22007-07-21 03:03:59 +00003271 assert(Fn && "no function call expression");
Mike Stump11289f42009-09-09 15:08:12 +00003272
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003273 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003274 // If this is a pseudo-destructor expression, build the call immediately.
3275 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3276 if (NumArgs > 0) {
3277 // Pseudo-destructor calls should not have any arguments.
3278 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3279 << CodeModificationHint::CreateRemoval(
3280 SourceRange(Args[0]->getLocStart(),
3281 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003282
Douglas Gregorad8a3362009-09-04 17:36:40 +00003283 for (unsigned I = 0; I != NumArgs; ++I)
3284 Args[I]->Destroy(Context);
Mike Stump11289f42009-09-09 15:08:12 +00003285
Douglas Gregorad8a3362009-09-04 17:36:40 +00003286 NumArgs = 0;
3287 }
Mike Stump11289f42009-09-09 15:08:12 +00003288
Douglas Gregorad8a3362009-09-04 17:36:40 +00003289 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3290 RParenLoc));
3291 }
Mike Stump11289f42009-09-09 15:08:12 +00003292
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003293 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003294 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003295 // FIXME: Will need to cache the results of name lookup (including ADL) in
3296 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003297 bool Dependent = false;
3298 if (Fn->isTypeDependent())
3299 Dependent = true;
3300 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3301 Dependent = true;
3302
3303 if (Dependent)
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003304 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003305 Context.DependentTy, RParenLoc));
3306
3307 // Determine whether this is a call to an object (C++ [over.call.object]).
3308 if (Fn->getType()->isRecordType())
3309 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3310 CommaLocs, RParenLoc));
3311
John McCall10eae182009-11-30 22:42:35 +00003312 Expr *NakedFn = Fn->IgnoreParens();
3313
3314 // Determine whether this is a call to an unresolved member function.
3315 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3316 // If lookup was unresolved but not dependent (i.e. didn't find
3317 // an unresolved using declaration), it has to be an overloaded
3318 // function set, which means it must contain either multiple
3319 // declarations (all methods or method templates) or a single
3320 // method template.
3321 assert((MemE->getNumDecls() > 1) ||
3322 isa<FunctionTemplateDecl>(*MemE->decls_begin()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00003323 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00003324
John McCall2d74de92009-12-01 22:10:20 +00003325 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3326 CommaLocs, RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003327 }
3328
Douglas Gregore254f902009-02-04 00:32:51 +00003329 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00003330 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003331 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00003332 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00003333 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3334 CommaLocs, RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003335 }
Anders Carlsson61914b52009-10-03 17:40:22 +00003336
3337 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00003338 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson61914b52009-10-03 17:40:22 +00003339 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3340 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003341 if (const FunctionProtoType *FPT =
3342 dyn_cast<FunctionProtoType>(BO->getType())) {
3343 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson61914b52009-10-03 17:40:22 +00003344
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003345 ExprOwningPtr<CXXMemberCallExpr>
3346 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
3347 NumArgs, ResultTy,
3348 RParenLoc));
Anders Carlsson61914b52009-10-03 17:40:22 +00003349
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003350 if (CheckCallReturnType(FPT->getResultType(),
3351 BO->getRHS()->getSourceRange().getBegin(),
3352 TheCall.get(), 0))
3353 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00003354
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003355 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
3356 RParenLoc))
3357 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00003358
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003359 return Owned(MaybeBindToTemporary(TheCall.release()).release());
3360 }
3361 return ExprError(Diag(Fn->getLocStart(),
3362 diag::err_typecheck_call_not_function)
3363 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson61914b52009-10-03 17:40:22 +00003364 }
3365 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003366 }
3367
Douglas Gregore254f902009-02-04 00:32:51 +00003368 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003369 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00003370 // lookup and whether there were any explicitly-specified template arguments.
John McCalld14a8642009-11-21 08:51:07 +00003371 llvm::SmallVector<NamedDecl*,8> Fns;
3372 DeclarationName UnqualifiedName;
John McCall283b9012009-11-22 00:44:51 +00003373 bool Overloaded;
3374 bool ADL;
Douglas Gregor89026b52009-06-30 23:57:56 +00003375 bool HasExplicitTemplateArgs = 0;
John McCall6b51f282009-11-23 01:53:49 +00003376 TemplateArgumentListInfo ExplicitTemplateArgs;
Douglas Gregorcabea402009-09-22 15:41:20 +00003377 NestedNameSpecifier *Qualifier = 0;
3378 SourceRange QualifierRange;
John McCalld14a8642009-11-21 08:51:07 +00003379 DeconstructCallFunction(Fn, Fns, UnqualifiedName, Qualifier, QualifierRange,
John McCall283b9012009-11-22 00:44:51 +00003380 ADL, Overloaded, HasExplicitTemplateArgs,
John McCall6b51f282009-11-23 01:53:49 +00003381 ExplicitTemplateArgs);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003382
John McCall283b9012009-11-22 00:44:51 +00003383 NamedDecl *NDecl; // the specific declaration we're calling, if applicable
3384 FunctionDecl *FDecl; // same, if it's known to be a function
John McCalld14a8642009-11-21 08:51:07 +00003385
John McCall283b9012009-11-22 00:44:51 +00003386 if (Overloaded || ADL) {
3387#ifndef NDEBUG
3388 if (ADL) {
3389 // To do ADL, we must have found an unqualified name.
3390 assert(UnqualifiedName && "found no unqualified name for ADL");
3391
3392 // We don't perform ADL for implicit declarations of builtins.
3393 // Verify that this was correctly set up.
3394 if (Fns.size() == 1 && (FDecl = dyn_cast<FunctionDecl>(Fns[0])) &&
3395 FDecl->getBuiltinID() && FDecl->isImplicit())
3396 assert(0 && "performing ADL for builtin");
3397
3398 // We don't perform ADL in C.
3399 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
3400 }
3401
3402 if (Overloaded) {
3403 // To be overloaded, we must either have multiple functions or
3404 // at least one function template (which is effectively an
3405 // infinite set of functions).
3406 assert((Fns.size() > 1 ||
3407 (Fns.size() == 1 &&
3408 isa<FunctionTemplateDecl>(Fns[0]->getUnderlyingDecl())))
3409 && "unrecognized overload situation");
3410 }
3411#endif
3412
3413 FDecl = ResolveOverloadedCallFn(Fn, Fns, UnqualifiedName,
John McCall6b51f282009-11-23 01:53:49 +00003414 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
John McCall283b9012009-11-22 00:44:51 +00003415 LParenLoc, Args, NumArgs, CommaLocs,
3416 RParenLoc, ADL);
3417 if (!FDecl)
3418 return ExprError();
3419
3420 Fn = FixOverloadedFunctionReference(Fn, FDecl);
3421
3422 NDecl = FDecl;
3423 } else {
3424 assert(Fns.size() <= 1 && "overloaded without Overloaded flag");
3425 if (Fns.empty())
John McCall2d74de92009-12-01 22:10:20 +00003426 NDecl = 0;
John McCall283b9012009-11-22 00:44:51 +00003427 else {
3428 NDecl = Fns[0];
Douglas Gregore254f902009-02-04 00:32:51 +00003429 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003430 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003431
John McCall2d74de92009-12-01 22:10:20 +00003432 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3433}
3434
3435/// BuildCallExpr - Build a call to a resolved expression, i.e. an
3436/// expression not of \p OverloadTy. The expression should
3437/// unary-convert to an expression of function-pointer or
3438/// block-pointer type.
3439///
3440/// \param NDecl the declaration being called, if available
3441Sema::OwningExprResult
3442Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3443 SourceLocation LParenLoc,
3444 Expr **Args, unsigned NumArgs,
3445 SourceLocation RParenLoc) {
3446 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3447
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003448 // Promote the function operand.
3449 UsualUnaryConversions(Fn);
3450
Chris Lattner08464942007-12-28 05:29:59 +00003451 // Make the call expr early, before semantic checks. This guarantees cleanup
3452 // of arguments and function on error.
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003453 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3454 Args, NumArgs,
3455 Context.BoolTy,
3456 RParenLoc));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003457
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003458 const FunctionType *FuncT;
3459 if (!Fn->getType()->isBlockPointerType()) {
3460 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3461 // have type pointer to function".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003462 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003463 if (PT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003464 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3465 << Fn->getType() << Fn->getSourceRange());
John McCall9dd450b2009-09-21 23:43:11 +00003466 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003467 } else { // This is a block call.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003468 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall9dd450b2009-09-21 23:43:11 +00003469 getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003470 }
Chris Lattner08464942007-12-28 05:29:59 +00003471 if (FuncT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003472 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3473 << Fn->getType() << Fn->getSourceRange());
3474
Eli Friedman3164fb12009-03-22 22:00:50 +00003475 // Check for a valid return type
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003476 if (CheckCallReturnType(FuncT->getResultType(),
3477 Fn->getSourceRange().getBegin(), TheCall.get(),
3478 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003479 return ExprError();
3480
Chris Lattner08464942007-12-28 05:29:59 +00003481 // We know the result type of the call, set it.
Douglas Gregor786ab212008-10-29 02:00:59 +00003482 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003483
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003484 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003485 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003486 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003487 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003488 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003489 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003490
Douglas Gregord8e97de2009-04-02 15:37:10 +00003491 if (FDecl) {
3492 // Check if we have too few/too many template arguments, based
3493 // on our knowledge of the function definition.
3494 const FunctionDecl *Def = 0;
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00003495 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003496 const FunctionProtoType *Proto =
John McCall9dd450b2009-09-21 23:43:11 +00003497 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003498 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3499 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3500 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3501 }
3502 }
Douglas Gregord8e97de2009-04-02 15:37:10 +00003503 }
3504
Steve Naroff0b661582007-08-28 23:30:39 +00003505 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003506 for (unsigned i = 0; i != NumArgs; i++) {
3507 Expr *Arg = Args[i];
3508 DefaultArgumentPromotion(Arg);
Eli Friedman3164fb12009-03-22 22:00:50 +00003509 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3510 Arg->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00003511 PDiag(diag::err_call_incomplete_argument)
3512 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003513 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003514 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003515 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003516 }
Chris Lattner08464942007-12-28 05:29:59 +00003517
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003518 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3519 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003520 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3521 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003522
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003523 // Check for sentinels
3524 if (NDecl)
3525 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003526
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003527 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003528 if (FDecl) {
3529 if (CheckFunctionCall(FDecl, TheCall.get()))
3530 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003531
Douglas Gregor15fc9562009-09-12 00:22:50 +00003532 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003533 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3534 } else if (NDecl) {
3535 if (CheckBlockCall(NDecl, TheCall.get()))
3536 return ExprError();
3537 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003538
Anders Carlssonf8984012009-08-16 03:06:32 +00003539 return MaybeBindToTemporary(TheCall.take());
Chris Lattnere168f762006-11-10 05:29:30 +00003540}
3541
Sebastian Redlb5d49352009-01-19 22:31:54 +00003542Action::OwningExprResult
3543Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3544 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003545 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003546 //FIXME: Preserve type source info.
3547 QualType literalType = GetTypeFromParser(Ty);
Steve Naroff57eb2c52007-07-19 21:32:11 +00003548 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003549 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb5d49352009-01-19 22:31:54 +00003550 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003551
Eli Friedman37a186d2008-05-20 05:22:08 +00003552 if (literalType->isArrayType()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003553 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003554 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3555 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003556 } else if (!literalType->isDependentType() &&
3557 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003558 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003559 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003560 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003561 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003562
Sebastian Redlb5d49352009-01-19 22:31:54 +00003563 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003564 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003565 return ExprError();
Steve Naroffd32419d2008-01-14 18:19:28 +00003566
Chris Lattner79413952008-12-04 23:50:19 +00003567 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003568 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003569 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003570 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003571 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00003572 InitExpr.release();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003573 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Narofff6009ed2009-01-21 00:14:39 +00003574 literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003575}
3576
Sebastian Redlb5d49352009-01-19 22:31:54 +00003577Action::OwningExprResult
3578Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003579 SourceLocation RBraceLoc) {
3580 unsigned NumInit = initlist.size();
3581 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson4692db02007-08-31 04:56:16 +00003582
Steve Naroff30d242c2007-09-15 18:49:24 +00003583 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003584 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003585
Mike Stump4e1f26a2009-02-19 03:04:26 +00003586 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00003587 RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003588 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003589 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003590}
3591
Anders Carlsson094c4592009-10-18 18:12:03 +00003592static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3593 QualType SrcTy, QualType DestTy) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003594 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson094c4592009-10-18 18:12:03 +00003595 return CastExpr::CK_NoOp;
3596
3597 if (SrcTy->hasPointerRepresentation()) {
3598 if (DestTy->hasPointerRepresentation())
3599 return CastExpr::CK_BitCast;
3600 if (DestTy->isIntegerType())
3601 return CastExpr::CK_PointerToIntegral;
3602 }
3603
3604 if (SrcTy->isIntegerType()) {
3605 if (DestTy->isIntegerType())
3606 return CastExpr::CK_IntegralCast;
3607 if (DestTy->hasPointerRepresentation())
3608 return CastExpr::CK_IntegralToPointer;
3609 if (DestTy->isRealFloatingType())
3610 return CastExpr::CK_IntegralToFloating;
3611 }
3612
3613 if (SrcTy->isRealFloatingType()) {
3614 if (DestTy->isRealFloatingType())
3615 return CastExpr::CK_FloatingCast;
3616 if (DestTy->isIntegerType())
3617 return CastExpr::CK_FloatingToIntegral;
3618 }
3619
3620 // FIXME: Assert here.
3621 // assert(false && "Unhandled cast combination!");
3622 return CastExpr::CK_Unknown;
3623}
3624
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003625/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redl955a0672009-07-29 13:50:23 +00003626bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump11289f42009-09-09 15:08:12 +00003627 CastExpr::CastKind& Kind,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003628 CXXMethodDecl *& ConversionDecl,
3629 bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00003630 if (getLangOptions().CPlusPlus)
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003631 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3632 ConversionDecl);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003633
Eli Friedmanda8d4de2009-08-15 19:02:19 +00003634 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003635
3636 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3637 // type needs to be scalar.
3638 if (castType->isVoidType()) {
3639 // Cast to void allows any expr type.
Anders Carlssonef918ac2009-10-16 02:35:04 +00003640 Kind = CastExpr::CK_ToVoid;
3641 return false;
3642 }
3643
3644 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003645 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003646 (castType->isStructureType() || castType->isUnionType())) {
3647 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00003648 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003649 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3650 << castType << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003651 Kind = CastExpr::CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003652 return false;
3653 }
3654
3655 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003656 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003657 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003658 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003659 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003660 Field != FieldEnd; ++Field) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003661 if (Context.hasSameUnqualifiedType(Field->getType(),
3662 castExpr->getType())) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003663 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3664 << castExpr->getSourceRange();
3665 break;
3666 }
3667 }
3668 if (Field == FieldEnd)
3669 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3670 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003671 Kind = CastExpr::CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003672 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003673 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00003674
3675 // Reject any other conversions to non-scalar types.
3676 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3677 << castType << castExpr->getSourceRange();
3678 }
3679
3680 if (!castExpr->getType()->isScalarType() &&
3681 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003682 return Diag(castExpr->getLocStart(),
3683 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003684 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00003685 }
3686
Anders Carlsson43d70f82009-10-16 05:23:41 +00003687 if (castType->isExtVectorType())
3688 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3689
Anders Carlsson525b76b2009-10-16 02:48:28 +00003690 if (castType->isVectorType())
3691 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3692 if (castExpr->getType()->isVectorType())
3693 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3694
3695 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffb47acdb2009-04-08 23:52:26 +00003696 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003697
Anders Carlsson43d70f82009-10-16 05:23:41 +00003698 if (isa<ObjCSelectorExpr>(castExpr))
3699 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3700
Anders Carlsson525b76b2009-10-16 02:48:28 +00003701 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00003702 QualType castExprType = castExpr->getType();
3703 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3704 return Diag(castExpr->getLocStart(),
3705 diag::err_cast_pointer_from_non_pointer_int)
3706 << castExprType << castExpr->getSourceRange();
3707 } else if (!castExpr->getType()->isArithmeticType()) {
3708 if (!castType->isIntegralType() && castType->isArithmeticType())
3709 return Diag(castExpr->getLocStart(),
3710 diag::err_cast_pointer_to_non_pointer_int)
3711 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003712 }
Anders Carlsson094c4592009-10-18 18:12:03 +00003713
3714 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003715 return false;
3716}
3717
Anders Carlsson525b76b2009-10-16 02:48:28 +00003718bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3719 CastExpr::CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00003720 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00003721
Anders Carlssonde71adf2007-11-27 05:51:55 +00003722 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00003723 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00003724 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00003725 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00003726 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00003727 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003728 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003729 } else
3730 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003731 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003732 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003733
Anders Carlsson525b76b2009-10-16 02:48:28 +00003734 Kind = CastExpr::CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003735 return false;
3736}
3737
Anders Carlsson43d70f82009-10-16 05:23:41 +00003738bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3739 CastExpr::CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00003740 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson43d70f82009-10-16 05:23:41 +00003741
3742 QualType SrcTy = CastExpr->getType();
3743
Nate Begemanc8961a42009-06-27 22:05:55 +00003744 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3745 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00003746 if (SrcTy->isVectorType()) {
3747 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3748 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3749 << DestTy << SrcTy << R;
Anders Carlsson43d70f82009-10-16 05:23:41 +00003750 Kind = CastExpr::CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00003751 return false;
3752 }
3753
Nate Begemanbd956c42009-06-28 02:36:38 +00003754 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00003755 // conversion will take place first from scalar to elt type, and then
3756 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00003757 if (SrcTy->isPointerType())
3758 return Diag(R.getBegin(),
3759 diag::err_invalid_conversion_between_vector_and_scalar)
3760 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00003761
3762 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3763 ImpCastExprToType(CastExpr, DestElemTy,
3764 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson43d70f82009-10-16 05:23:41 +00003765
3766 Kind = CastExpr::CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00003767 return false;
3768}
3769
Sebastian Redlb5d49352009-01-19 22:31:54 +00003770Action::OwningExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00003771Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003772 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssonf10e4142009-08-07 22:21:05 +00003773 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump11289f42009-09-09 15:08:12 +00003774
Sebastian Redlb5d49352009-01-19 22:31:54 +00003775 assert((Ty != 0) && (Op.get() != 0) &&
3776 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00003777
Nate Begeman5ec4b312009-08-10 23:49:36 +00003778 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003779 //FIXME: Preserve type source info.
3780 QualType castType = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003781
Nate Begeman5ec4b312009-08-10 23:49:36 +00003782 // If the Expr being casted is a ParenListExpr, handle it specially.
3783 if (isa<ParenListExpr>(castExpr))
3784 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlssone9766d52009-09-09 21:33:21 +00003785 CXXMethodDecl *Method = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003786 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlssone9766d52009-09-09 21:33:21 +00003787 Kind, Method))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003788 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00003789
3790 if (Method) {
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003791 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
Anders Carlssone9766d52009-09-09 21:33:21 +00003792 Method, move(Op));
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003793
Anders Carlssone9766d52009-09-09 21:33:21 +00003794 if (CastArg.isInvalid())
3795 return ExprError();
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003796
Anders Carlssone9766d52009-09-09 21:33:21 +00003797 castExpr = CastArg.takeAs<Expr>();
3798 } else {
3799 Op.release();
Fariborz Jahanian3df87672009-08-29 19:15:16 +00003800 }
Mike Stump11289f42009-09-09 15:08:12 +00003801
Sebastian Redl9f831db2009-07-25 15:41:38 +00003802 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump11289f42009-09-09 15:08:12 +00003803 Kind, castExpr, castType,
Anders Carlssonf10e4142009-08-07 22:21:05 +00003804 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003805}
3806
Nate Begeman5ec4b312009-08-10 23:49:36 +00003807/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3808/// of comma binary operators.
3809Action::OwningExprResult
3810Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3811 Expr *expr = EA.takeAs<Expr>();
3812 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3813 if (!E)
3814 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00003815
Nate Begeman5ec4b312009-08-10 23:49:36 +00003816 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00003817
Nate Begeman5ec4b312009-08-10 23:49:36 +00003818 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3819 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3820 Owned(E->getExpr(i)));
Mike Stump11289f42009-09-09 15:08:12 +00003821
Nate Begeman5ec4b312009-08-10 23:49:36 +00003822 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3823}
3824
3825Action::OwningExprResult
3826Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3827 SourceLocation RParenLoc, ExprArg Op,
3828 QualType Ty) {
3829 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump11289f42009-09-09 15:08:12 +00003830
3831 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman5ec4b312009-08-10 23:49:36 +00003832 // then handle it as such.
3833 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3834 if (PE->getNumExprs() == 0) {
3835 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3836 return ExprError();
3837 }
3838
3839 llvm::SmallVector<Expr *, 8> initExprs;
3840 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3841 initExprs.push_back(PE->getExpr(i));
3842
3843 // FIXME: This means that pretty-printing the final AST will produce curly
3844 // braces instead of the original commas.
3845 Op.release();
Mike Stump11289f42009-09-09 15:08:12 +00003846 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00003847 initExprs.size(), RParenLoc);
3848 E->setType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003849 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman5ec4b312009-08-10 23:49:36 +00003850 Owned(E));
3851 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003852 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00003853 // sequence of BinOp comma operators.
3854 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3855 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3856 }
3857}
3858
Fariborz Jahanian906d8712009-11-25 01:26:41 +00003859Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00003860 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00003861 MultiExprArg Val,
3862 TypeTy *TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003863 unsigned nexprs = Val.size();
3864 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00003865 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
3866 Expr *expr;
3867 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
3868 expr = new (Context) ParenExpr(L, R, exprs[0]);
3869 else
3870 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00003871 return Owned(expr);
3872}
3873
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003874/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3875/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00003876/// C99 6.5.15
3877QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3878 SourceLocation QuestionLoc) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003879 // C++ is sufficiently different to merit its own checker.
3880 if (getLangOptions().CPlusPlus)
3881 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3882
John McCall1fa36b72009-11-05 09:23:39 +00003883 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
3884
Chris Lattner432cff52009-02-18 04:28:32 +00003885 UsualUnaryConversions(Cond);
3886 UsualUnaryConversions(LHS);
3887 UsualUnaryConversions(RHS);
3888 QualType CondTy = Cond->getType();
3889 QualType LHSTy = LHS->getType();
3890 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00003891
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003892 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003893 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3894 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3895 << CondTy;
3896 return QualType();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003897 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003898
Chris Lattnere2949f42008-01-06 22:42:25 +00003899 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00003900 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3901 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00003902
Chris Lattnere2949f42008-01-06 22:42:25 +00003903 // If both operands have arithmetic type, do the usual arithmetic conversions
3904 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00003905 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3906 UsualArithmeticConversions(LHS, RHS);
3907 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00003908 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003909
Chris Lattnere2949f42008-01-06 22:42:25 +00003910 // If both operands are the same structure or union type, the result is that
3911 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003912 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3913 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00003914 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00003915 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00003916 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00003917 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00003918 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003919 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003920
Chris Lattnere2949f42008-01-06 22:42:25 +00003921 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00003922 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00003923 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3924 if (!LHSTy->isVoidType())
3925 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3926 << RHS->getSourceRange();
3927 if (!RHSTy->isVoidType())
3928 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3929 << LHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003930 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
3931 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00003932 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00003933 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00003934 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3935 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00003936 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00003937 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003938 // promote the null to a pointer.
3939 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00003940 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00003941 }
Steve Naroff6b712a72009-07-14 18:25:06 +00003942 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00003943 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003944 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00003945 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00003946 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00003947
3948 // All objective-c pointer type analysis is done here.
3949 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
3950 QuestionLoc);
3951 if (!compositeType.isNull())
3952 return compositeType;
3953
3954
Steve Naroff05efa972009-07-01 14:36:47 +00003955 // Handle block pointer types.
3956 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3957 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3958 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3959 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003960 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
3961 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00003962 return destType;
3963 }
3964 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00003965 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00003966 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00003967 }
Steve Naroff05efa972009-07-01 14:36:47 +00003968 // We have 2 block pointer types.
3969 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3970 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00003971 return LHSTy;
3972 }
Steve Naroff05efa972009-07-01 14:36:47 +00003973 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003974 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3975 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00003976
Steve Naroff05efa972009-07-01 14:36:47 +00003977 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3978 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00003979 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00003980 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00003981 // In this situation, we assume void* type. No especially good
3982 // reason, but this is what gcc does, and we do have to pick
3983 // to get a consistent AST.
3984 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003985 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3986 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00003987 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003988 }
Steve Naroff05efa972009-07-01 14:36:47 +00003989 // The block pointer types are compatible.
Eli Friedman06ed2a52009-10-20 08:27:19 +00003990 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3991 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00003992 return LHSTy;
3993 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00003994
Steve Naroff05efa972009-07-01 14:36:47 +00003995 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3996 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3997 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003998 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3999 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00004000
4001 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4002 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4003 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00004004 QualType destPointee
4005 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004006 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004007 // Add qualifiers if necessary.
4008 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4009 // Promote to void*.
4010 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004011 return destType;
4012 }
4013 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004014 QualType destPointee
4015 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004016 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004017 // Add qualifiers if necessary.
Eli Friedmanb0bc5592009-11-17 01:22:05 +00004018 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004019 // Promote to void*.
Eli Friedmanb0bc5592009-11-17 01:22:05 +00004020 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004021 return destType;
4022 }
4023
4024 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4025 // Two identical pointer types are always compatible.
4026 return LHSTy;
4027 }
4028 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4029 rhptee.getUnqualifiedType())) {
4030 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4031 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4032 // In this situation, we assume void* type. No especially good
4033 // reason, but this is what gcc does, and we do have to pick
4034 // to get a consistent AST.
4035 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004036 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4037 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004038 return incompatTy;
4039 }
4040 // The pointer types are compatible.
4041 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4042 // differently qualified versions of compatible types, the result type is
4043 // a pointer to an appropriately qualified version of the *composite*
4044 // type.
4045 // FIXME: Need to calculate the composite type.
4046 // FIXME: Need to add qualifiers
Eli Friedman06ed2a52009-10-20 08:27:19 +00004047 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4048 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004049 return LHSTy;
4050 }
Mike Stump11289f42009-09-09 15:08:12 +00004051
Steve Naroff05efa972009-07-01 14:36:47 +00004052 // GCC compatibility: soften pointer/integer mismatch.
4053 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4054 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4055 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004056 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004057 return RHSTy;
4058 }
4059 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4060 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4061 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004062 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004063 return LHSTy;
4064 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00004065
Chris Lattnere2949f42008-01-06 22:42:25 +00004066 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004067 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4068 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004069 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004070}
4071
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004072/// FindCompositeObjCPointerType - Helper method to find composite type of
4073/// two objective-c pointer types of the two input expressions.
4074QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4075 SourceLocation QuestionLoc) {
4076 QualType LHSTy = LHS->getType();
4077 QualType RHSTy = RHS->getType();
4078
4079 // Handle things like Class and struct objc_class*. Here we case the result
4080 // to the pseudo-builtin, because that will be implicitly cast back to the
4081 // redefinition type if an attempt is made to access its fields.
4082 if (LHSTy->isObjCClassType() &&
4083 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4084 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4085 return LHSTy;
4086 }
4087 if (RHSTy->isObjCClassType() &&
4088 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4089 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4090 return RHSTy;
4091 }
4092 // And the same for struct objc_object* / id
4093 if (LHSTy->isObjCIdType() &&
4094 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4095 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4096 return LHSTy;
4097 }
4098 if (RHSTy->isObjCIdType() &&
4099 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4100 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4101 return RHSTy;
4102 }
4103 // And the same for struct objc_selector* / SEL
4104 if (Context.isObjCSelType(LHSTy) &&
4105 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4106 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4107 return LHSTy;
4108 }
4109 if (Context.isObjCSelType(RHSTy) &&
4110 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4111 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4112 return RHSTy;
4113 }
4114 // Check constraints for Objective-C object pointers types.
4115 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
4116
4117 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4118 // Two identical object pointer types are always compatible.
4119 return LHSTy;
4120 }
4121 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4122 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4123 QualType compositeType = LHSTy;
4124
4125 // If both operands are interfaces and either operand can be
4126 // assigned to the other, use that type as the composite
4127 // type. This allows
4128 // xxx ? (A*) a : (B*) b
4129 // where B is a subclass of A.
4130 //
4131 // Additionally, as for assignment, if either type is 'id'
4132 // allow silent coercion. Finally, if the types are
4133 // incompatible then make sure to use 'id' as the composite
4134 // type so the result is acceptable for sending messages to.
4135
4136 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4137 // It could return the composite type.
4138 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4139 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4140 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4141 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4142 } else if ((LHSTy->isObjCQualifiedIdType() ||
4143 RHSTy->isObjCQualifiedIdType()) &&
4144 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4145 // Need to handle "id<xx>" explicitly.
4146 // GCC allows qualified id and any Objective-C type to devolve to
4147 // id. Currently localizing to here until clear this should be
4148 // part of ObjCQualifiedIdTypesAreCompatible.
4149 compositeType = Context.getObjCIdType();
4150 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4151 compositeType = Context.getObjCIdType();
4152 } else if (!(compositeType =
4153 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4154 ;
4155 else {
4156 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4157 << LHSTy << RHSTy
4158 << LHS->getSourceRange() << RHS->getSourceRange();
4159 QualType incompatTy = Context.getObjCIdType();
4160 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4161 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4162 return incompatTy;
4163 }
4164 // The object pointer types are compatible.
4165 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4166 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
4167 return compositeType;
4168 }
4169 // Check Objective-C object pointer types and 'void *'
4170 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4171 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4172 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4173 QualType destPointee
4174 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4175 QualType destType = Context.getPointerType(destPointee);
4176 // Add qualifiers if necessary.
4177 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4178 // Promote to void*.
4179 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4180 return destType;
4181 }
4182 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4183 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4184 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4185 QualType destPointee
4186 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4187 QualType destType = Context.getPointerType(destPointee);
4188 // Add qualifiers if necessary.
4189 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4190 // Promote to void*.
4191 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4192 return destType;
4193 }
4194 return QualType();
4195}
4196
Steve Naroff83895f72007-09-16 03:34:24 +00004197/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004198/// in the case of a the GNU conditional expr extension.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004199Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4200 SourceLocation ColonLoc,
4201 ExprArg Cond, ExprArg LHS,
4202 ExprArg RHS) {
4203 Expr *CondExpr = (Expr *) Cond.get();
4204 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner2ab40a62007-11-26 01:40:58 +00004205
4206 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4207 // was the condition.
4208 bool isLHSNull = LHSExpr == 0;
4209 if (isLHSNull)
4210 LHSExpr = CondExpr;
Sebastian Redlb5d49352009-01-19 22:31:54 +00004211
4212 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattnerdaaa9f22007-07-16 21:39:03 +00004213 RHSExpr, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00004214 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004215 return ExprError();
4216
4217 Cond.release();
4218 LHS.release();
4219 RHS.release();
Douglas Gregor7e112b02009-08-26 14:37:04 +00004220 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Narofff6009ed2009-01-21 00:14:39 +00004221 isLHSNull ? 0 : LHSExpr,
Douglas Gregor7e112b02009-08-26 14:37:04 +00004222 ColonLoc, RHSExpr, result));
Chris Lattnere168f762006-11-10 05:29:30 +00004223}
4224
Steve Naroff3f597292007-05-11 22:18:03 +00004225// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00004226// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00004227// routine is it effectively iqnores the qualifiers on the top level pointee.
4228// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4229// FIXME: add a couple examples in this comment.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004230Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00004231Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Steve Naroff3f597292007-05-11 22:18:03 +00004232 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004233
David Chisnall9f57c292009-08-17 16:35:33 +00004234 if ((lhsType->isObjCClassType() &&
4235 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4236 (rhsType->isObjCClassType() &&
4237 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4238 return Compatible;
4239 }
4240
Steve Naroff1f4d7272007-05-11 04:00:31 +00004241 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004242 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4243 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004244
Steve Naroff1f4d7272007-05-11 04:00:31 +00004245 // make sure we operate on the canonical type
Chris Lattner574dee62008-07-26 22:17:49 +00004246 lhptee = Context.getCanonicalType(lhptee);
4247 rhptee = Context.getCanonicalType(rhptee);
Steve Naroff1f4d7272007-05-11 04:00:31 +00004248
Chris Lattner9bad62c2008-01-04 18:04:52 +00004249 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004250
4251 // C99 6.5.16.1p1: This following citation is common to constraints
4252 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4253 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianece85822009-02-17 18:27:45 +00004254 // FIXME: Handle ExtQualType
Douglas Gregor9a657932008-10-21 23:43:52 +00004255 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner9bad62c2008-01-04 18:04:52 +00004256 ConvTy = CompatiblePointerDiscardsQualifiers;
Steve Naroff3f597292007-05-11 22:18:03 +00004257
Mike Stump4e1f26a2009-02-19 03:04:26 +00004258 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4259 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00004260 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00004261 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004262 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004263 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004264
Chris Lattner0a788432008-01-03 22:56:36 +00004265 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004266 assert(rhptee->isFunctionType());
4267 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004268 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004269
Chris Lattner0a788432008-01-03 22:56:36 +00004270 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004271 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004272 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00004273
4274 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004275 assert(lhptee->isFunctionType());
4276 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004277 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004278 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00004279 // unqualified versions of compatible types, ...
Eli Friedman80160bd2009-03-22 23:59:44 +00004280 lhptee = lhptee.getUnqualifiedType();
4281 rhptee = rhptee.getUnqualifiedType();
4282 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4283 // Check if the pointee types are compatible ignoring the sign.
4284 // We explicitly check for char so that we catch "char" vs
4285 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00004286 if (lhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004287 lhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00004288 else if (lhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004289 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00004290
4291 if (rhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004292 rhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00004293 else if (rhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004294 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00004295
Eli Friedman80160bd2009-03-22 23:59:44 +00004296 if (lhptee == rhptee) {
4297 // Types are compatible ignoring the sign. Qualifier incompatibility
4298 // takes priority over sign incompatibility because the sign
4299 // warning can be disabled.
4300 if (ConvTy != Compatible)
4301 return ConvTy;
4302 return IncompatiblePointerSign;
4303 }
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004304
4305 // If we are a multi-level pointer, it's possible that our issue is simply
4306 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4307 // the eventual target type is the same and the pointers have the same
4308 // level of indirection, this must be the issue.
4309 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4310 do {
4311 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4312 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
4313
4314 lhptee = Context.getCanonicalType(lhptee);
4315 rhptee = Context.getCanonicalType(rhptee);
4316 } while (lhptee->isPointerType() && rhptee->isPointerType());
4317
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004318 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Alexis Hunt6f3de502009-11-08 07:46:34 +00004319 return IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004320 }
4321
Eli Friedman80160bd2009-03-22 23:59:44 +00004322 // General pointer incompatibility takes priority over qualifiers.
Mike Stump11289f42009-09-09 15:08:12 +00004323 return IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00004324 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00004325 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00004326}
4327
Steve Naroff081c7422008-09-04 15:10:53 +00004328/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4329/// block pointer types are compatible or whether a block and normal pointer
4330/// are compatible. It is more restrict than comparing two function pointer
4331// types.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004332Sema::AssignConvertType
4333Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff081c7422008-09-04 15:10:53 +00004334 QualType rhsType) {
4335 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004336
Steve Naroff081c7422008-09-04 15:10:53 +00004337 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004338 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4339 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004340
Steve Naroff081c7422008-09-04 15:10:53 +00004341 // make sure we operate on the canonical type
4342 lhptee = Context.getCanonicalType(lhptee);
4343 rhptee = Context.getCanonicalType(rhptee);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004344
Steve Naroff081c7422008-09-04 15:10:53 +00004345 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004346
Steve Naroff081c7422008-09-04 15:10:53 +00004347 // For blocks we enforce that qualifiers are identical.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004348 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff081c7422008-09-04 15:10:53 +00004349 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004350
Eli Friedmana6638ca2009-06-08 05:08:54 +00004351 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump4e1f26a2009-02-19 03:04:26 +00004352 return IncompatibleBlockPointer;
Steve Naroff081c7422008-09-04 15:10:53 +00004353 return ConvTy;
4354}
4355
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004356/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4357/// for assignment compatibility.
4358Sema::AssignConvertType
4359Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4360 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
4361 return Compatible;
4362 QualType lhptee =
4363 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4364 QualType rhptee =
4365 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4366 // make sure we operate on the canonical type
4367 lhptee = Context.getCanonicalType(lhptee);
4368 rhptee = Context.getCanonicalType(rhptee);
4369 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4370 return CompatiblePointerDiscardsQualifiers;
4371
4372 if (Context.typesAreCompatible(lhsType, rhsType))
4373 return Compatible;
4374 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4375 return IncompatibleObjCQualifiedId;
4376 return IncompatiblePointer;
4377}
4378
Mike Stump4e1f26a2009-02-19 03:04:26 +00004379/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4380/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00004381/// pointers. Here are some objectionable examples that GCC considers warnings:
4382///
4383/// int a, *pint;
4384/// short *pshort;
4385/// struct foo *pfoo;
4386///
4387/// pint = pshort; // warning: assignment from incompatible pointer type
4388/// a = pint; // warning: assignment makes integer from pointer without a cast
4389/// pint = a; // warning: assignment makes pointer from integer without a cast
4390/// pint = pfoo; // warning: assignment from incompatible pointer type
4391///
4392/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00004393/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00004394///
Chris Lattner9bad62c2008-01-04 18:04:52 +00004395Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00004396Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnera52c2f22008-01-04 23:18:45 +00004397 // Get canonical types. We're not formatting these types, just comparing
4398 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00004399 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4400 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00004401
4402 if (lhsType == rhsType)
Chris Lattnerf5c973d2008-01-07 17:51:46 +00004403 return Compatible; // Common case: fast path an exact match.
Steve Naroff44fd8ff2007-07-24 21:46:40 +00004404
David Chisnall9f57c292009-08-17 16:35:33 +00004405 if ((lhsType->isObjCClassType() &&
4406 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4407 (rhsType->isObjCClassType() &&
4408 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4409 return Compatible;
4410 }
4411
Douglas Gregor6b754842008-10-28 00:22:11 +00004412 // If the left-hand side is a reference type, then we are in a
4413 // (rare!) case where we've allowed the use of references in C,
4414 // e.g., as a parameter type in a built-in function. In this case,
4415 // just make sure that the type referenced is compatible with the
4416 // right-hand side type. The caller is responsible for adjusting
4417 // lhsType so that the resulting expression does not have reference
4418 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004419 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor6b754842008-10-28 00:22:11 +00004420 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson24ebce62007-10-12 23:56:29 +00004421 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004422 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00004423 }
Nate Begemanbd956c42009-06-28 02:36:38 +00004424 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4425 // to the same ExtVector type.
4426 if (lhsType->isExtVectorType()) {
4427 if (rhsType->isExtVectorType())
4428 return lhsType == rhsType ? Compatible : Incompatible;
4429 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
4430 return Compatible;
4431 }
Mike Stump11289f42009-09-09 15:08:12 +00004432
Nate Begeman191a6b12008-07-14 18:02:46 +00004433 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004434 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump4e1f26a2009-02-19 03:04:26 +00004435 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begeman191a6b12008-07-14 18:02:46 +00004436 // no bits are changed but the result type is different.
Chris Lattner881a2122008-01-04 23:32:24 +00004437 if (getLangOptions().LaxVectorConversions &&
4438 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004439 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004440 return IncompatibleVectors;
Chris Lattner881a2122008-01-04 23:32:24 +00004441 }
4442 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004443 }
Eli Friedman3360d892008-05-30 18:07:22 +00004444
Chris Lattner881a2122008-01-04 23:32:24 +00004445 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Steve Naroff98cf3e92007-06-06 18:38:38 +00004446 return Compatible;
Eli Friedman3360d892008-05-30 18:07:22 +00004447
Chris Lattnerec646832008-04-07 06:49:41 +00004448 if (isa<PointerType>(lhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00004449 if (rhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00004450 return IntToPointer;
Eli Friedman3360d892008-05-30 18:07:22 +00004451
Chris Lattnerec646832008-04-07 06:49:41 +00004452 if (isa<PointerType>(rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004453 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004454
Steve Naroffaccc4882009-07-20 17:56:53 +00004455 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004456 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004457 if (lhsType->isVoidPointerType()) // an exception to the rule.
4458 return Compatible;
4459 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004460 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004461 if (rhsType->getAs<BlockPointerType>()) {
4462 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004463 return Compatible;
Steve Naroff32d072c2008-09-29 18:10:17 +00004464
4465 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004466 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00004467 return Compatible;
4468 }
Steve Naroff081c7422008-09-04 15:10:53 +00004469 return Incompatible;
4470 }
4471
4472 if (isa<BlockPointerType>(lhsType)) {
4473 if (rhsType->isIntegerType())
Eli Friedman8163b7a2009-02-25 04:20:42 +00004474 return IntToBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004475
Steve Naroff32d072c2008-09-29 18:10:17 +00004476 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004477 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00004478 return Compatible;
4479
Steve Naroff081c7422008-09-04 15:10:53 +00004480 if (rhsType->isBlockPointerType())
4481 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004482
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004483 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff081c7422008-09-04 15:10:53 +00004484 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004485 return Compatible;
Steve Naroff081c7422008-09-04 15:10:53 +00004486 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00004487 return Incompatible;
4488 }
4489
Steve Naroff7cae42b2009-07-10 23:34:53 +00004490 if (isa<ObjCObjectPointerType>(lhsType)) {
4491 if (rhsType->isIntegerType())
4492 return IntToPointer;
Mike Stump11289f42009-09-09 15:08:12 +00004493
Steve Naroffaccc4882009-07-20 17:56:53 +00004494 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004495 if (isa<PointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004496 if (rhsType->isVoidPointerType()) // an exception to the rule.
4497 return Compatible;
4498 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004499 }
4500 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004501 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004502 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004503 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004504 if (RHSPT->getPointeeType()->isVoidType())
4505 return Compatible;
4506 }
4507 // Treat block pointers as objects.
4508 if (rhsType->isBlockPointerType())
4509 return Compatible;
4510 return Incompatible;
4511 }
Chris Lattnerec646832008-04-07 06:49:41 +00004512 if (isa<PointerType>(rhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00004513 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman3360d892008-05-30 18:07:22 +00004514 if (lhsType == Context.BoolTy)
4515 return Compatible;
4516
4517 if (lhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00004518 return PointerToInt;
Steve Naroff98cf3e92007-06-06 18:38:38 +00004519
Mike Stump4e1f26a2009-02-19 03:04:26 +00004520 if (isa<PointerType>(lhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004521 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004522
4523 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004524 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004525 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004526 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004527 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004528 if (isa<ObjCObjectPointerType>(rhsType)) {
4529 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4530 if (lhsType == Context.BoolTy)
4531 return Compatible;
4532
4533 if (lhsType->isIntegerType())
4534 return PointerToInt;
4535
Steve Naroffaccc4882009-07-20 17:56:53 +00004536 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004537 if (isa<PointerType>(lhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004538 if (lhsType->isVoidPointerType()) // an exception to the rule.
4539 return Compatible;
4540 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004541 }
4542 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004543 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004544 return Compatible;
4545 return Incompatible;
4546 }
Eli Friedman3360d892008-05-30 18:07:22 +00004547
Chris Lattnera52c2f22008-01-04 23:18:45 +00004548 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattnerec646832008-04-07 06:49:41 +00004549 if (Context.typesAreCompatible(lhsType, rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004550 return Compatible;
Bill Wendling216423b2007-05-30 06:30:29 +00004551 }
Steve Naroff98cf3e92007-06-06 18:38:38 +00004552 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00004553}
4554
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004555/// \brief Constructs a transparent union from an expression that is
4556/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00004557static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004558 QualType UnionType, FieldDecl *Field) {
4559 // Build an initializer list that designates the appropriate member
4560 // of the transparent union.
4561 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
4562 &E, 1,
4563 SourceLocation());
4564 Initializer->setType(UnionType);
4565 Initializer->setInitializedFieldInUnion(Field);
4566
4567 // Build a compound literal constructing a value of the transparent
4568 // union type from this initializer list.
4569 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
4570 false);
4571}
4572
4573Sema::AssignConvertType
4574Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4575 QualType FromType = rExpr->getType();
4576
Mike Stump11289f42009-09-09 15:08:12 +00004577 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004578 // transparent_union GCC extension.
4579 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004580 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004581 return Incompatible;
4582
4583 // The field to initialize within the transparent union.
4584 RecordDecl *UD = UT->getDecl();
4585 FieldDecl *InitField = 0;
4586 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004587 for (RecordDecl::field_iterator it = UD->field_begin(),
4588 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004589 it != itend; ++it) {
4590 if (it->getType()->isPointerType()) {
4591 // If the transparent union contains a pointer type, we allow:
4592 // 1) void pointer
4593 // 2) null pointer constant
4594 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004595 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004596 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004597 InitField = *it;
4598 break;
4599 }
Mike Stump11289f42009-09-09 15:08:12 +00004600
Douglas Gregor56751b52009-09-25 04:25:58 +00004601 if (rExpr->isNullPointerConstant(Context,
4602 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004603 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004604 InitField = *it;
4605 break;
4606 }
4607 }
4608
4609 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4610 == Compatible) {
4611 InitField = *it;
4612 break;
4613 }
4614 }
4615
4616 if (!InitField)
4617 return Incompatible;
4618
4619 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4620 return Compatible;
4621}
4622
Chris Lattner9bad62c2008-01-04 18:04:52 +00004623Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004624Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00004625 if (getLangOptions().CPlusPlus) {
4626 if (!lhsType->isRecordType()) {
4627 // C++ 5.17p3: If the left operand is not of class type, the
4628 // expression is implicitly converted (C++ 4) to the
4629 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00004630 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
4631 "assigning"))
Douglas Gregor9a657932008-10-21 23:43:52 +00004632 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00004633 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00004634 }
4635
4636 // FIXME: Currently, we fall through and treat C++ classes like C
4637 // structures.
4638 }
4639
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004640 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4641 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00004642 if ((lhsType->isPointerType() ||
4643 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00004644 lhsType->isBlockPointerType())
Douglas Gregor56751b52009-09-25 04:25:58 +00004645 && rExpr->isNullPointerConstant(Context,
4646 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004647 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004648 return Compatible;
4649 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004650
Chris Lattnere6dcd502007-10-16 02:55:40 +00004651 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004652 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00004653 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004654 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00004655 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00004656 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00004657 if (!lhsType->isReferenceType())
4658 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004659
Chris Lattner9bad62c2008-01-04 18:04:52 +00004660 Sema::AssignConvertType result =
4661 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00004662
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004663 // C99 6.5.16.1p2: The value of the right operand is converted to the
4664 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00004665 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4666 // so that we can use references in built-in functions even in C.
4667 // The getNonReferenceType() call makes sure that the resulting expression
4668 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004669 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman06ed2a52009-10-20 08:27:19 +00004670 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4671 CastExpr::CK_Unknown);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004672 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004673}
4674
Chris Lattner326f7572008-11-18 01:30:42 +00004675QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00004676 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00004677 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004678 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00004679 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00004680}
4681
Mike Stump4e1f26a2009-02-19 03:04:26 +00004682inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff7a5af782007-07-13 16:58:59 +00004683 Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00004684 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004685 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00004686 QualType lhsType =
4687 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4688 QualType rhsType =
4689 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004690
Nate Begeman191a6b12008-07-14 18:02:46 +00004691 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004692 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00004693 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00004694
Nate Begeman191a6b12008-07-14 18:02:46 +00004695 // Handle the case of a vector & extvector type of the same size and element
4696 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004697 if (getLangOptions().LaxVectorConversions) {
4698 // FIXME: Should we warn here?
John McCall9dd450b2009-09-21 23:43:11 +00004699 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4700 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begeman191a6b12008-07-14 18:02:46 +00004701 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004702 LV->getNumElements() == RV->getNumElements()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004703 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004704 }
4705 }
4706 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004707
Nate Begemanbd956c42009-06-28 02:36:38 +00004708 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4709 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4710 bool swapped = false;
4711 if (rhsType->isExtVectorType()) {
4712 swapped = true;
4713 std::swap(rex, lex);
4714 std::swap(rhsType, lhsType);
4715 }
Mike Stump11289f42009-09-09 15:08:12 +00004716
Nate Begeman886448d2009-06-28 19:12:57 +00004717 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00004718 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00004719 QualType EltTy = LV->getElementType();
4720 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4721 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004722 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00004723 if (swapped) std::swap(rex, lex);
4724 return lhsType;
4725 }
4726 }
4727 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4728 rhsType->isRealFloatingType()) {
4729 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004730 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00004731 if (swapped) std::swap(rex, lex);
4732 return lhsType;
4733 }
Nate Begeman330aaa72007-12-30 02:59:45 +00004734 }
4735 }
Mike Stump11289f42009-09-09 15:08:12 +00004736
Nate Begeman886448d2009-06-28 19:12:57 +00004737 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00004738 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004739 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004740 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00004741 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00004742}
4743
Steve Naroff218bc2b2007-05-04 21:54:46 +00004744inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004745 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00004746 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00004747 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004748
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004749 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004750
Steve Naroffdbd9e892007-07-17 00:58:39 +00004751 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004752 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00004753 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004754}
4755
Steve Naroff218bc2b2007-05-04 21:54:46 +00004756inline QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004757 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00004758 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4759 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4760 return CheckVectorOperands(Loc, lex, rex);
4761 return InvalidOperands(Loc, lex, rex);
4762 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004763
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004764 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004765
Steve Naroffdbd9e892007-07-17 00:58:39 +00004766 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004767 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00004768 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00004769}
4770
4771inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00004772 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004773 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4774 QualType compType = CheckVectorOperands(Loc, lex, rex);
4775 if (CompLHSTy) *CompLHSTy = compType;
4776 return compType;
4777 }
Steve Naroff7a5af782007-07-13 16:58:59 +00004778
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004779 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00004780
Steve Naroffe4718892007-04-27 18:30:00 +00004781 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004782 if (lex->getType()->isArithmeticType() &&
4783 rex->getType()->isArithmeticType()) {
4784 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004785 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004786 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00004787
Eli Friedman8e122982008-05-18 18:08:51 +00004788 // Put any potential pointer into PExp
4789 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00004790 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00004791 std::swap(PExp, IExp);
4792
Steve Naroff6b712a72009-07-14 18:25:06 +00004793 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004794
Eli Friedman8e122982008-05-18 18:08:51 +00004795 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004796 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004797
Chris Lattner12bdebb2009-04-24 23:50:08 +00004798 // Check for arithmetic on pointers to incomplete types.
4799 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004800 if (getLangOptions().CPlusPlus) {
4801 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00004802 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00004803 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00004804 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004805
4806 // GNU extension: arithmetic on pointer to void
4807 Diag(Loc, diag::ext_gnu_void_ptr)
4808 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00004809 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004810 if (getLangOptions().CPlusPlus) {
4811 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4812 << lex->getType() << lex->getSourceRange();
4813 return QualType();
4814 }
4815
4816 // GNU extension: arithmetic on pointer to function
4817 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4818 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00004819 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004820 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00004821 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00004822 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004823 PExp->getType()->isObjCObjectPointerType()) &&
4824 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00004825 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4826 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00004827 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004828 return QualType();
4829 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00004830 // Diagnose bad cases where we step over interface counts.
4831 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4832 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4833 << PointeeTy << PExp->getSourceRange();
4834 return QualType();
4835 }
Mike Stump11289f42009-09-09 15:08:12 +00004836
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004837 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00004838 QualType LHSTy = Context.isPromotableBitField(lex);
4839 if (LHSTy.isNull()) {
4840 LHSTy = lex->getType();
4841 if (LHSTy->isPromotableIntegerType())
4842 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00004843 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004844 *CompLHSTy = LHSTy;
4845 }
Eli Friedman8e122982008-05-18 18:08:51 +00004846 return PExp->getType();
4847 }
4848 }
4849
Chris Lattner326f7572008-11-18 01:30:42 +00004850 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004851}
4852
Chris Lattner2a3569b2008-04-07 05:30:13 +00004853// C99 6.5.6
4854QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004855 SourceLocation Loc, QualType* CompLHSTy) {
4856 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4857 QualType compType = CheckVectorOperands(Loc, lex, rex);
4858 if (CompLHSTy) *CompLHSTy = compType;
4859 return compType;
4860 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004861
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004862 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004863
Chris Lattner4d62f422007-12-09 21:53:25 +00004864 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004865
Chris Lattner4d62f422007-12-09 21:53:25 +00004866 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00004867 if (lex->getType()->isArithmeticType()
4868 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004869 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004870 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004871 }
Mike Stump11289f42009-09-09 15:08:12 +00004872
Chris Lattner4d62f422007-12-09 21:53:25 +00004873 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00004874 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00004875 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004876
Douglas Gregorac1fb652009-03-24 19:52:54 +00004877 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00004878
Douglas Gregorac1fb652009-03-24 19:52:54 +00004879 bool ComplainAboutVoid = false;
4880 Expr *ComplainAboutFunc = 0;
4881 if (lpointee->isVoidType()) {
4882 if (getLangOptions().CPlusPlus) {
4883 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4884 << lex->getSourceRange() << rex->getSourceRange();
4885 return QualType();
4886 }
4887
4888 // GNU C extension: arithmetic on pointer to void
4889 ComplainAboutVoid = true;
4890 } else if (lpointee->isFunctionType()) {
4891 if (getLangOptions().CPlusPlus) {
4892 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004893 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00004894 return QualType();
4895 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004896
4897 // GNU C extension: arithmetic on pointer to function
4898 ComplainAboutFunc = lex;
4899 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00004900 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00004901 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00004902 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00004903 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00004904 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004905
Chris Lattner12bdebb2009-04-24 23:50:08 +00004906 // Diagnose bad cases where we step over interface counts.
4907 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4908 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4909 << lpointee << lex->getSourceRange();
4910 return QualType();
4911 }
Mike Stump11289f42009-09-09 15:08:12 +00004912
Chris Lattner4d62f422007-12-09 21:53:25 +00004913 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00004914 if (rex->getType()->isIntegerType()) {
4915 if (ComplainAboutVoid)
4916 Diag(Loc, diag::ext_gnu_void_ptr)
4917 << lex->getSourceRange() << rex->getSourceRange();
4918 if (ComplainAboutFunc)
4919 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00004920 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00004921 << ComplainAboutFunc->getSourceRange();
4922
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004923 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004924 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00004925 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004926
Chris Lattner4d62f422007-12-09 21:53:25 +00004927 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004928 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00004929 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004930
Douglas Gregorac1fb652009-03-24 19:52:54 +00004931 // RHS must be a completely-type object type.
4932 // Handle the GNU void* extension.
4933 if (rpointee->isVoidType()) {
4934 if (getLangOptions().CPlusPlus) {
4935 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4936 << lex->getSourceRange() << rex->getSourceRange();
4937 return QualType();
4938 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004939
Douglas Gregorac1fb652009-03-24 19:52:54 +00004940 ComplainAboutVoid = true;
4941 } else if (rpointee->isFunctionType()) {
4942 if (getLangOptions().CPlusPlus) {
4943 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004944 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00004945 return QualType();
4946 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004947
4948 // GNU extension: arithmetic on pointer to function
4949 if (!ComplainAboutFunc)
4950 ComplainAboutFunc = rex;
4951 } else if (!rpointee->isDependentType() &&
4952 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00004953 PDiag(diag::err_typecheck_sub_ptr_object)
4954 << rex->getSourceRange()
4955 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00004956 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004957
Eli Friedman168fe152009-05-16 13:54:38 +00004958 if (getLangOptions().CPlusPlus) {
4959 // Pointee types must be the same: C++ [expr.add]
4960 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4961 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4962 << lex->getType() << rex->getType()
4963 << lex->getSourceRange() << rex->getSourceRange();
4964 return QualType();
4965 }
4966 } else {
4967 // Pointee types must be compatible C99 6.5.6p3
4968 if (!Context.typesAreCompatible(
4969 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4970 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4971 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4972 << lex->getType() << rex->getType()
4973 << lex->getSourceRange() << rex->getSourceRange();
4974 return QualType();
4975 }
Chris Lattner4d62f422007-12-09 21:53:25 +00004976 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004977
Douglas Gregorac1fb652009-03-24 19:52:54 +00004978 if (ComplainAboutVoid)
4979 Diag(Loc, diag::ext_gnu_void_ptr)
4980 << lex->getSourceRange() << rex->getSourceRange();
4981 if (ComplainAboutFunc)
4982 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00004983 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00004984 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004985
4986 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004987 return Context.getPointerDiffType();
4988 }
4989 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004990
Chris Lattner326f7572008-11-18 01:30:42 +00004991 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00004992}
4993
Chris Lattner2a3569b2008-04-07 05:30:13 +00004994// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00004995QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattner2a3569b2008-04-07 05:30:13 +00004996 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00004997 // C99 6.5.7p2: Each of the operands shall have integer type.
4998 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner326f7572008-11-18 01:30:42 +00004999 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005000
Nate Begemane46ee9a2009-10-25 02:26:48 +00005001 // Vector shifts promote their scalar inputs to vector type.
5002 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5003 return CheckVectorOperands(Loc, lex, rex);
5004
Chris Lattner5c11c412007-12-12 05:47:28 +00005005 // Shifts don't perform usual arithmetic conversions, they just do integer
5006 // promotions on each operand. C99 6.5.7p3
Eli Friedman629ffb92009-08-20 04:21:42 +00005007 QualType LHSTy = Context.isPromotableBitField(lex);
5008 if (LHSTy.isNull()) {
5009 LHSTy = lex->getType();
5010 if (LHSTy->isPromotableIntegerType())
5011 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005012 }
Chris Lattner3c133402007-12-13 07:28:16 +00005013 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +00005014 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005015
Chris Lattner5c11c412007-12-12 05:47:28 +00005016 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005017
Ryan Flynnf53fab82009-08-07 16:20:20 +00005018 // Sanity-check shift operands
5019 llvm::APSInt Right;
5020 // Check right/shifter operand
Daniel Dunbar687fa862009-09-17 06:31:27 +00005021 if (!rex->isValueDependent() &&
5022 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn2f085712009-08-08 19:18:23 +00005023 if (Right.isNegative())
Ryan Flynnf53fab82009-08-07 16:20:20 +00005024 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
5025 else {
5026 llvm::APInt LeftBits(Right.getBitWidth(),
5027 Context.getTypeSize(lex->getType()));
5028 if (Right.uge(LeftBits))
5029 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
5030 }
5031 }
5032
Chris Lattner5c11c412007-12-12 05:47:28 +00005033 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005034 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005035}
5036
John McCall99ce6bf2009-11-06 08:49:08 +00005037/// \brief Implements -Wsign-compare.
5038///
5039/// \param lex the left-hand expression
5040/// \param rex the right-hand expression
5041/// \param OpLoc the location of the joining operator
John McCalle46fd852009-11-06 08:53:51 +00005042/// \param Equality whether this is an "equality-like" join, which
5043/// suppresses the warning in some cases
John McCall1fa36b72009-11-05 09:23:39 +00005044void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
John McCall99ce6bf2009-11-06 08:49:08 +00005045 const PartialDiagnostic &PD, bool Equality) {
John McCalle2c91e62009-11-06 18:16:06 +00005046 // Don't warn if we're in an unevaluated context.
Douglas Gregorff790f12009-11-26 00:44:06 +00005047 if (ExprEvalContexts.back().Context == Unevaluated)
John McCalle2c91e62009-11-06 18:16:06 +00005048 return;
5049
John McCall644a4182009-11-05 00:40:04 +00005050 QualType lt = lex->getType(), rt = rex->getType();
5051
5052 // Only warn if both operands are integral.
5053 if (!lt->isIntegerType() || !rt->isIntegerType())
5054 return;
5055
Sebastian Redl0b7c85f2009-11-05 21:09:23 +00005056 // If either expression is value-dependent, don't warn. We'll get another
5057 // chance at instantiation time.
5058 if (lex->isValueDependent() || rex->isValueDependent())
5059 return;
5060
John McCall644a4182009-11-05 00:40:04 +00005061 // The rule is that the signed operand becomes unsigned, so isolate the
5062 // signed operand.
John McCall99ce6bf2009-11-06 08:49:08 +00005063 Expr *signedOperand, *unsignedOperand;
John McCall644a4182009-11-05 00:40:04 +00005064 if (lt->isSignedIntegerType()) {
5065 if (rt->isSignedIntegerType()) return;
5066 signedOperand = lex;
John McCall99ce6bf2009-11-06 08:49:08 +00005067 unsignedOperand = rex;
John McCall644a4182009-11-05 00:40:04 +00005068 } else {
5069 if (!rt->isSignedIntegerType()) return;
5070 signedOperand = rex;
John McCall99ce6bf2009-11-06 08:49:08 +00005071 unsignedOperand = lex;
John McCall644a4182009-11-05 00:40:04 +00005072 }
5073
John McCall99ce6bf2009-11-06 08:49:08 +00005074 // If the unsigned type is strictly smaller than the signed type,
John McCalle46fd852009-11-06 08:53:51 +00005075 // then (1) the result type will be signed and (2) the unsigned
5076 // value will fit fully within the signed type, and thus the result
John McCall99ce6bf2009-11-06 08:49:08 +00005077 // of the comparison will be exact.
5078 if (Context.getIntWidth(signedOperand->getType()) >
5079 Context.getIntWidth(unsignedOperand->getType()))
5080 return;
5081
John McCall644a4182009-11-05 00:40:04 +00005082 // If the value is a non-negative integer constant, then the
5083 // signed->unsigned conversion won't change it.
5084 llvm::APSInt value;
John McCall1fa36b72009-11-05 09:23:39 +00005085 if (signedOperand->isIntegerConstantExpr(value, Context)) {
John McCall644a4182009-11-05 00:40:04 +00005086 assert(value.isSigned() && "result of signed expression not signed");
5087
5088 if (value.isNonNegative())
5089 return;
5090 }
5091
John McCall99ce6bf2009-11-06 08:49:08 +00005092 if (Equality) {
5093 // For (in)equality comparisons, if the unsigned operand is a
John McCalle46fd852009-11-06 08:53:51 +00005094 // constant which cannot collide with a overflowed signed operand,
5095 // then reinterpreting the signed operand as unsigned will not
5096 // change the result of the comparison.
John McCall99ce6bf2009-11-06 08:49:08 +00005097 if (unsignedOperand->isIntegerConstantExpr(value, Context)) {
5098 assert(!value.isSigned() && "result of unsigned expression is signed");
5099
5100 // 2's complement: test the top bit.
5101 if (value.isNonNegative())
5102 return;
5103 }
5104 }
5105
John McCall1fa36b72009-11-05 09:23:39 +00005106 Diag(OpLoc, PD)
John McCall644a4182009-11-05 00:40:04 +00005107 << lex->getType() << rex->getType()
5108 << lex->getSourceRange() << rex->getSourceRange();
5109}
5110
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005111// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00005112QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005113 unsigned OpaqueOpc, bool isRelational) {
5114 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5115
Chris Lattner9a152e22009-12-05 05:40:13 +00005116 // Handle vector comparisons separately.
Nate Begeman191a6b12008-07-14 18:02:46 +00005117 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005118 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005119
John McCall99ce6bf2009-11-06 08:49:08 +00005120 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
5121 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall644a4182009-11-05 00:40:04 +00005122
Chris Lattnerb620c342007-08-26 01:18:55 +00005123 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff47fea352007-08-10 18:26:40 +00005124 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5125 UsualArithmeticConversions(lex, rex);
5126 else {
5127 UsualUnaryConversions(lex);
5128 UsualUnaryConversions(rex);
5129 }
Steve Naroff31090012007-07-16 21:54:35 +00005130 QualType lType = lex->getType();
5131 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005132
Mike Stumpf70bcf72009-05-07 18:43:07 +00005133 if (!lType->isFloatingType()
5134 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00005135 // For non-floating point types, check for self-comparisons of the form
5136 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5137 // often indicate logic errors in the program.
Mike Stump11289f42009-09-09 15:08:12 +00005138 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenekde9e9682009-03-20 19:57:37 +00005139 // from macro expansions, and are usually quite deliberate.
Chris Lattner222b8bd2009-03-08 19:39:53 +00005140 Expr *LHSStripped = lex->IgnoreParens();
5141 Expr *RHSStripped = rex->IgnoreParens();
5142 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
5143 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenek9ffbe412009-03-20 18:35:45 +00005144 if (DRL->getDecl() == DRR->getDecl() &&
5145 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump4e1f26a2009-02-19 03:04:26 +00005146 Diag(Loc, diag::warn_selfcomparison);
Mike Stump11289f42009-09-09 15:08:12 +00005147
Chris Lattner222b8bd2009-03-08 19:39:53 +00005148 if (isa<CastExpr>(LHSStripped))
5149 LHSStripped = LHSStripped->IgnoreParenCasts();
5150 if (isa<CastExpr>(RHSStripped))
5151 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005152
Chris Lattner222b8bd2009-03-08 19:39:53 +00005153 // Warn about comparisons against a string constant (unless the other
5154 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005155 Expr *literalString = 0;
5156 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00005157 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005158 !RHSStripped->isNullPointerConstant(Context,
5159 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005160 literalString = lex;
5161 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00005162 } else if ((isa<StringLiteral>(RHSStripped) ||
5163 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005164 !LHSStripped->isNullPointerConstant(Context,
5165 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005166 literalString = rex;
5167 literalStringStripped = RHSStripped;
5168 }
5169
5170 if (literalString) {
5171 std::string resultComparison;
5172 switch (Opc) {
5173 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5174 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5175 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5176 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5177 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5178 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5179 default: assert(false && "Invalid comparison operator");
5180 }
5181 Diag(Loc, diag::warn_stringcompare)
5182 << isa<ObjCEncodeExpr>(literalStringStripped)
5183 << literalString->getSourceRange()
Douglas Gregor170512f2009-04-01 23:51:29 +00005184 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
5185 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
5186 "strcmp(")
5187 << CodeModificationHint::CreateInsertion(
5188 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005189 resultComparison);
5190 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00005191 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005192
Douglas Gregorca63811b2008-11-19 03:25:36 +00005193 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner9a152e22009-12-05 05:40:13 +00005194 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregorca63811b2008-11-19 03:25:36 +00005195
Chris Lattnerb620c342007-08-26 01:18:55 +00005196 if (isRelational) {
5197 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00005198 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00005199 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00005200 // Check for comparisons of floating point operands using != and ==.
Chris Lattner9a152e22009-12-05 05:40:13 +00005201 if (lType->isFloatingType() && rType->isFloatingType())
Chris Lattner326f7572008-11-18 01:30:42 +00005202 CheckFloatComparison(Loc,lex,rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005203
Chris Lattnerb620c342007-08-26 01:18:55 +00005204 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00005205 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00005206 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005207
Douglas Gregor56751b52009-09-25 04:25:58 +00005208 bool LHSIsNull = lex->isNullPointerConstant(Context,
5209 Expr::NPC_ValueDependentIsNull);
5210 bool RHSIsNull = rex->isNullPointerConstant(Context,
5211 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005212
Chris Lattnerb620c342007-08-26 01:18:55 +00005213 // All of the following pointer related warnings are GCC extensions, except
5214 // when handling null pointer constants. One day, we can consider making them
5215 // errors (when -pedantic-errors is enabled).
Steve Naroff808eb8f2007-08-27 04:08:11 +00005216 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00005217 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005218 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00005219 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005220 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00005221
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005222 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00005223 if (LCanPointeeTy == RCanPointeeTy)
5224 return ResultTy;
5225
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005226 // C++ [expr.rel]p2:
5227 // [...] Pointer conversions (4.10) and qualification
5228 // conversions (4.4) are performed on pointer operands (or on
5229 // a pointer operand and a null pointer constant) to bring
5230 // them to their composite pointer type. [...]
5231 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005232 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005233 // comparisons of pointers.
Douglas Gregorb8420462009-05-05 04:50:50 +00005234 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005235 if (T.isNull()) {
5236 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5237 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5238 return QualType();
5239 }
5240
Eli Friedman06ed2a52009-10-20 08:27:19 +00005241 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5242 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005243 return ResultTy;
5244 }
Eli Friedman16c209612009-08-23 00:27:47 +00005245 // C99 6.5.9p2 and C99 6.5.8p2
5246 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5247 RCanPointeeTy.getUnqualifiedType())) {
5248 // Valid unless a relational comparison of function pointers
5249 if (isRelational && LCanPointeeTy->isFunctionType()) {
5250 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5251 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5252 }
5253 } else if (!isRelational &&
5254 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5255 // Valid unless comparison between non-null pointer and function pointer
5256 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5257 && !LHSIsNull && !RHSIsNull) {
5258 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5259 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5260 }
5261 } else {
5262 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00005263 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005264 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00005265 }
Eli Friedman16c209612009-08-23 00:27:47 +00005266 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman06ed2a52009-10-20 08:27:19 +00005267 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005268 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00005269 }
Mike Stump11289f42009-09-09 15:08:12 +00005270
Sebastian Redl576fd422009-05-10 18:38:11 +00005271 if (getLangOptions().CPlusPlus) {
Mike Stump11289f42009-09-09 15:08:12 +00005272 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005273 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00005274 if (RHSIsNull &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005275 (lType->isPointerType() ||
5276 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00005277 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00005278 return ResultTy;
5279 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005280 if (LHSIsNull &&
5281 (rType->isPointerType() ||
5282 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00005283 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00005284 return ResultTy;
5285 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005286
5287 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00005288 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005289 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5290 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005291 // In addition, pointers to members can be compared, or a pointer to
5292 // member and a null pointer constant. Pointer to member conversions
5293 // (4.11) and qualification conversions (4.4) are performed to bring
5294 // them to a common type. If one operand is a null pointer constant,
5295 // the common type is the type of the other operand. Otherwise, the
5296 // common type is a pointer to member type similar (4.4) to the type
5297 // of one of the operands, with a cv-qualification signature (4.4)
5298 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005299 // types.
5300 QualType T = FindCompositePointerType(lex, rex);
5301 if (T.isNull()) {
5302 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5303 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5304 return QualType();
5305 }
Mike Stump11289f42009-09-09 15:08:12 +00005306
Eli Friedman06ed2a52009-10-20 08:27:19 +00005307 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5308 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005309 return ResultTy;
5310 }
Mike Stump11289f42009-09-09 15:08:12 +00005311
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005312 // Comparison of nullptr_t with itself.
Sebastian Redl576fd422009-05-10 18:38:11 +00005313 if (lType->isNullPtrType() && rType->isNullPtrType())
5314 return ResultTy;
5315 }
Mike Stump11289f42009-09-09 15:08:12 +00005316
Steve Naroff081c7422008-09-04 15:10:53 +00005317 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00005318 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005319 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5320 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005321
Steve Naroff081c7422008-09-04 15:10:53 +00005322 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00005323 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005324 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005325 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00005326 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005327 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005328 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00005329 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00005330 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00005331 if (!isRelational
5332 && ((lType->isBlockPointerType() && rType->isPointerType())
5333 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00005334 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005335 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00005336 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005337 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00005338 ->getPointeeType()->isVoidType())))
5339 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5340 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00005341 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005342 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005343 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00005344 }
Steve Naroff081c7422008-09-04 15:10:53 +00005345
Steve Naroff7cae42b2009-07-10 23:34:53 +00005346 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00005347 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005348 const PointerType *LPT = lType->getAs<PointerType>();
5349 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005350 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00005351 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005352 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00005353 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005354
Steve Naroff753567f2008-11-17 19:49:16 +00005355 if (!LPtrToVoid && !RPtrToVoid &&
5356 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005357 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005358 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00005359 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005360 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005361 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00005362 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005363 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005364 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005365 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5366 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00005367 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005368 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00005369 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00005370 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005371 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00005372 unsigned DiagID = 0;
5373 if (RHSIsNull) {
5374 if (isRelational)
5375 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5376 } else if (isRelational)
5377 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5378 else
5379 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00005380
Chris Lattnerd99bd522009-08-23 00:03:44 +00005381 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005382 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00005383 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00005384 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005385 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005386 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00005387 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005388 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00005389 unsigned DiagID = 0;
5390 if (LHSIsNull) {
5391 if (isRelational)
5392 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5393 } else if (isRelational)
5394 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5395 else
5396 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00005397
Chris Lattnerd99bd522009-08-23 00:03:44 +00005398 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005399 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00005400 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00005401 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005402 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005403 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00005404 }
Steve Naroff4b191572008-09-04 16:56:14 +00005405 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00005406 if (!isRelational && RHSIsNull
5407 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005408 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005409 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00005410 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00005411 if (!isRelational && LHSIsNull
5412 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005413 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005414 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00005415 }
Chris Lattner326f7572008-11-18 01:30:42 +00005416 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005417}
5418
Nate Begeman191a6b12008-07-14 18:02:46 +00005419/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00005420/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00005421/// like a scalar comparison, a vector comparison produces a vector of integer
5422/// types.
5423QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00005424 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00005425 bool isRelational) {
5426 // Check to make sure we're operating on vectors of the same type and width,
5427 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00005428 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00005429 if (vType.isNull())
5430 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005431
Nate Begeman191a6b12008-07-14 18:02:46 +00005432 QualType lType = lex->getType();
5433 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005434
Nate Begeman191a6b12008-07-14 18:02:46 +00005435 // For non-floating point types, check for self-comparisons of the form
5436 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5437 // often indicate logic errors in the program.
5438 if (!lType->isFloatingType()) {
5439 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5440 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5441 if (DRL->getDecl() == DRR->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005442 Diag(Loc, diag::warn_selfcomparison);
Nate Begeman191a6b12008-07-14 18:02:46 +00005443 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005444
Nate Begeman191a6b12008-07-14 18:02:46 +00005445 // Check for comparisons of floating point operands using != and ==.
5446 if (!isRelational && lType->isFloatingType()) {
5447 assert (rType->isFloatingType());
Chris Lattner326f7572008-11-18 01:30:42 +00005448 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00005449 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005450
Nate Begeman191a6b12008-07-14 18:02:46 +00005451 // Return the type for the comparison, which is the same as vector type for
5452 // integer vectors, or an integer type of identical size and number of
5453 // elements for floating point vectors.
5454 if (lType->isIntegerType())
5455 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005456
John McCall9dd450b2009-09-21 23:43:11 +00005457 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00005458 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005459 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00005460 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00005461 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005462 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5463
Mike Stump4e1f26a2009-02-19 03:04:26 +00005464 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005465 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00005466 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5467}
5468
Steve Naroff218bc2b2007-05-04 21:54:46 +00005469inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00005470 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff94a5aca2007-07-16 22:23:01 +00005471 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005472 return CheckVectorOperands(Loc, lex, rex);
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005473
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005474 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005475
Steve Naroffdbd9e892007-07-17 00:58:39 +00005476 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005477 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00005478 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005479}
5480
Steve Naroff218bc2b2007-05-04 21:54:46 +00005481inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump11289f42009-09-09 15:08:12 +00005482 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005483 if (!Context.getLangOptions().CPlusPlus) {
5484 UsualUnaryConversions(lex);
5485 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005486
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005487 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5488 return InvalidOperands(Loc, lex, rex);
Anders Carlsson35a99d92009-10-16 01:44:21 +00005489
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005490 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00005491 }
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005492
5493 // C++ [expr.log.and]p1
5494 // C++ [expr.log.or]p1
5495 // The operands are both implicitly converted to type bool (clause 4).
5496 StandardConversionSequence LHS;
5497 if (!IsStandardConversion(lex, Context.BoolTy,
5498 /*InOverloadResolution=*/false, LHS))
5499 return InvalidOperands(Loc, lex, rex);
Anders Carlsson35a99d92009-10-16 01:44:21 +00005500
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005501 if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
5502 "passing", /*IgnoreBaseAccess=*/false))
5503 return InvalidOperands(Loc, lex, rex);
5504
5505 StandardConversionSequence RHS;
5506 if (!IsStandardConversion(rex, Context.BoolTy,
5507 /*InOverloadResolution=*/false, RHS))
5508 return InvalidOperands(Loc, lex, rex);
5509
5510 if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
5511 "passing", /*IgnoreBaseAccess=*/false))
5512 return InvalidOperands(Loc, lex, rex);
5513
5514 // C++ [expr.log.and]p2
5515 // C++ [expr.log.or]p2
5516 // The result is a bool.
5517 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00005518}
5519
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005520/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5521/// is a read-only property; return true if so. A readonly property expression
5522/// depends on various declarations and thus must be treated specially.
5523///
Mike Stump11289f42009-09-09 15:08:12 +00005524static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005525 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5526 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5527 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5528 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005529 if (const ObjCObjectPointerType *OPT =
Steve Naroff7cae42b2009-07-10 23:34:53 +00005530 BaseType->getAsObjCInterfacePointerType())
5531 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5532 if (S.isPropertyReadonly(PDecl, IFace))
5533 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005534 }
5535 }
5536 return false;
5537}
5538
Chris Lattner30bd3272008-11-18 01:22:49 +00005539/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5540/// emit an error and return true. If so, return false.
5541static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005542 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00005543 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005544 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005545 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5546 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00005547 if (IsLV == Expr::MLV_Valid)
5548 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005549
Chris Lattner30bd3272008-11-18 01:22:49 +00005550 unsigned Diag = 0;
5551 bool NeedType = false;
5552 switch (IsLV) { // C99 6.5.16p2
5553 default: assert(0 && "Unknown result from isModifiableLvalue!");
5554 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005555 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00005556 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5557 NeedType = true;
5558 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005559 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00005560 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5561 NeedType = true;
5562 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00005563 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00005564 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5565 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005566 case Expr::MLV_InvalidExpression:
Chris Lattner30bd3272008-11-18 01:22:49 +00005567 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5568 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005569 case Expr::MLV_IncompleteType:
5570 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00005571 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00005572 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
5573 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00005574 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00005575 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5576 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00005577 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00005578 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5579 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00005580 case Expr::MLV_ReadonlyProperty:
5581 Diag = diag::error_readonly_property_assignment;
5582 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00005583 case Expr::MLV_NoSetterProperty:
5584 Diag = diag::error_nosetter_property_assignment;
5585 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005586 }
Steve Naroffad373bd2007-07-31 12:34:36 +00005587
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005588 SourceRange Assign;
5589 if (Loc != OrigLoc)
5590 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00005591 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005592 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00005593 else
Mike Stump11289f42009-09-09 15:08:12 +00005594 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00005595 return true;
5596}
5597
5598
5599
5600// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00005601QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5602 SourceLocation Loc,
5603 QualType CompoundType) {
5604 // Verify that LHS is a modifiable lvalue, and emit error if not.
5605 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00005606 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00005607
5608 QualType LHSType = LHS->getType();
5609 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005610
Chris Lattner9bad62c2008-01-04 18:04:52 +00005611 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00005612 if (CompoundType.isNull()) {
Chris Lattnerea714382008-08-21 18:04:13 +00005613 // Simple assignment "x = y".
Chris Lattner326f7572008-11-18 01:30:42 +00005614 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005615 // Special case of NSObject attributes on c-style pointer types.
5616 if (ConvTy == IncompatiblePointer &&
5617 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00005618 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005619 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00005620 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005621 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005622
Chris Lattnerea714382008-08-21 18:04:13 +00005623 // If the RHS is a unary plus or minus, check to see if they = and + are
5624 // right next to each other. If so, the user may have typo'd "x =+ 4"
5625 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00005626 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00005627 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5628 RHSCheck = ICE->getSubExpr();
5629 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5630 if ((UO->getOpcode() == UnaryOperator::Plus ||
5631 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00005632 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00005633 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00005634 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5635 // And there is a space or other character before the subexpr of the
5636 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00005637 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5638 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00005639 Diag(Loc, diag::warn_not_compound_assign)
5640 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5641 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00005642 }
Chris Lattnerea714382008-08-21 18:04:13 +00005643 }
5644 } else {
5645 // Compound assignment "x += y"
Eli Friedmanb05c41e2009-05-16 05:56:02 +00005646 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00005647 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005648
Chris Lattner326f7572008-11-18 01:30:42 +00005649 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
5650 RHS, "assigning"))
Chris Lattner9bad62c2008-01-04 18:04:52 +00005651 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005652
Steve Naroff98cf3e92007-06-06 18:38:38 +00005653 // C99 6.5.16p3: The type of an assignment expression is the type of the
5654 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00005655 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00005656 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5657 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00005658 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00005659 // operand.
Chris Lattner326f7572008-11-18 01:30:42 +00005660 return LHSType.getUnqualifiedType();
Steve Naroffae4143e2007-04-26 20:39:23 +00005661}
5662
Chris Lattner326f7572008-11-18 01:30:42 +00005663// C99 6.5.17
5664QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattnerf6e1e302008-07-25 20:54:07 +00005665 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner326f7572008-11-18 01:30:42 +00005666 DefaultFunctionArrayConversion(RHS);
Eli Friedmanba961a92009-03-23 00:24:07 +00005667
5668 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5669 // incomplete in C++).
5670
Chris Lattner326f7572008-11-18 01:30:42 +00005671 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00005672}
5673
Steve Naroff7a5af782007-07-13 16:58:59 +00005674/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5675/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle10c2c32008-12-20 09:35:34 +00005676QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5677 bool isInc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005678 if (Op->isTypeDependent())
5679 return Context.DependentTy;
5680
Chris Lattner6b0cf142008-11-21 07:05:48 +00005681 QualType ResType = Op->getType();
5682 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00005683
Sebastian Redle10c2c32008-12-20 09:35:34 +00005684 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5685 // Decrement of bool is not allowed.
5686 if (!isInc) {
5687 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5688 return QualType();
5689 }
5690 // Increment of bool sets it to true, but is deprecated.
5691 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5692 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00005693 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00005694 } else if (ResType->isAnyPointerType()) {
5695 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005696
Chris Lattner6b0cf142008-11-21 07:05:48 +00005697 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00005698 if (PointeeTy->isVoidType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005699 if (getLangOptions().CPlusPlus) {
5700 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5701 << Op->getSourceRange();
5702 return QualType();
5703 }
5704
5705 // Pointer to void is a GNU extension in C.
Chris Lattner6b0cf142008-11-21 07:05:48 +00005706 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005707 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005708 if (getLangOptions().CPlusPlus) {
5709 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5710 << Op->getType() << Op->getSourceRange();
5711 return QualType();
5712 }
5713
5714 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005715 << ResType << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005716 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlsson029fc692009-08-26 22:59:12 +00005717 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00005718 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005719 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00005720 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00005721 // Diagnose bad cases where we step over interface counts.
5722 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5723 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5724 << PointeeTy << Op->getSourceRange();
5725 return QualType();
5726 }
Chris Lattner6b0cf142008-11-21 07:05:48 +00005727 } else if (ResType->isComplexType()) {
5728 // C99 does not support ++/-- on complex types, we allow as an extension.
5729 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005730 << ResType << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005731 } else {
5732 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005733 << ResType << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005734 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00005735 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005736 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00005737 // Now make sure the operand is a modifiable lvalue.
Chris Lattner6b0cf142008-11-21 07:05:48 +00005738 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Steve Naroff35d85152007-05-07 00:24:15 +00005739 return QualType();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005740 return ResType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005741}
5742
Anders Carlsson806700f2008-02-01 07:15:58 +00005743/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00005744/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005745/// where the declaration is needed for type checking. We only need to
5746/// handle cases when the expression references a function designator
5747/// or is an lvalue. Here are some examples:
5748/// - &(x) => x
5749/// - &*****f => f for f a function designator.
5750/// - &s.xx => s
5751/// - &s.zz[1].yy -> s, if zz is an array
5752/// - *(x + 1) -> x, if x is an array
5753/// - &"123"[2] -> 0
5754/// - & __real__ x -> x
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005755static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005756 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00005757 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005758 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00005759 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005760 // If this is an arrow operator, the address is an offset from
5761 // the base's value, so the object the base refers to is
5762 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005763 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00005764 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00005765 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005766 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00005767 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00005768 // FIXME: This code shouldn't be necessary! We should catch the implicit
5769 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00005770 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5771 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5772 if (ICE->getSubExpr()->getType()->isArrayType())
5773 return getPrimaryDecl(ICE->getSubExpr());
5774 }
5775 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00005776 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005777 case Stmt::UnaryOperatorClass: {
5778 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005779
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005780 switch(UO->getOpcode()) {
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005781 case UnaryOperator::Real:
5782 case UnaryOperator::Imag:
5783 case UnaryOperator::Extension:
5784 return getPrimaryDecl(UO->getSubExpr());
5785 default:
5786 return 0;
5787 }
5788 }
Steve Naroff47500512007-04-19 23:00:49 +00005789 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005790 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00005791 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005792 // If the result of an implicit cast is an l-value, we care about
5793 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005794 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00005795 default:
5796 return 0;
5797 }
5798}
5799
5800/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00005801/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00005802/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005803/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005804/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005805/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00005806/// we allow the '&' but retain the overloaded-function type.
Steve Naroff35d85152007-05-07 00:24:15 +00005807QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00005808 // Make sure to ignore parentheses in subsequent checks
5809 op = op->IgnoreParens();
5810
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00005811 if (op->isTypeDependent())
5812 return Context.DependentTy;
5813
Steve Naroff826e91a2008-01-13 17:10:08 +00005814 if (getLangOptions().C99) {
5815 // Implement C99-only parts of addressof rules.
5816 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5817 if (uOp->getOpcode() == UnaryOperator::Deref)
5818 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5819 // (assuming the deref expression is valid).
5820 return uOp->getSubExpr()->getType();
5821 }
5822 // Technically, there should be a check for array subscript
5823 // expressions here, but the result of one is always an lvalue anyway.
5824 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005825 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner67315442008-07-26 21:30:36 +00005826 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00005827
Eli Friedmance7f9002009-05-16 23:27:50 +00005828 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5829 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005830 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00005831 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00005832 // FIXME: emit more specific diag...
Chris Lattnerf490e152008-11-19 05:27:50 +00005833 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5834 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005835 return QualType();
5836 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00005837 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005838 // The operand cannot be a bit-field
5839 Diag(OpLoc, diag::err_typecheck_address_of)
5840 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00005841 return QualType();
Nate Begemana6b47a42009-02-15 22:45:20 +00005842 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5843 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman3a1e6922009-04-20 08:23:18 +00005844 // The operand cannot be an element of a vector
Chris Lattner29e812b2008-11-20 06:06:08 +00005845 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00005846 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005847 return QualType();
Fariborz Jahanian385db802009-07-07 18:50:52 +00005848 } else if (isa<ObjCPropertyRefExpr>(op)) {
5849 // cannot take address of a property expression.
5850 Diag(OpLoc, diag::err_typecheck_address_of)
5851 << "property expression" << op->getSourceRange();
5852 return QualType();
Anders Carlsson3fa58d12009-09-14 23:15:26 +00005853 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5854 // FIXME: Can LHS ever be null here?
Anders Carlsson01ccf992009-09-15 16:03:44 +00005855 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5856 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00005857 } else if (isa<UnresolvedLookupExpr>(op)) {
5858 return Context.OverloadTy;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005859 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00005860 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00005861 // with the register storage-class specifier.
5862 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Steve Naroff35d85152007-05-07 00:24:15 +00005863 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner29e812b2008-11-20 06:06:08 +00005864 Diag(OpLoc, diag::err_typecheck_address_of)
5865 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005866 return QualType();
5867 }
John McCalld14a8642009-11-21 08:51:07 +00005868 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005869 return Context.OverloadTy;
Anders Carlsson0b675f52009-07-08 21:45:58 +00005870 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00005871 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005872 // Could be a pointer to member, though, if there is an explicit
5873 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005874 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005875 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00005876 if (Ctx && Ctx->isRecord()) {
5877 if (FD->getType()->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005878 Diag(OpLoc,
Anders Carlsson0b675f52009-07-08 21:45:58 +00005879 diag::err_cannot_form_pointer_to_member_of_reference_type)
5880 << FD->getDeclName() << FD->getType();
5881 return QualType();
5882 }
Mike Stump11289f42009-09-09 15:08:12 +00005883
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005884 return Context.getMemberPointerType(op->getType(),
5885 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00005886 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005887 }
Anders Carlsson5b535762009-05-16 21:43:42 +00005888 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes5773a1b2008-12-16 22:58:26 +00005889 // Okay: we can take the address of a function.
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005890 // As above.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005891 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5892 MD->isInstance())
Anders Carlsson5b535762009-05-16 21:43:42 +00005893 return Context.getMemberPointerType(op->getType(),
5894 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5895 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00005896 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00005897 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005898
Eli Friedmance7f9002009-05-16 23:27:50 +00005899 if (lval == Expr::LV_IncompleteVoidType) {
5900 // Taking the address of a void variable is technically illegal, but we
5901 // allow it in cases which are otherwise valid.
5902 // Example: "extern void x; void* y = &x;".
5903 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5904 }
5905
Steve Naroff47500512007-04-19 23:00:49 +00005906 // If the operand has type "type", the result has type "pointer to type".
Steve Naroff35d85152007-05-07 00:24:15 +00005907 return Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00005908}
5909
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005910QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005911 if (Op->isTypeDependent())
5912 return Context.DependentTy;
5913
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005914 UsualUnaryConversions(Op);
5915 QualType Ty = Op->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005916
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005917 // Note that per both C89 and C99, this is always legal, even if ptype is an
5918 // incomplete type or void. It would be possible to warn about dereferencing
5919 // a void pointer, but it's completely well-defined, and such a warning is
5920 // unlikely to catch any mistakes.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005921 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff826e91a2008-01-13 17:10:08 +00005922 return PT->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005923
John McCall9dd450b2009-09-21 23:43:11 +00005924 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanianf15d4b62009-09-03 00:43:07 +00005925 return OPT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005926
Chris Lattner29e812b2008-11-20 06:06:08 +00005927 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005928 << Ty << Op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005929 return QualType();
Steve Naroff1926c832007-04-24 00:23:05 +00005930}
Steve Naroff218bc2b2007-05-04 21:54:46 +00005931
5932static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5933 tok::TokenKind Kind) {
5934 BinaryOperator::Opcode Opc;
5935 switch (Kind) {
5936 default: assert(0 && "Unknown binop!");
Sebastian Redl112a97662009-02-07 00:15:38 +00005937 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5938 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005939 case tok::star: Opc = BinaryOperator::Mul; break;
5940 case tok::slash: Opc = BinaryOperator::Div; break;
5941 case tok::percent: Opc = BinaryOperator::Rem; break;
5942 case tok::plus: Opc = BinaryOperator::Add; break;
5943 case tok::minus: Opc = BinaryOperator::Sub; break;
5944 case tok::lessless: Opc = BinaryOperator::Shl; break;
5945 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5946 case tok::lessequal: Opc = BinaryOperator::LE; break;
5947 case tok::less: Opc = BinaryOperator::LT; break;
5948 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5949 case tok::greater: Opc = BinaryOperator::GT; break;
5950 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5951 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5952 case tok::amp: Opc = BinaryOperator::And; break;
5953 case tok::caret: Opc = BinaryOperator::Xor; break;
5954 case tok::pipe: Opc = BinaryOperator::Or; break;
5955 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5956 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5957 case tok::equal: Opc = BinaryOperator::Assign; break;
5958 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5959 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5960 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5961 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5962 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5963 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5964 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5965 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5966 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5967 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5968 case tok::comma: Opc = BinaryOperator::Comma; break;
5969 }
5970 return Opc;
5971}
5972
Steve Naroff35d85152007-05-07 00:24:15 +00005973static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5974 tok::TokenKind Kind) {
5975 UnaryOperator::Opcode Opc;
5976 switch (Kind) {
5977 default: assert(0 && "Unknown unary op!");
5978 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5979 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5980 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5981 case tok::star: Opc = UnaryOperator::Deref; break;
5982 case tok::plus: Opc = UnaryOperator::Plus; break;
5983 case tok::minus: Opc = UnaryOperator::Minus; break;
5984 case tok::tilde: Opc = UnaryOperator::Not; break;
5985 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Steve Naroff35d85152007-05-07 00:24:15 +00005986 case tok::kw___real: Opc = UnaryOperator::Real; break;
5987 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
Chris Lattnerd0f76512007-06-08 22:16:53 +00005988 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00005989 }
5990 return Opc;
5991}
5992
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005993/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5994/// operator @p Opc at location @c TokLoc. This routine only supports
5995/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005996Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5997 unsigned Op,
5998 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005999 QualType ResultTy; // Result type of the binary operator.
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006000 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006001 // The following two variables are used for compound assignment operators
6002 QualType CompLHSTy; // Type of LHS after promotions for computation
6003 QualType CompResultTy; // Type of computation result
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006004
6005 switch (Opc) {
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006006 case BinaryOperator::Assign:
6007 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
6008 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00006009 case BinaryOperator::PtrMemD:
6010 case BinaryOperator::PtrMemI:
6011 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
6012 Opc == BinaryOperator::PtrMemI);
6013 break;
6014 case BinaryOperator::Mul:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006015 case BinaryOperator::Div:
6016 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
6017 break;
6018 case BinaryOperator::Rem:
6019 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
6020 break;
6021 case BinaryOperator::Add:
6022 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
6023 break;
6024 case BinaryOperator::Sub:
6025 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
6026 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00006027 case BinaryOperator::Shl:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006028 case BinaryOperator::Shr:
6029 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
6030 break;
6031 case BinaryOperator::LE:
6032 case BinaryOperator::LT:
6033 case BinaryOperator::GE:
6034 case BinaryOperator::GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006035 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006036 break;
6037 case BinaryOperator::EQ:
6038 case BinaryOperator::NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006039 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006040 break;
6041 case BinaryOperator::And:
6042 case BinaryOperator::Xor:
6043 case BinaryOperator::Or:
6044 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
6045 break;
6046 case BinaryOperator::LAnd:
6047 case BinaryOperator::LOr:
6048 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
6049 break;
6050 case BinaryOperator::MulAssign:
6051 case BinaryOperator::DivAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006052 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
6053 CompLHSTy = CompResultTy;
6054 if (!CompResultTy.isNull())
6055 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006056 break;
6057 case BinaryOperator::RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006058 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
6059 CompLHSTy = CompResultTy;
6060 if (!CompResultTy.isNull())
6061 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006062 break;
6063 case BinaryOperator::AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006064 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6065 if (!CompResultTy.isNull())
6066 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006067 break;
6068 case BinaryOperator::SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006069 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6070 if (!CompResultTy.isNull())
6071 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006072 break;
6073 case BinaryOperator::ShlAssign:
6074 case BinaryOperator::ShrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006075 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6076 CompLHSTy = CompResultTy;
6077 if (!CompResultTy.isNull())
6078 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006079 break;
6080 case BinaryOperator::AndAssign:
6081 case BinaryOperator::XorAssign:
6082 case BinaryOperator::OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006083 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6084 CompLHSTy = CompResultTy;
6085 if (!CompResultTy.isNull())
6086 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006087 break;
6088 case BinaryOperator::Comma:
6089 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6090 break;
6091 }
6092 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00006093 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006094 if (CompResultTy.isNull())
Steve Narofff6009ed2009-01-21 00:14:39 +00006095 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6096 else
6097 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006098 CompLHSTy, CompResultTy,
6099 OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006100}
6101
Sebastian Redl44615072009-10-27 12:10:02 +00006102/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6103/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006104static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6105 const PartialDiagnostic &PD,
6106 SourceRange ParenRange)
6107{
6108 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6109 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6110 // We can't display the parentheses, so just dig the
6111 // warning/error and return.
6112 Self.Diag(Loc, PD);
6113 return;
6114 }
6115
6116 Self.Diag(Loc, PD)
6117 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
6118 << CodeModificationHint::CreateInsertion(EndLoc, ")");
6119}
6120
Sebastian Redl44615072009-10-27 12:10:02 +00006121/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6122/// operators are mixed in a way that suggests that the programmer forgot that
6123/// comparison operators have higher precedence. The most typical example of
6124/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl43028242009-10-26 15:24:15 +00006125static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6126 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00006127 typedef BinaryOperator BinOp;
6128 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6129 rhsopc = static_cast<BinOp::Opcode>(-1);
6130 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00006131 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00006132 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00006133 rhsopc = BO->getOpcode();
6134
6135 // Subs are not binary operators.
6136 if (lhsopc == -1 && rhsopc == -1)
6137 return;
6138
6139 // Bitwise operations are sometimes used as eager logical ops.
6140 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00006141 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6142 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00006143 return;
6144
Sebastian Redl44615072009-10-27 12:10:02 +00006145 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006146 SuggestParentheses(Self, OpLoc,
6147 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00006148 << SourceRange(lhs->getLocStart(), OpLoc)
6149 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
6150 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
6151 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006152 SuggestParentheses(Self, OpLoc,
6153 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00006154 << SourceRange(OpLoc, rhs->getLocEnd())
6155 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
6156 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl43028242009-10-26 15:24:15 +00006157}
6158
6159/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6160/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6161/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6162static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6163 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00006164 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl43028242009-10-26 15:24:15 +00006165 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6166}
6167
Steve Naroff218bc2b2007-05-04 21:54:46 +00006168// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb5d49352009-01-19 22:31:54 +00006169Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6170 tok::TokenKind Kind,
6171 ExprArg LHS, ExprArg RHS) {
Steve Naroff218bc2b2007-05-04 21:54:46 +00006172 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssonb781bcd2009-05-01 19:49:17 +00006173 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Steve Naroff218bc2b2007-05-04 21:54:46 +00006174
Steve Naroff83895f72007-09-16 03:34:24 +00006175 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6176 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00006177
Sebastian Redl43028242009-10-26 15:24:15 +00006178 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6179 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6180
Douglas Gregor5287f092009-11-05 00:51:44 +00006181 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6182}
6183
6184Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6185 BinaryOperator::Opcode Opc,
6186 Expr *lhs, Expr *rhs) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006187 if (getLangOptions().CPlusPlus &&
Mike Stump11289f42009-09-09 15:08:12 +00006188 (lhs->getType()->isOverloadableType() ||
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006189 rhs->getType()->isOverloadableType())) {
6190 // Find all of the overloaded operators visible from this
6191 // point. We perform both an operator-name lookup from the local
6192 // scope and an argument-dependent lookup based on the types of
6193 // the arguments.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006194 FunctionSet Functions;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006195 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
6196 if (OverOp != OO_None) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006197 if (S)
6198 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6199 Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006200 Expr *Args[2] = { lhs, rhs };
Mike Stump11289f42009-09-09 15:08:12 +00006201 DeclarationName OpName
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006202 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redlc057f422009-10-23 19:23:15 +00006203 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
Douglas Gregora11693b2008-11-12 17:17:38 +00006204 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006205
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006206 // Build the (potentially-overloaded, potentially-dependent)
6207 // binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00006208 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb5d49352009-01-19 22:31:54 +00006209 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006210
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006211 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00006212 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006213}
6214
Douglas Gregor084d8552009-03-13 23:49:33 +00006215Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006216 unsigned OpcIn,
Douglas Gregor084d8552009-03-13 23:49:33 +00006217 ExprArg InputArg) {
6218 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregord08452f2008-11-19 15:42:04 +00006219
Mike Stump87c57ac2009-05-16 07:39:55 +00006220 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregor084d8552009-03-13 23:49:33 +00006221 Expr *Input = (Expr *)InputArg.get();
Steve Naroff35d85152007-05-07 00:24:15 +00006222 QualType resultType;
6223 switch (Opc) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006224 case UnaryOperator::OffsetOf:
6225 assert(false && "Invalid unary operator");
6226 break;
6227
Steve Naroff35d85152007-05-07 00:24:15 +00006228 case UnaryOperator::PreInc:
6229 case UnaryOperator::PreDec:
Eli Friedman6aea5752009-07-22 22:25:00 +00006230 case UnaryOperator::PostInc:
6231 case UnaryOperator::PostDec:
Sebastian Redle10c2c32008-12-20 09:35:34 +00006232 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman6aea5752009-07-22 22:25:00 +00006233 Opc == UnaryOperator::PreInc ||
6234 Opc == UnaryOperator::PostInc);
Steve Naroff35d85152007-05-07 00:24:15 +00006235 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006236 case UnaryOperator::AddrOf:
Chris Lattner86554282007-06-08 22:32:33 +00006237 resultType = CheckAddressOfOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00006238 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006239 case UnaryOperator::Deref:
Steve Naroffb7235642007-12-18 04:06:57 +00006240 DefaultFunctionArrayConversion(Input);
Chris Lattner86554282007-06-08 22:32:33 +00006241 resultType = CheckIndirectionOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00006242 break;
6243 case UnaryOperator::Plus:
6244 case UnaryOperator::Minus:
Steve Naroff31090012007-07-16 21:54:35 +00006245 UsualUnaryConversions(Input);
6246 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006247 if (resultType->isDependentType())
6248 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006249 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
6250 break;
6251 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6252 resultType->isEnumeralType())
6253 break;
6254 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6255 Opc == UnaryOperator::Plus &&
6256 resultType->isPointerType())
6257 break;
6258
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006259 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6260 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00006261 case UnaryOperator::Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00006262 UsualUnaryConversions(Input);
6263 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006264 if (resultType->isDependentType())
6265 break;
Chris Lattner0d707612008-07-25 23:52:49 +00006266 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6267 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6268 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00006269 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006270 << resultType << Input->getSourceRange();
Chris Lattner0d707612008-07-25 23:52:49 +00006271 else if (!resultType->isIntegerType())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006272 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6273 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00006274 break;
6275 case UnaryOperator::LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00006276 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroff31090012007-07-16 21:54:35 +00006277 DefaultFunctionArrayConversion(Input);
6278 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006279 if (resultType->isDependentType())
6280 break;
Steve Naroff35d85152007-05-07 00:24:15 +00006281 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006282 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6283 << resultType << Input->getSourceRange());
Chris Lattnerbe31ed82007-06-02 19:11:33 +00006284 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006285 // In C++, it's bool. C++ 5.3.1p8
6286 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Steve Naroff35d85152007-05-07 00:24:15 +00006287 break;
Chris Lattner30b5dd02007-08-24 21:16:53 +00006288 case UnaryOperator::Real:
Chris Lattner30b5dd02007-08-24 21:16:53 +00006289 case UnaryOperator::Imag:
Chris Lattner709322b2009-02-17 08:12:06 +00006290 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner30b5dd02007-08-24 21:16:53 +00006291 break;
Chris Lattner86554282007-06-08 22:32:33 +00006292 case UnaryOperator::Extension:
Chris Lattner86554282007-06-08 22:32:33 +00006293 resultType = Input->getType();
Steve Naroff043d45d2007-05-15 02:32:35 +00006294 break;
Steve Naroff35d85152007-05-07 00:24:15 +00006295 }
6296 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006297 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00006298
6299 InputArg.release();
Steve Narofff6009ed2009-01-21 00:14:39 +00006300 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00006301}
Chris Lattnereefa10e2007-05-28 06:56:27 +00006302
Douglas Gregor5287f092009-11-05 00:51:44 +00006303Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6304 UnaryOperator::Opcode Opc,
6305 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006306 Expr *Input = (Expr*)input.get();
Anders Carlsson461a2c02009-11-14 21:26:41 +00006307 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6308 Opc != UnaryOperator::Extension) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006309 // Find all of the overloaded operators visible from this
6310 // point. We perform both an operator-name lookup from the local
6311 // scope and an argument-dependent lookup based on the types of
6312 // the arguments.
6313 FunctionSet Functions;
6314 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
6315 if (OverOp != OO_None) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006316 if (S)
6317 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6318 Functions);
Mike Stump11289f42009-09-09 15:08:12 +00006319 DeclarationName OpName
Douglas Gregor084d8552009-03-13 23:49:33 +00006320 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redlc057f422009-10-23 19:23:15 +00006321 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
Douglas Gregor084d8552009-03-13 23:49:33 +00006322 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006323
Douglas Gregor084d8552009-03-13 23:49:33 +00006324 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6325 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006326
Douglas Gregor084d8552009-03-13 23:49:33 +00006327 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6328}
6329
Douglas Gregor5287f092009-11-05 00:51:44 +00006330// Unary Operators. 'Tok' is the token for the operator.
6331Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6332 tok::TokenKind Op, ExprArg input) {
6333 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6334}
6335
Steve Naroff66356bd2007-09-16 14:56:35 +00006336/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006337Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6338 SourceLocation LabLoc,
6339 IdentifierInfo *LabelII) {
Chris Lattnereefa10e2007-05-28 06:56:27 +00006340 // Look up the record for this label identifier.
Chris Lattner3318e862009-04-18 20:01:55 +00006341 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump4e1f26a2009-02-19 03:04:26 +00006342
Daniel Dunbar88402ce2008-08-04 16:51:22 +00006343 // If we haven't seen this label yet, create a forward reference. It
6344 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff846b1ec2009-03-13 15:38:40 +00006345 if (LabelDecl == 0)
Steve Narofff6009ed2009-01-21 00:14:39 +00006346 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006347
Chris Lattnereefa10e2007-05-28 06:56:27 +00006348 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006349 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6350 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00006351}
6352
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006353Sema::OwningExprResult
6354Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6355 SourceLocation RPLoc) { // "({..})"
6356 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner366727f2007-07-24 16:58:17 +00006357 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6358 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6359
Eli Friedman52cc0162009-01-24 23:09:00 +00006360 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattnera69b0762009-04-25 19:11:05 +00006361 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006362 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00006363
Chris Lattner366727f2007-07-24 16:58:17 +00006364 // FIXME: there are a variety of strange constraints to enforce here, for
6365 // example, it is not possible to goto into a stmt expression apparently.
6366 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006367
Chris Lattner366727f2007-07-24 16:58:17 +00006368 // If there are sub stmts in the compound stmt, take the type of the last one
6369 // as the type of the stmtexpr.
6370 QualType Ty = Context.VoidTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006371
Chris Lattner944d3062008-07-26 19:51:01 +00006372 if (!Compound->body_empty()) {
6373 Stmt *LastStmt = Compound->body_back();
6374 // If LastStmt is a label, skip down through into the body.
6375 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6376 LastStmt = Label->getSubStmt();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006377
Chris Lattner944d3062008-07-26 19:51:01 +00006378 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner366727f2007-07-24 16:58:17 +00006379 Ty = LastExpr->getType();
Chris Lattner944d3062008-07-26 19:51:01 +00006380 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006381
Eli Friedmanba961a92009-03-23 00:24:07 +00006382 // FIXME: Check that expression type is complete/non-abstract; statement
6383 // expressions are not lvalues.
6384
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006385 substmt.release();
6386 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner366727f2007-07-24 16:58:17 +00006387}
Steve Naroff78864672007-08-01 22:05:33 +00006388
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006389Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6390 SourceLocation BuiltinLoc,
6391 SourceLocation TypeLoc,
6392 TypeTy *argty,
6393 OffsetOfComponent *CompPtr,
6394 unsigned NumComponents,
6395 SourceLocation RPLoc) {
6396 // FIXME: This function leaks all expressions in the offset components on
6397 // error.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006398 // FIXME: Preserve type source info.
6399 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattnerf17bd422007-08-30 17:45:32 +00006400 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006401
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006402 bool Dependent = ArgTy->isDependentType();
6403
Chris Lattnerf17bd422007-08-30 17:45:32 +00006404 // We must have at least one component that refers to the type, and the first
6405 // one is known to be a field designator. Verify that the ArgTy represents
6406 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006407 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006408 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006409
Eli Friedmanba961a92009-03-23 00:24:07 +00006410 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6411 // with an incomplete type would be illegal.
Douglas Gregor26897462009-03-11 16:48:53 +00006412
Eli Friedman988a16b2009-02-27 06:44:11 +00006413 // Otherwise, create a null pointer as the base, and iteratively process
6414 // the offsetof designators.
6415 QualType ArgTyPtr = Context.getPointerType(ArgTy);
6416 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006417 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman988a16b2009-02-27 06:44:11 +00006418 ArgTy, SourceLocation());
Eli Friedman16c88df2009-01-26 01:33:06 +00006419
Chris Lattner78502cf2007-08-31 21:49:13 +00006420 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6421 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00006422 // FIXME: This diagnostic isn't actually visible because the location is in
6423 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00006424 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00006425 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6426 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006427
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006428 if (!Dependent) {
Eli Friedman8469bc72009-05-03 21:22:18 +00006429 bool DidWarnAboutNonPOD = false;
Mike Stump11289f42009-09-09 15:08:12 +00006430
John McCall9eff4e62009-11-04 03:03:43 +00006431 if (RequireCompleteType(TypeLoc, Res->getType(),
6432 diag::err_offsetof_incomplete_type))
6433 return ExprError();
6434
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006435 // FIXME: Dependent case loses a lot of information here. And probably
6436 // leaks like a sieve.
6437 for (unsigned i = 0; i != NumComponents; ++i) {
6438 const OffsetOfComponent &OC = CompPtr[i];
6439 if (OC.isBrackets) {
6440 // Offset of an array sub-field. TODO: Should we allow vector elements?
6441 const ArrayType *AT = Context.getAsArrayType(Res->getType());
6442 if (!AT) {
6443 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006444 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6445 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006446 }
6447
6448 // FIXME: C++: Verify that operator[] isn't overloaded.
6449
Eli Friedman988a16b2009-02-27 06:44:11 +00006450 // Promote the array so it looks more like a normal array subscript
6451 // expression.
6452 DefaultFunctionArrayConversion(Res);
6453
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006454 // C99 6.5.2.1p1
6455 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006456 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006457 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006458 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner003af242009-04-25 22:50:55 +00006459 diag::err_typecheck_subscript_not_integer)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006460 << Idx->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006461
6462 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
6463 OC.LocEnd);
6464 continue;
Chris Lattnerf17bd422007-08-30 17:45:32 +00006465 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006466
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006467 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006468 if (!RC) {
6469 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006470 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6471 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006472 }
Chris Lattner98dbf0a2007-08-30 17:59:59 +00006473
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006474 // Get the decl corresponding to this.
6475 RecordDecl *RD = RC->getDecl();
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00006476 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson38ebcaa2009-05-02 18:36:10 +00006477 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Douglas Gregor7ca84af2009-12-12 07:25:49 +00006478 switch (ExprEvalContexts.back().Context ) {
6479 case Unevaluated:
6480 // The argument will never be evaluated, so don't complain.
6481 break;
6482
6483 case PotentiallyEvaluated:
6484 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
6485 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6486 << Res->getType());
6487 DidWarnAboutNonPOD = true;
6488 break;
6489
6490 case PotentiallyPotentiallyEvaluated:
6491 // FIXME: Queue it!
6492 DidWarnAboutNonPOD = true;
6493 break;
6494 }
Anders Carlsson38ebcaa2009-05-02 18:36:10 +00006495 }
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00006496 }
Mike Stump11289f42009-09-09 15:08:12 +00006497
John McCall27b18f82009-11-17 02:14:36 +00006498 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6499 LookupQualifiedName(R, RD);
John McCall9f3059a2009-10-09 21:13:30 +00006500
John McCall67c00872009-12-02 08:25:40 +00006501 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006502 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006503 if (!MemberDecl)
Douglas Gregore40876a2009-10-13 21:16:44 +00006504 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6505 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump4e1f26a2009-02-19 03:04:26 +00006506
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006507 // FIXME: C++: Verify that MemberDecl isn't a static field.
6508 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman64fc3c62009-04-26 20:50:44 +00006509 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +00006510 Res = BuildAnonymousStructUnionMemberReference(
John McCall7e1d6d72009-11-11 03:23:23 +00006511 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedman64fc3c62009-04-26 20:50:44 +00006512 } else {
Eli Friedman78cde142009-12-04 07:18:51 +00006513 PerformObjectMemberConversion(Res, MemberDecl);
Eli Friedman64fc3c62009-04-26 20:50:44 +00006514 // MemberDecl->getType() doesn't get the right qualifiers, but it
6515 // doesn't matter here.
6516 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
6517 MemberDecl->getType().getNonReferenceType());
6518 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006519 }
Chris Lattnerf17bd422007-08-30 17:45:32 +00006520 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006521
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006522 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
6523 Context.getSizeType(), BuiltinLoc));
Chris Lattnerf17bd422007-08-30 17:45:32 +00006524}
6525
6526
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006527Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
6528 TypeTy *arg1,TypeTy *arg2,
6529 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006530 // FIXME: Preserve type source info.
6531 QualType argT1 = GetTypeFromParser(arg1);
6532 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006533
Steve Naroff78864672007-08-01 22:05:33 +00006534 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006535
Douglas Gregorf907cbf2009-05-19 22:28:02 +00006536 if (getLangOptions().CPlusPlus) {
6537 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
6538 << SourceRange(BuiltinLoc, RPLoc);
6539 return ExprError();
6540 }
6541
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006542 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
6543 argT1, argT2, RPLoc));
Steve Naroff78864672007-08-01 22:05:33 +00006544}
6545
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006546Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
6547 ExprArg cond,
6548 ExprArg expr1, ExprArg expr2,
6549 SourceLocation RPLoc) {
6550 Expr *CondExpr = static_cast<Expr*>(cond.get());
6551 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
6552 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006553
Steve Naroff9efdabc2007-08-03 21:21:27 +00006554 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
6555
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006556 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00006557 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00006558 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006559 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00006560 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006561 } else {
6562 // The conditional expression is required to be a constant expression.
6563 llvm::APSInt condEval(32);
6564 SourceLocation ExpLoc;
6565 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006566 return ExprError(Diag(ExpLoc,
6567 diag::err_typecheck_choose_expr_requires_constant)
6568 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00006569
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006570 // If the condition is > zero, then the AST type is the same as the LSHExpr.
6571 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregor56751b52009-09-25 04:25:58 +00006572 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
6573 : RHSExpr->isValueDependent();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006574 }
6575
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006576 cond.release(); expr1.release(); expr2.release();
6577 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregor56751b52009-09-25 04:25:58 +00006578 resType, RPLoc,
6579 resType->isDependentType(),
6580 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00006581}
6582
Steve Naroffc540d662008-09-03 18:15:37 +00006583//===----------------------------------------------------------------------===//
6584// Clang Extensions.
6585//===----------------------------------------------------------------------===//
6586
6587/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006588void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00006589 // Analyze block parameters.
6590 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006591
Steve Naroffc540d662008-09-03 18:15:37 +00006592 // Add BSI to CurBlock.
6593 BSI->PrevBlockInfo = CurBlock;
6594 CurBlock = BSI;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006595
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006596 BSI->ReturnType = QualType();
Steve Naroffc540d662008-09-03 18:15:37 +00006597 BSI->TheScope = BlockScope;
Mike Stumpa6703322009-02-19 22:01:56 +00006598 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarb9a68612009-07-29 01:59:17 +00006599 BSI->hasPrototype = false;
Chris Lattner45542ea2009-04-19 05:28:12 +00006600 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
6601 CurFunctionNeedsScopeChecking = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006602
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006603 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Ted Kremenek54ad1ab2009-12-07 22:01:30 +00006604 CurContext->addDecl(BSI->TheDecl);
Douglas Gregor91f84212008-12-11 16:49:14 +00006605 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006606}
6607
Mike Stump82f071f2009-02-04 22:31:32 +00006608void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00006609 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump82f071f2009-02-04 22:31:32 +00006610
6611 if (ParamInfo.getNumTypeObjects() == 0
6612 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor758a8692009-06-17 21:51:59 +00006613 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump82f071f2009-02-04 22:31:32 +00006614 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6615
Mike Stumpd456c482009-04-28 01:10:27 +00006616 if (T->isArrayType()) {
6617 Diag(ParamInfo.getSourceRange().getBegin(),
6618 diag::err_block_returns_array);
6619 return;
6620 }
6621
Mike Stump82f071f2009-02-04 22:31:32 +00006622 // The parameter list is optional, if there was none, assume ().
6623 if (!T->isFunctionType())
6624 T = Context.getFunctionType(T, NULL, 0, 0, 0);
6625
6626 CurBlock->hasPrototype = true;
6627 CurBlock->isVariadic = false;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006628 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006629 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00006630 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00006631 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006632 // FIXME: remove the attribute.
6633 }
John McCall9dd450b2009-09-21 23:43:11 +00006634 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006635
Chris Lattner6de05082009-04-11 19:27:54 +00006636 // Do not allow returning a objc interface by-value.
6637 if (RetTy->isObjCInterfaceType()) {
6638 Diag(ParamInfo.getSourceRange().getBegin(),
6639 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6640 return;
6641 }
Mike Stump82f071f2009-02-04 22:31:32 +00006642 return;
6643 }
6644
Steve Naroffc540d662008-09-03 18:15:37 +00006645 // Analyze arguments to block.
6646 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6647 "Not a function declarator!");
6648 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006649
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006650 CurBlock->hasPrototype = FTI.hasPrototype;
6651 CurBlock->isVariadic = true;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006652
Steve Naroffc540d662008-09-03 18:15:37 +00006653 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6654 // no arguments, not a function that takes a single void argument.
6655 if (FTI.hasPrototype &&
6656 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner83f095c2009-03-28 19:18:32 +00006657 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6658 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroffc540d662008-09-03 18:15:37 +00006659 // empty arg list, don't push any params.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006660 CurBlock->isVariadic = false;
Steve Naroffc540d662008-09-03 18:15:37 +00006661 } else if (FTI.hasPrototype) {
6662 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner83f095c2009-03-28 19:18:32 +00006663 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006664 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroffc540d662008-09-03 18:15:37 +00006665 }
Jay Foad7d0479f2009-05-21 09:52:38 +00006666 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner6de05082009-04-11 19:27:54 +00006667 CurBlock->Params.size());
Fariborz Jahanian960910a2009-05-19 17:08:59 +00006668 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor758a8692009-06-17 21:51:59 +00006669 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006670 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
6671 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
6672 // If this has an identifier, add it to the scope stack.
6673 if ((*AI)->getIdentifier())
6674 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner6de05082009-04-11 19:27:54 +00006675
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006676 // Check for a valid sentinel attribute on this block.
Mike Stump11289f42009-09-09 15:08:12 +00006677 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006678 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00006679 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00006680 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006681 // FIXME: remove the attribute.
6682 }
Mike Stump11289f42009-09-09 15:08:12 +00006683
Chris Lattner6de05082009-04-11 19:27:54 +00006684 // Analyze the return type.
6685 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall9dd450b2009-09-21 23:43:11 +00006686 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006687
Chris Lattner6de05082009-04-11 19:27:54 +00006688 // Do not allow returning a objc interface by-value.
6689 if (RetTy->isObjCInterfaceType()) {
6690 Diag(ParamInfo.getSourceRange().getBegin(),
6691 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6692 } else if (!RetTy->isDependentType())
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006693 CurBlock->ReturnType = RetTy;
Steve Naroffc540d662008-09-03 18:15:37 +00006694}
6695
6696/// ActOnBlockError - If there is an error parsing a block, this callback
6697/// is invoked to pop the information about the block from the action impl.
6698void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6699 // Ensure that CurBlock is deleted.
6700 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006701
Chris Lattner45542ea2009-04-19 05:28:12 +00006702 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6703
Steve Naroffc540d662008-09-03 18:15:37 +00006704 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00006705 PopDeclContext();
Steve Naroffc540d662008-09-03 18:15:37 +00006706 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroffc540d662008-09-03 18:15:37 +00006707 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroffc540d662008-09-03 18:15:37 +00006708}
6709
6710/// ActOnBlockStmtExpr - This is called when the body of a block statement
6711/// literal was successfully completed. ^(int x){...}
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006712Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6713 StmtArg body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00006714 // If blocks are disabled, emit an error.
6715 if (!LangOpts.Blocks)
6716 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00006717
Steve Naroffc540d662008-09-03 18:15:37 +00006718 // Ensure that CurBlock is deleted.
6719 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroffc540d662008-09-03 18:15:37 +00006720
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006721 PopDeclContext();
6722
Steve Naroffc540d662008-09-03 18:15:37 +00006723 // Pop off CurBlock, handle nested blocks.
6724 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006725
Steve Naroffc540d662008-09-03 18:15:37 +00006726 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006727 if (!BSI->ReturnType.isNull())
6728 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006729
Steve Naroffc540d662008-09-03 18:15:37 +00006730 llvm::SmallVector<QualType, 8> ArgTypes;
6731 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6732 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006733
Mike Stump3bf1ab42009-07-28 22:04:01 +00006734 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00006735 QualType BlockTy;
6736 if (!BSI->hasPrototype)
Mike Stump3bf1ab42009-07-28 22:04:01 +00006737 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6738 NoReturn);
Steve Naroffc540d662008-09-03 18:15:37 +00006739 else
Jay Foad7d0479f2009-05-21 09:52:38 +00006740 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump3bf1ab42009-07-28 22:04:01 +00006741 BSI->isVariadic, 0, false, false, 0, 0,
6742 NoReturn);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006743
Eli Friedmanba961a92009-03-23 00:24:07 +00006744 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006745 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroffc540d662008-09-03 18:15:37 +00006746 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006747
Chris Lattner45542ea2009-04-19 05:28:12 +00006748 // If needed, diagnose invalid gotos and switches in the block.
6749 if (CurFunctionNeedsScopeChecking)
6750 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6751 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump11289f42009-09-09 15:08:12 +00006752
Anders Carlssonb781bcd2009-05-01 19:49:17 +00006753 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump3bf1ab42009-07-28 22:04:01 +00006754 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006755 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6756 BSI->hasBlockDeclRefExprs));
Steve Naroffc540d662008-09-03 18:15:37 +00006757}
6758
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006759Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6760 ExprArg expr, TypeTy *type,
6761 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006762 QualType T = GetTypeFromParser(type);
Chris Lattner56382aa2009-04-05 15:49:53 +00006763 Expr *E = static_cast<Expr*>(expr.get());
6764 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00006765
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006766 InitBuiltinVaListType();
Eli Friedman121ba0c2008-08-09 23:32:40 +00006767
6768 // Get the va_list type
6769 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00006770 if (VaListType->isArrayType()) {
6771 // Deal with implicit array decay; for example, on x86-64,
6772 // va_list is an array, but it's supposed to decay to
6773 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00006774 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00006775 // Make sure the input expression also decays appropriately.
6776 UsualUnaryConversions(E);
6777 } else {
6778 // Otherwise, the va_list argument must be an l-value because
6779 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00006780 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00006781 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00006782 return ExprError();
6783 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00006784
Douglas Gregorad3150c2009-05-19 23:10:31 +00006785 if (!E->isTypeDependent() &&
6786 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006787 return ExprError(Diag(E->getLocStart(),
6788 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00006789 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00006790 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006791
Eli Friedmanba961a92009-03-23 00:24:07 +00006792 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006793 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006794
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006795 expr.release();
6796 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6797 RPLoc));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006798}
6799
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006800Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00006801 // The type of __null will be int or long, depending on the size of
6802 // pointers on the target.
6803 QualType Ty;
6804 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6805 Ty = Context.IntTy;
6806 else
6807 Ty = Context.LongTy;
6808
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006809 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00006810}
6811
Anders Carlssonace5d072009-11-10 04:46:30 +00006812static void
6813MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6814 QualType DstType,
6815 Expr *SrcExpr,
6816 CodeModificationHint &Hint) {
6817 if (!SemaRef.getLangOptions().ObjC1)
6818 return;
6819
6820 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6821 if (!PT)
6822 return;
6823
6824 // Check if the destination is of type 'id'.
6825 if (!PT->isObjCIdType()) {
6826 // Check if the destination is the 'NSString' interface.
6827 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6828 if (!ID || !ID->getIdentifier()->isStr("NSString"))
6829 return;
6830 }
6831
6832 // Strip off any parens and casts.
6833 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
6834 if (!SL || SL->isWide())
6835 return;
6836
6837 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
6838}
6839
Chris Lattner9bad62c2008-01-04 18:04:52 +00006840bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6841 SourceLocation Loc,
6842 QualType DstType, QualType SrcType,
6843 Expr *SrcExpr, const char *Flavor) {
6844 // Decode the result (notice that AST's are still created for extensions).
6845 bool isInvalid = false;
6846 unsigned DiagKind;
Anders Carlssonace5d072009-11-10 04:46:30 +00006847 CodeModificationHint Hint;
6848
Chris Lattner9bad62c2008-01-04 18:04:52 +00006849 switch (ConvTy) {
6850 default: assert(0 && "Unknown conversion type");
6851 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006852 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00006853 DiagKind = diag::ext_typecheck_convert_pointer_int;
6854 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006855 case IntToPointer:
6856 DiagKind = diag::ext_typecheck_convert_int_pointer;
6857 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006858 case IncompatiblePointer:
Anders Carlssonace5d072009-11-10 04:46:30 +00006859 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00006860 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6861 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00006862 case IncompatiblePointerSign:
6863 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6864 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006865 case FunctionVoidPointer:
6866 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6867 break;
6868 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00006869 // If the qualifiers lost were because we were applying the
6870 // (deprecated) C++ conversion from a string literal to a char*
6871 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
6872 // Ideally, this check would be performed in
6873 // CheckPointerTypesForAssignment. However, that would require a
6874 // bit of refactoring (so that the second argument is an
6875 // expression, rather than a type), which should be done as part
6876 // of a larger effort to fix CheckPointerTypesForAssignment for
6877 // C++ semantics.
6878 if (getLangOptions().CPlusPlus &&
6879 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6880 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006881 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6882 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00006883 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00006884 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006885 break;
Steve Naroff081c7422008-09-04 15:10:53 +00006886 case IntToBlockPointer:
6887 DiagKind = diag::err_int_to_block_pointer;
6888 break;
6889 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00006890 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00006891 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00006892 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00006893 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00006894 // it can give a more specific diagnostic.
6895 DiagKind = diag::warn_incompatible_qualified_id;
6896 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006897 case IncompatibleVectors:
6898 DiagKind = diag::warn_incompatible_vectors;
6899 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006900 case Incompatible:
6901 DiagKind = diag::err_typecheck_convert_incompatible;
6902 isInvalid = true;
6903 break;
6904 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006905
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006906 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
Anders Carlssonace5d072009-11-10 04:46:30 +00006907 << SrcExpr->getSourceRange() << Hint;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006908 return isInvalid;
6909}
Anders Carlssone54e8a12008-11-30 19:50:32 +00006910
Chris Lattnerc71d08b2009-04-25 21:59:05 +00006911bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00006912 llvm::APSInt ICEResult;
6913 if (E->isIntegerConstantExpr(ICEResult, Context)) {
6914 if (Result)
6915 *Result = ICEResult;
6916 return false;
6917 }
6918
Anders Carlssone54e8a12008-11-30 19:50:32 +00006919 Expr::EvalResult EvalResult;
6920
Mike Stump4e1f26a2009-02-19 03:04:26 +00006921 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00006922 EvalResult.HasSideEffects) {
6923 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6924
6925 if (EvalResult.Diag) {
6926 // We only show the note if it's not the usual "invalid subexpression"
6927 // or if it's actually in a subexpression.
6928 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
6929 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6930 Diag(EvalResult.DiagLoc, EvalResult.Diag);
6931 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006932
Anders Carlssone54e8a12008-11-30 19:50:32 +00006933 return true;
6934 }
6935
Eli Friedmanbb967cc2009-04-25 22:26:58 +00006936 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6937 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00006938
Eli Friedmanbb967cc2009-04-25 22:26:58 +00006939 if (EvalResult.Diag &&
6940 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6941 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006942
Anders Carlssone54e8a12008-11-30 19:50:32 +00006943 if (Result)
6944 *Result = EvalResult.Val.getInt();
6945 return false;
6946}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006947
Douglas Gregorff790f12009-11-26 00:44:06 +00006948void
Mike Stump11289f42009-09-09 15:08:12 +00006949Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00006950 ExprEvalContexts.push_back(
6951 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006952}
6953
Mike Stump11289f42009-09-09 15:08:12 +00006954void
Douglas Gregorff790f12009-11-26 00:44:06 +00006955Sema::PopExpressionEvaluationContext() {
6956 // Pop the current expression evaluation context off the stack.
6957 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
6958 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006959
Douglas Gregorff790f12009-11-26 00:44:06 +00006960 if (Rec.Context == PotentiallyPotentiallyEvaluated &&
6961 Rec.PotentiallyReferenced) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006962 // Mark any remaining declarations in the current position of the stack
6963 // as "referenced". If they were not meant to be referenced, semantic
6964 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Douglas Gregorff790f12009-11-26 00:44:06 +00006965 for (PotentiallyReferencedDecls::iterator
6966 I = Rec.PotentiallyReferenced->begin(),
6967 IEnd = Rec.PotentiallyReferenced->end();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006968 I != IEnd; ++I)
6969 MarkDeclarationReferenced(I->first, I->second);
Douglas Gregorff790f12009-11-26 00:44:06 +00006970 }
6971
6972 // When are coming out of an unevaluated context, clear out any
6973 // temporaries that we may have created as part of the evaluation of
6974 // the expression in that context: they aren't relevant because they
6975 // will never be constructed.
6976 if (Rec.Context == Unevaluated &&
6977 ExprTemporaries.size() > Rec.NumTemporaries)
6978 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
6979 ExprTemporaries.end());
6980
6981 // Destroy the popped expression evaluation record.
6982 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006983}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006984
6985/// \brief Note that the given declaration was referenced in the source code.
6986///
6987/// This routine should be invoke whenever a given declaration is referenced
6988/// in the source code, and where that reference occurred. If this declaration
6989/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6990/// C99 6.9p3), then the declaration will be marked as used.
6991///
6992/// \param Loc the location where the declaration was referenced.
6993///
6994/// \param D the declaration that has been referenced by the source code.
6995void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6996 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00006997
Douglas Gregor77b50e12009-06-22 23:06:13 +00006998 if (D->isUsed())
6999 return;
Mike Stump11289f42009-09-09 15:08:12 +00007000
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00007001 // Mark a parameter or variable declaration "used", regardless of whether we're in a
7002 // template or not. The reason for this is that unevaluated expressions
7003 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
7004 // -Wunused-parameters)
7005 if (isa<ParmVarDecl>(D) ||
7006 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007007 D->setUsed(true);
Mike Stump11289f42009-09-09 15:08:12 +00007008
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007009 // Do not mark anything as "used" within a dependent context; wait for
7010 // an instantiation.
7011 if (CurContext->isDependentContext())
7012 return;
Mike Stump11289f42009-09-09 15:08:12 +00007013
Douglas Gregorff790f12009-11-26 00:44:06 +00007014 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007015 case Unevaluated:
7016 // We are in an expression that is not potentially evaluated; do nothing.
7017 return;
Mike Stump11289f42009-09-09 15:08:12 +00007018
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007019 case PotentiallyEvaluated:
7020 // We are in a potentially-evaluated expression, so this declaration is
7021 // "used"; handle this below.
7022 break;
Mike Stump11289f42009-09-09 15:08:12 +00007023
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007024 case PotentiallyPotentiallyEvaluated:
7025 // We are in an expression that may be potentially evaluated; queue this
7026 // declaration reference until we know whether the expression is
7027 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00007028 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007029 return;
7030 }
Mike Stump11289f42009-09-09 15:08:12 +00007031
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007032 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00007033 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007034 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00007035 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
7036 if (!Constructor->isUsed())
7037 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00007038 } else if (Constructor->isImplicit() &&
Mike Stump12b8ce12009-08-04 21:02:39 +00007039 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007040 if (!Constructor->isUsed())
7041 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7042 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007043
7044 MaybeMarkVirtualMembersReferenced(Loc, Constructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007045 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
7046 if (Destructor->isImplicit() && !Destructor->isUsed())
7047 DefineImplicitDestructor(Loc, Destructor);
Mike Stump11289f42009-09-09 15:08:12 +00007048
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007049 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7050 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7051 MethodDecl->getOverloadedOperator() == OO_Equal) {
7052 if (!MethodDecl->isUsed())
7053 DefineImplicitOverloadedAssign(Loc, MethodDecl);
7054 }
7055 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00007056 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00007057 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00007058 // class templates.
Douglas Gregorafca3b42009-10-27 20:53:28 +00007059 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00007060 bool AlreadyInstantiated = false;
7061 if (FunctionTemplateSpecializationInfo *SpecInfo
7062 = Function->getTemplateSpecializationInfo()) {
7063 if (SpecInfo->getPointOfInstantiation().isInvalid())
7064 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregorafca3b42009-10-27 20:53:28 +00007065 else if (SpecInfo->getTemplateSpecializationKind()
7066 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00007067 AlreadyInstantiated = true;
7068 } else if (MemberSpecializationInfo *MSInfo
7069 = Function->getMemberSpecializationInfo()) {
7070 if (MSInfo->getPointOfInstantiation().isInvalid())
7071 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregorafca3b42009-10-27 20:53:28 +00007072 else if (MSInfo->getTemplateSpecializationKind()
7073 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00007074 AlreadyInstantiated = true;
7075 }
7076
7077 if (!AlreadyInstantiated)
7078 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
7079 }
7080
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007081 // FIXME: keep track of references to static functions
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007082 Function->setUsed(true);
7083 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00007084 }
Mike Stump11289f42009-09-09 15:08:12 +00007085
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007086 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007087 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00007088 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00007089 Var->getInstantiatedFromStaticDataMember()) {
7090 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7091 assert(MSInfo && "Missing member specialization information?");
7092 if (MSInfo->getPointOfInstantiation().isInvalid() &&
7093 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7094 MSInfo->setPointOfInstantiation(Loc);
7095 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7096 }
7097 }
Mike Stump11289f42009-09-09 15:08:12 +00007098
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007099 // FIXME: keep track of references to static data?
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007100
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007101 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007102 return;
Sam Weinigbae69142009-09-11 03:29:30 +00007103 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007104}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007105
7106bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7107 CallExpr *CE, FunctionDecl *FD) {
7108 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7109 return false;
7110
7111 PartialDiagnostic Note =
7112 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7113 << FD->getDeclName() : PDiag();
7114 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
7115
7116 if (RequireCompleteType(Loc, ReturnType,
7117 FD ?
7118 PDiag(diag::err_call_function_incomplete_return)
7119 << CE->getSourceRange() << FD->getDeclName() :
7120 PDiag(diag::err_call_incomplete_return)
7121 << CE->getSourceRange(),
7122 std::make_pair(NoteLoc, Note)))
7123 return true;
7124
7125 return false;
7126}
7127
John McCalld5707ab2009-10-12 21:59:07 +00007128// Diagnose the common s/=/==/ typo. Note that adding parentheses
7129// will prevent this condition from triggering, which is what we want.
7130void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7131 SourceLocation Loc;
7132
John McCall0506e4a2009-11-11 02:41:58 +00007133 unsigned diagnostic = diag::warn_condition_is_assignment;
7134
John McCalld5707ab2009-10-12 21:59:07 +00007135 if (isa<BinaryOperator>(E)) {
7136 BinaryOperator *Op = cast<BinaryOperator>(E);
7137 if (Op->getOpcode() != BinaryOperator::Assign)
7138 return;
7139
John McCallb0e419e2009-11-12 00:06:05 +00007140 // Greylist some idioms by putting them into a warning subcategory.
7141 if (ObjCMessageExpr *ME
7142 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7143 Selector Sel = ME->getSelector();
7144
John McCallb0e419e2009-11-12 00:06:05 +00007145 // self = [<foo> init...]
7146 if (isSelfExpr(Op->getLHS())
7147 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7148 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7149
7150 // <foo> = [<bar> nextObject]
7151 else if (Sel.isUnarySelector() &&
7152 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7153 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7154 }
John McCall0506e4a2009-11-11 02:41:58 +00007155
John McCalld5707ab2009-10-12 21:59:07 +00007156 Loc = Op->getOperatorLoc();
7157 } else if (isa<CXXOperatorCallExpr>(E)) {
7158 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7159 if (Op->getOperator() != OO_Equal)
7160 return;
7161
7162 Loc = Op->getOperatorLoc();
7163 } else {
7164 // Not an assignment.
7165 return;
7166 }
7167
John McCalld5707ab2009-10-12 21:59:07 +00007168 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00007169 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCalld5707ab2009-10-12 21:59:07 +00007170
John McCall0506e4a2009-11-11 02:41:58 +00007171 Diag(Loc, diagnostic)
John McCalld5707ab2009-10-12 21:59:07 +00007172 << E->getSourceRange()
7173 << CodeModificationHint::CreateInsertion(Open, "(")
7174 << CodeModificationHint::CreateInsertion(Close, ")");
7175}
7176
7177bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7178 DiagnoseAssignmentAsCondition(E);
7179
7180 if (!E->isTypeDependent()) {
7181 DefaultFunctionArrayConversion(E);
7182
7183 QualType T = E->getType();
7184
7185 if (getLangOptions().CPlusPlus) {
7186 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7187 return true;
7188 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7189 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7190 << T << E->getSourceRange();
7191 return true;
7192 }
7193 }
7194
7195 return false;
7196}