blob: 2d3aaf6edc05daf74742b8bdc70061ec94b270b0 [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"
Douglas Gregor85dabae2009-12-16 01:38:02 +000015#include "SemaInit.h"
John McCall5cebab12009-11-18 07:57:50 +000016#include "Lookup.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000017#include "AnalysisBasedWarnings.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000018#include "clang/AST/ASTContext.h"
Douglas Gregord1702062010-04-29 00:18:15 +000019#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000021#include "clang/AST/DeclTemplate.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000022#include "clang/AST/Expr.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000023#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregor5597ab42010-05-07 23:12:07 +000025#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000026#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000027#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000028#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000029#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000030#include "clang/Lex/LiteralSupport.h"
31#include "clang/Lex/Preprocessor.h"
Steve Naroffc540d662008-09-03 18:15:37 +000032#include "clang/Parse/DeclSpec.h"
Chris Lattner07d754a2008-10-26 23:43:26 +000033#include "clang/Parse/Designator.h"
Steve Naroffc540d662008-09-03 18:15:37 +000034#include "clang/Parse/Scope.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000035#include "clang/Parse/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000036using namespace clang;
37
David Chisnall9f57c292009-08-17 16:35:33 +000038
Douglas Gregor171c45a2009-02-18 21:56:37 +000039/// \brief Determine whether the use of this declaration is valid, and
40/// emit any corresponding diagnostics.
41///
42/// This routine diagnoses various problems with referencing
43/// declarations that can occur when using a declaration. For example,
44/// it might warn if a deprecated or unavailable declaration is being
45/// used, or produce an error (and return true) if a C++0x deleted
46/// function is being used.
47///
Chris Lattnerb7df3c62009-10-25 22:31:57 +000048/// If IgnoreDeprecated is set to true, this should not want about deprecated
49/// decls.
50///
Douglas Gregor171c45a2009-02-18 21:56:37 +000051/// \returns true if there was an error (this declaration cannot be
52/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000053///
John McCall28a6aea2009-11-04 02:18:39 +000054bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner4bf74fd2009-02-15 22:43:40 +000055 // See if the decl is deprecated.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000056 if (D->getAttr<DeprecatedAttr>()) {
John McCall28a6aea2009-11-04 02:18:39 +000057 EmitDeprecationWarning(D, Loc);
Chris Lattner4bf74fd2009-02-15 22:43:40 +000058 }
59
Chris Lattnera27dd592009-10-25 17:21:40 +000060 // See if the decl is unavailable
61 if (D->getAttr<UnavailableAttr>()) {
62 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
63 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
64 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000065
Douglas Gregor171c45a2009-02-18 21:56:37 +000066 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000067 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000068 if (FD->isDeleted()) {
69 Diag(Loc, diag::err_deleted_function_use);
70 Diag(D->getLocation(), diag::note_unavailable_here) << true;
71 return true;
72 }
Douglas Gregorde681d42009-02-24 04:26:15 +000073 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000074
Douglas Gregor171c45a2009-02-18 21:56:37 +000075 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +000076}
77
Fariborz Jahanian027b8862009-05-13 18:09:35 +000078/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +000079/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +000080/// attribute. It warns if call does not have the sentinel argument.
81///
82void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +000083 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000084 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +000085 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +000086 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +000087
88 // FIXME: In C++0x, if any of the arguments are parameter pack
89 // expansions, we can't check for the sentinel now.
Fariborz Jahanian9e877212009-05-13 23:20:50 +000090 int sentinelPos = attr->getSentinel();
91 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +000092
Mike Stump87c57ac2009-05-16 07:39:55 +000093 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
94 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +000095 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +000096 bool warnNotEnoughArgs = false;
97 int isMethod = 0;
98 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
99 // skip over named parameters.
100 ObjCMethodDecl::param_iterator P, E = MD->param_end();
101 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
102 if (nullPos)
103 --nullPos;
104 else
105 ++i;
106 }
107 warnNotEnoughArgs = (P != E || i >= NumArgs);
108 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000109 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000110 // skip over named parameters.
111 ObjCMethodDecl::param_iterator P, E = FD->param_end();
112 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
113 if (nullPos)
114 --nullPos;
115 else
116 ++i;
117 }
118 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000119 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000120 // block or function pointer call.
121 QualType Ty = V->getType();
122 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000123 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000124 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
125 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000126 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
127 unsigned NumArgsInProto = Proto->getNumArgs();
128 unsigned k;
129 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
130 if (nullPos)
131 --nullPos;
132 else
133 ++i;
134 }
135 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
136 }
137 if (Ty->isBlockPointerType())
138 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000139 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000140 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000141 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000142 return;
143
144 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000145 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000146 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000147 return;
148 }
149 int sentinel = i;
150 while (sentinelPos > 0 && i < NumArgs-1) {
151 --sentinelPos;
152 ++i;
153 }
154 if (sentinelPos > 0) {
155 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000156 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000157 return;
158 }
159 while (i < NumArgs-1) {
160 ++i;
161 ++sentinel;
162 }
163 Expr *sentinelExpr = Args[sentinel];
John McCall7ddbcf42010-05-06 23:53:00 +0000164 if (!sentinelExpr) return;
165 if (sentinelExpr->isTypeDependent()) return;
166 if (sentinelExpr->isValueDependent()) return;
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000167 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-05-06 23:53:00 +0000168 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
169 Expr::NPC_ValueDependentIsNull))
170 return;
171
172 // Unfortunately, __null has type 'int'.
173 if (isa<GNUNullExpr>(sentinelExpr)) return;
174
175 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
176 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000177}
178
Douglas Gregor87f95b02009-02-26 21:00:50 +0000179SourceRange Sema::getExprRange(ExprTy *E) const {
180 Expr *Ex = (Expr *)E;
181 return Ex? Ex->getSourceRange() : SourceRange();
182}
183
Chris Lattner513165e2008-07-25 21:10:04 +0000184//===----------------------------------------------------------------------===//
185// Standard Promotions and Conversions
186//===----------------------------------------------------------------------===//
187
Chris Lattner513165e2008-07-25 21:10:04 +0000188/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
189void Sema::DefaultFunctionArrayConversion(Expr *&E) {
190 QualType Ty = E->getType();
191 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
192
Chris Lattner513165e2008-07-25 21:10:04 +0000193 if (Ty->isFunctionType())
Mike Stump11289f42009-09-09 15:08:12 +0000194 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlsson6904f642009-09-01 20:37:18 +0000195 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000196 else if (Ty->isArrayType()) {
197 // In C90 mode, arrays only promote to pointers if the array expression is
198 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
199 // type 'array of type' is converted to an expression that has type 'pointer
200 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
201 // that has type 'array of type' ...". The relevant change is "an lvalue"
202 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000203 //
204 // C++ 4.2p1:
205 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
206 // T" can be converted to an rvalue of type "pointer to T".
207 //
208 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
209 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson8fc489d2009-08-07 23:48:20 +0000210 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
211 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000212 }
Chris Lattner513165e2008-07-25 21:10:04 +0000213}
214
Douglas Gregorb92a1562010-02-03 00:27:59 +0000215void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
216 DefaultFunctionArrayConversion(E);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000217
Douglas Gregorb92a1562010-02-03 00:27:59 +0000218 QualType Ty = E->getType();
219 assert(!Ty.isNull() && "DefaultFunctionArrayLvalueConversion - missing type");
220 if (!Ty->isDependentType() && Ty.hasQualifiers() &&
221 (!getLangOptions().CPlusPlus || !Ty->isRecordType()) &&
222 E->isLvalue(Context) == Expr::LV_Valid) {
223 // C++ [conv.lval]p1:
224 // [...] If T is a non-class type, the type of the rvalue is the
225 // cv-unqualified version of T. Otherwise, the type of the
226 // rvalue is T
227 //
228 // C99 6.3.2.1p2:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000229 // If the lvalue has qualified type, the value has the unqualified
230 // version of the type of the lvalue; otherwise, the value has the
Douglas Gregorb92a1562010-02-03 00:27:59 +0000231 // type of the lvalue.
232 ImpCastExprToType(E, Ty.getUnqualifiedType(), CastExpr::CK_NoOp);
233 }
234}
235
236
Chris Lattner513165e2008-07-25 21:10:04 +0000237/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000238/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner513165e2008-07-25 21:10:04 +0000239/// sometimes surpressed. For example, the array->pointer conversion doesn't
240/// apply if the array is an argument to the sizeof or address (&) operators.
241/// In these instances, this routine should *not* be called.
242Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
243 QualType Ty = Expr->getType();
244 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000245
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000246 // C99 6.3.1.1p2:
247 //
248 // The following may be used in an expression wherever an int or
249 // unsigned int may be used:
250 // - an object or expression with an integer type whose integer
251 // conversion rank is less than or equal to the rank of int
252 // and unsigned int.
253 // - A bit-field of type _Bool, int, signed int, or unsigned int.
254 //
255 // If an int can represent all values of the original type, the
256 // value is converted to an int; otherwise, it is converted to an
257 // unsigned int. These are called the integer promotions. All
258 // other types are unchanged by the integer promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000259 QualType PTy = Context.isPromotableBitField(Expr);
260 if (!PTy.isNull()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +0000261 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman629ffb92009-08-20 04:21:42 +0000262 return Expr;
263 }
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000264 if (Ty->isPromotableIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000265 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman06ed2a52009-10-20 08:27:19 +0000266 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000267 return Expr;
Eli Friedman629ffb92009-08-20 04:21:42 +0000268 }
269
Douglas Gregorb92a1562010-02-03 00:27:59 +0000270 DefaultFunctionArrayLvalueConversion(Expr);
Chris Lattner513165e2008-07-25 21:10:04 +0000271 return Expr;
272}
273
Chris Lattner2ce500f2008-07-25 22:25:12 +0000274/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000275/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000276/// double. All other argument types are converted by UsualUnaryConversions().
277void Sema::DefaultArgumentPromotion(Expr *&Expr) {
278 QualType Ty = Expr->getType();
279 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000280
Chris Lattner2ce500f2008-07-25 22:25:12 +0000281 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000282 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
283 return ImpCastExprToType(Expr, Context.DoubleTy,
284 CastExpr::CK_FloatingCast);
Mike Stump11289f42009-09-09 15:08:12 +0000285
Chris Lattner2ce500f2008-07-25 22:25:12 +0000286 UsualUnaryConversions(Expr);
287}
288
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000289/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
290/// will warn if the resulting type is not a POD type, and rejects ObjC
291/// interfaces passed by value. This returns true if the argument type is
292/// completely illegal.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000293bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
294 FunctionDecl *FDecl) {
Anders Carlssona7d069d2009-01-16 16:48:51 +0000295 DefaultArgumentPromotion(Expr);
Mike Stump11289f42009-09-09 15:08:12 +0000296
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000297 // __builtin_va_start takes the second argument as a "varargs" argument, but
298 // it doesn't actually do anything with it. It doesn't need to be non-pod
299 // etc.
300 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
301 return false;
302
John McCall8b07ec22010-05-15 11:32:37 +0000303 if (Expr->getType()->isObjCObjectType() &&
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000304 DiagRuntimeBehavior(Expr->getLocStart(),
305 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
306 << Expr->getType() << CT))
307 return true;
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000308
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000309 if (!Expr->getType()->isPODType() &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000310 DiagRuntimeBehavior(Expr->getLocStart(),
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000311 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
312 << Expr->getType() << CT))
313 return true;
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000314
315 return false;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000316}
317
318
Chris Lattner513165e2008-07-25 21:10:04 +0000319/// UsualArithmeticConversions - Performs various conversions that are common to
320/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000321/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000322/// responsible for emitting appropriate error diagnostics.
323/// FIXME: verify the conversion rules for "complex int" are consistent with
324/// GCC.
325QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
326 bool isCompAssign) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000327 if (!isCompAssign)
Chris Lattner513165e2008-07-25 21:10:04 +0000328 UsualUnaryConversions(lhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000329
330 UsualUnaryConversions(rhsExpr);
Douglas Gregora11693b2008-11-12 17:17:38 +0000331
Mike Stump11289f42009-09-09 15:08:12 +0000332 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000333 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000334 QualType lhs =
335 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000336 QualType rhs =
Chris Lattner574dee62008-07-26 22:17:49 +0000337 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000338
339 // If both types are identical, no conversion is needed.
340 if (lhs == rhs)
341 return lhs;
342
343 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
344 // The caller can deal with this (e.g. pointer + int).
345 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
346 return lhs;
347
Douglas Gregord2c2d172009-05-02 00:36:19 +0000348 // Perform bitfield promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000349 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000350 if (!LHSBitfieldPromoteTy.isNull())
351 lhs = LHSBitfieldPromoteTy;
Eli Friedman629ffb92009-08-20 04:21:42 +0000352 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000353 if (!RHSBitfieldPromoteTy.isNull())
354 rhs = RHSBitfieldPromoteTy;
355
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000356 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000357 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +0000358 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
359 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregora11693b2008-11-12 17:17:38 +0000360 return destType;
361}
362
Chris Lattner513165e2008-07-25 21:10:04 +0000363//===----------------------------------------------------------------------===//
364// Semantic Analysis for various Expression Types
365//===----------------------------------------------------------------------===//
366
367
Steve Naroff83895f72007-09-16 03:34:24 +0000368/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000369/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
370/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
371/// multiple tokens. However, the common case is that StringToks points to one
372/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000373///
374Action::OwningExprResult
Steve Naroff83895f72007-09-16 03:34:24 +0000375Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000376 assert(NumStringToks && "Must have at least one string!");
377
Chris Lattner8a24e582009-01-16 18:51:42 +0000378 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000379 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000380 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000381
Chris Lattner23b7eb62007-06-15 23:05:46 +0000382 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000383 for (unsigned i = 0; i != NumStringToks; ++i)
384 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000385
Chris Lattner36fc8792008-02-11 00:02:17 +0000386 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidiscbad7252008-08-09 17:20:01 +0000387 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattner36fc8792008-02-11 00:02:17 +0000388 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000389
390 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +0000391 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000392 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000393
Chris Lattner36fc8792008-02-11 00:02:17 +0000394 // Get an array type for the string, according to C99 6.4.5. This includes
395 // the nul terminator character as well as the string length for pascal
396 // strings.
397 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000398 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000399 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000400
Chris Lattner5b183d82006-11-10 05:03:26 +0000401 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump11289f42009-09-09 15:08:12 +0000402 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000403 Literal.GetStringLength(),
404 Literal.AnyWide, StrTy,
405 &StringTokLocs[0],
406 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000407}
408
Chris Lattner2a9d9892008-10-20 05:16:36 +0000409/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
410/// CurBlock to VD should cause it to be snapshotted (as we do for auto
411/// variables defined outside the block) or false if this is not needed (e.g.
412/// for values inside the block or for globals).
413///
Douglas Gregor4f13beb2010-03-01 20:44:28 +0000414/// This also keeps the 'hasBlockDeclRefExprs' in the BlockScopeInfo records
Chris Lattner497d7b02009-04-21 22:26:47 +0000415/// up-to-date.
416///
Douglas Gregor9a28e842010-03-01 23:15:13 +0000417static bool ShouldSnapshotBlockValueReference(Sema &S, BlockScopeInfo *CurBlock,
Chris Lattner2a9d9892008-10-20 05:16:36 +0000418 ValueDecl *VD) {
419 // If the value is defined inside the block, we couldn't snapshot it even if
420 // we wanted to.
421 if (CurBlock->TheDecl == VD->getDeclContext())
422 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000423
Chris Lattner2a9d9892008-10-20 05:16:36 +0000424 // If this is an enum constant or function, it is constant, don't snapshot.
425 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
426 return false;
427
428 // If this is a reference to an extern, static, or global variable, no need to
429 // snapshot it.
430 // FIXME: What about 'const' variables in C++?
431 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner497d7b02009-04-21 22:26:47 +0000432 if (!Var->hasLocalStorage())
433 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000434
Chris Lattner497d7b02009-04-21 22:26:47 +0000435 // Blocks that have these can't be constant.
436 CurBlock->hasBlockDeclRefExprs = true;
437
438 // If we have nested blocks, the decl may be declared in an outer block (in
439 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
440 // be defined outside all of the current blocks (in which case the blocks do
441 // all get the bit). Walk the nesting chain.
Douglas Gregor9a28e842010-03-01 23:15:13 +0000442 for (unsigned I = S.FunctionScopes.size() - 1; I; --I) {
443 BlockScopeInfo *NextBlock = dyn_cast<BlockScopeInfo>(S.FunctionScopes[I]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000444
Douglas Gregor9a28e842010-03-01 23:15:13 +0000445 if (!NextBlock)
446 continue;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000447
Chris Lattner497d7b02009-04-21 22:26:47 +0000448 // If we found the defining block for the variable, don't mark the block as
449 // having a reference outside it.
450 if (NextBlock->TheDecl == VD->getDeclContext())
451 break;
Mike Stump11289f42009-09-09 15:08:12 +0000452
Chris Lattner497d7b02009-04-21 22:26:47 +0000453 // Otherwise, the DeclRef from the inner block causes the outer one to need
454 // a snapshot as well.
455 NextBlock->hasBlockDeclRefExprs = true;
456 }
Mike Stump11289f42009-09-09 15:08:12 +0000457
Chris Lattner2a9d9892008-10-20 05:16:36 +0000458 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000459}
460
Chris Lattner2a9d9892008-10-20 05:16:36 +0000461
462
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000463/// BuildDeclRefExpr - Build a DeclRefExpr.
Anders Carlsson946b86d2009-06-24 00:10:43 +0000464Sema::OwningExprResult
John McCallce546572009-12-08 09:08:17 +0000465Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc,
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000466 const CXXScopeSpec *SS) {
Anders Carlsson364035d12009-06-26 19:16:07 +0000467 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
468 Diag(Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000469 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlsson364035d12009-06-26 19:16:07 +0000470 << D->getDeclName();
471 return ExprError();
472 }
Mike Stump11289f42009-09-09 15:08:12 +0000473
Anders Carlsson946b86d2009-06-24 00:10:43 +0000474 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Douglas Gregor15243332010-04-27 21:10:04 +0000475 if (isa<NonTypeTemplateParmDecl>(VD)) {
476 // Non-type template parameters can be referenced anywhere they are
477 // visible.
Douglas Gregora8a089b2010-07-13 18:40:04 +0000478 Ty = Ty.getNonLValueExprType(Context);
Douglas Gregor15243332010-04-27 21:10:04 +0000479 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
Anders Carlsson946b86d2009-06-24 00:10:43 +0000480 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
481 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Mike Stump11289f42009-09-09 15:08:12 +0000482 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000483 << D->getIdentifier() << FD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +0000484 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000485 << D->getIdentifier();
486 return ExprError();
487 }
488 }
489 }
490 }
Mike Stump11289f42009-09-09 15:08:12 +0000491
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000492 MarkDeclarationReferenced(Loc, D);
Mike Stump11289f42009-09-09 15:08:12 +0000493
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000494 return Owned(DeclRefExpr::Create(Context,
495 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
496 SS? SS->getRange() : SourceRange(),
Douglas Gregored6c7442009-11-23 11:41:28 +0000497 D, Loc, Ty));
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000498}
499
Douglas Gregord5846a12009-04-15 06:41:24 +0000500/// \brief Given a field that represents a member of an anonymous
501/// struct/union, build the path from that field's context to the
502/// actual member.
503///
504/// Construct the sequence of field member references we'll have to
505/// perform to get to the field in the anonymous union/struct. The
506/// list of members is built from the field outward, so traverse it
507/// backwards to go from an object in the current context to the field
508/// we found.
509///
510/// \returns The variable from which the field access should begin,
511/// for an anonymous struct/union that is not a member of another
512/// class. Otherwise, returns NULL.
513VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
514 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000515 assert(Field->getDeclContext()->isRecord() &&
516 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
517 && "Field must be stored inside an anonymous struct or union");
518
Douglas Gregord5846a12009-04-15 06:41:24 +0000519 Path.push_back(Field);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000520 VarDecl *BaseObject = 0;
521 DeclContext *Ctx = Field->getDeclContext();
522 do {
523 RecordDecl *Record = cast<RecordDecl>(Ctx);
John McCall61925b02010-05-21 01:17:40 +0000524 ValueDecl *AnonObject = Record->getAnonymousStructOrUnionObject();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000525 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregord5846a12009-04-15 06:41:24 +0000526 Path.push_back(AnonField);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000527 else {
528 BaseObject = cast<VarDecl>(AnonObject);
529 break;
530 }
531 Ctx = Ctx->getParent();
Mike Stump11289f42009-09-09 15:08:12 +0000532 } while (Ctx->isRecord() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000533 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregord5846a12009-04-15 06:41:24 +0000534
535 return BaseObject;
536}
537
538Sema::OwningExprResult
539Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
540 FieldDecl *Field,
541 Expr *BaseObjectExpr,
542 SourceLocation OpLoc) {
543 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump11289f42009-09-09 15:08:12 +0000544 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregord5846a12009-04-15 06:41:24 +0000545 AnonFields);
546
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000547 // Build the expression that refers to the base object, from
548 // which we will build a sequence of member references to each
549 // of the anonymous union objects and, eventually, the field we
550 // found via name lookup.
551 bool BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000552 Qualifiers BaseQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000553 if (BaseObject) {
554 // BaseObject is an anonymous struct/union variable (and is,
555 // therefore, not part of another non-anonymous record).
Ted Kremenek5a201952009-02-07 01:47:29 +0000556 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000557 MarkDeclarationReferenced(Loc, BaseObject);
Steve Narofff6009ed2009-01-21 00:14:39 +0000558 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump4e1f26a2009-02-19 03:04:26 +0000559 SourceLocation());
John McCall8ccfcb52009-09-24 19:53:00 +0000560 BaseQuals
561 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000562 } else if (BaseObjectExpr) {
563 // The caller provided the base object expression. Determine
564 // whether its a pointer and whether it adds any qualifiers to the
565 // anonymous struct/union fields we're looking into.
566 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000567 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000568 BaseObjectIsPointer = true;
569 ObjectType = ObjectPtr->getPointeeType();
570 }
John McCall8ccfcb52009-09-24 19:53:00 +0000571 BaseQuals
572 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000573 } else {
574 // We've found a member of an anonymous struct/union that is
575 // inside a non-anonymous struct/union, so in a well-formed
576 // program our base object expression is "this".
John McCall87fe5d52010-05-20 01:18:31 +0000577 DeclContext *DC = getFunctionLevelDeclContext();
578 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000579 if (!MD->isStatic()) {
Mike Stump11289f42009-09-09 15:08:12 +0000580 QualType AnonFieldType
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000581 = Context.getTagDeclType(
582 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
583 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump11289f42009-09-09 15:08:12 +0000584 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000585 == Context.getCanonicalType(ThisType)) ||
586 IsDerivedFrom(ThisType, AnonFieldType)) {
587 // Our base object expression is "this".
Douglas Gregor4b654412009-12-24 20:23:34 +0000588 BaseObjectExpr = new (Context) CXXThisExpr(Loc,
Douglas Gregorb15af892010-01-07 23:12:05 +0000589 MD->getThisType(Context),
590 /*isImplicit=*/true);
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);
John McCall16df1e52010-03-30 21:47:33 +0000632 PerformObjectMemberConversion(Result, /*FIXME:Qualifier=*/0, *FI, *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
John McCall69f9dbc2010-02-08 19:26:07 +0000681/// Determines whether the given record is "fully-formed" at the given
682/// location, i.e. whether a qualified lookup into it is assured of
683/// getting consistent results already.
John McCall10eae182009-11-30 22:42:35 +0000684static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
John McCall69f9dbc2010-02-08 19:26:07 +0000685 if (!Record->hasDefinition())
686 return false;
687
John McCall10eae182009-11-30 22:42:35 +0000688 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
689 E = Record->bases_end(); I != E; ++I) {
690 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
691 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
692 if (!BaseRT) return false;
693
694 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall69f9dbc2010-02-08 19:26:07 +0000695 if (!BaseRecord->hasDefinition() ||
John McCall10eae182009-11-30 22:42:35 +0000696 !IsFullyFormedScope(SemaRef, BaseRecord))
697 return false;
698 }
699
700 return true;
701}
702
John McCallf786fb12009-11-30 23:50:49 +0000703/// Determines whether we can lookup this id-expression now or whether
704/// we have to wait until template instantiation is complete.
705static bool IsDependentIdExpression(Sema &SemaRef, const CXXScopeSpec &SS) {
John McCall10eae182009-11-30 22:42:35 +0000706 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
John McCall10eae182009-11-30 22:42:35 +0000707
John McCallf786fb12009-11-30 23:50:49 +0000708 // If the qualifier scope isn't computable, it's definitely dependent.
709 if (!DC) return true;
710
711 // If the qualifier scope doesn't name a record, we can always look into it.
712 if (!isa<CXXRecordDecl>(DC)) return false;
713
714 // We can't look into record types unless they're fully-formed.
715 if (!IsFullyFormedScope(SemaRef, cast<CXXRecordDecl>(DC))) return true;
716
John McCall2d74de92009-12-01 22:10:20 +0000717 return false;
718}
John McCallf786fb12009-11-30 23:50:49 +0000719
John McCall2d74de92009-12-01 22:10:20 +0000720/// Determines if the given class is provably not derived from all of
721/// the prospective base classes.
722static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
723 CXXRecordDecl *Record,
724 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +0000725 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +0000726 return false;
727
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000728 RecordDecl *RD = Record->getDefinition();
John McCalla6d407c2009-12-01 22:28:41 +0000729 if (!RD) return false;
730 Record = cast<CXXRecordDecl>(RD);
731
John McCall2d74de92009-12-01 22:10:20 +0000732 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
733 E = Record->bases_end(); I != E; ++I) {
734 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
735 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
736 if (!BaseRT) return false;
737
738 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +0000739 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
740 return false;
741 }
742
743 return true;
744}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000745
John McCall2d74de92009-12-01 22:10:20 +0000746enum IMAKind {
747 /// The reference is definitely not an instance member access.
748 IMA_Static,
749
750 /// The reference may be an implicit instance member access.
751 IMA_Mixed,
752
753 /// The reference may be to an instance member, but it is invalid if
754 /// so, because the context is not an instance method.
755 IMA_Mixed_StaticContext,
756
757 /// The reference may be to an instance member, but it is invalid if
758 /// so, because the context is from an unrelated class.
759 IMA_Mixed_Unrelated,
760
761 /// The reference is definitely an implicit instance member access.
762 IMA_Instance,
763
764 /// The reference may be to an unresolved using declaration.
765 IMA_Unresolved,
766
767 /// The reference may be to an unresolved using declaration and the
768 /// context is not an instance method.
769 IMA_Unresolved_StaticContext,
770
771 /// The reference is to a member of an anonymous structure in a
772 /// non-class context.
773 IMA_AnonymousMember,
774
775 /// All possible referrents are instance members and the current
776 /// context is not an instance method.
777 IMA_Error_StaticContext,
778
779 /// All possible referrents are instance members of an unrelated
780 /// class.
781 IMA_Error_Unrelated
782};
783
784/// The given lookup names class member(s) and is not being used for
785/// an address-of-member expression. Classify the type of access
786/// according to whether it's possible that this reference names an
787/// instance member. This is best-effort; it is okay to
788/// conservatively answer "yes", in which case some errors will simply
789/// not be caught until template-instantiation.
790static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
791 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +0000792 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +0000793
John McCall87fe5d52010-05-20 01:18:31 +0000794 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCall2d74de92009-12-01 22:10:20 +0000795 bool isStaticContext =
John McCall87fe5d52010-05-20 01:18:31 +0000796 (!isa<CXXMethodDecl>(DC) ||
797 cast<CXXMethodDecl>(DC)->isStatic());
John McCall2d74de92009-12-01 22:10:20 +0000798
799 if (R.isUnresolvableResult())
800 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
801
802 // Collect all the declaring classes of instance members we find.
803 bool hasNonInstance = false;
804 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
805 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCalla8ae2222010-04-06 21:38:20 +0000806 NamedDecl *D = *I;
807 if (D->isCXXInstanceMember()) {
John McCall2d74de92009-12-01 22:10:20 +0000808 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
809
810 // If this is a member of an anonymous record, move out to the
811 // innermost non-anonymous struct or union. If there isn't one,
812 // that's a special case.
813 while (R->isAnonymousStructOrUnion()) {
814 R = dyn_cast<CXXRecordDecl>(R->getParent());
815 if (!R) return IMA_AnonymousMember;
816 }
817 Classes.insert(R->getCanonicalDecl());
818 }
819 else
820 hasNonInstance = true;
821 }
822
823 // If we didn't find any instance members, it can't be an implicit
824 // member reference.
825 if (Classes.empty())
826 return IMA_Static;
827
828 // If the current context is not an instance method, it can't be
829 // an implicit member reference.
830 if (isStaticContext)
831 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
832
833 // If we can prove that the current context is unrelated to all the
834 // declaring classes, it can't be an implicit member reference (in
835 // which case it's an error if any of those members are selected).
836 if (IsProvablyNotDerivedFrom(SemaRef,
John McCall87fe5d52010-05-20 01:18:31 +0000837 cast<CXXMethodDecl>(DC)->getParent(),
John McCall2d74de92009-12-01 22:10:20 +0000838 Classes))
839 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
840
841 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
842}
843
844/// Diagnose a reference to a field with no object available.
845static void DiagnoseInstanceReference(Sema &SemaRef,
846 const CXXScopeSpec &SS,
847 const LookupResult &R) {
848 SourceLocation Loc = R.getNameLoc();
849 SourceRange Range(Loc);
850 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
851
852 if (R.getAsSingle<FieldDecl>()) {
853 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
854 if (MD->isStatic()) {
855 // "invalid use of member 'x' in static member function"
856 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
857 << Range << R.getLookupName();
858 return;
859 }
860 }
861
862 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
863 << R.getLookupName() << Range;
864 return;
865 }
866
867 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +0000868}
869
John McCalld681c392009-12-16 08:11:27 +0000870/// Diagnose an empty lookup.
871///
872/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000873bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
874 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +0000875 DeclarationName Name = R.getLookupName();
876
John McCalld681c392009-12-16 08:11:27 +0000877 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +0000878 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +0000879 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
880 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +0000881 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +0000882 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +0000883 diagnostic_suggest = diag::err_undeclared_use_suggest;
884 }
John McCalld681c392009-12-16 08:11:27 +0000885
Douglas Gregor598b08f2009-12-31 05:20:13 +0000886 // If the original lookup was an unqualified lookup, fake an
887 // unqualified lookup. This is useful when (for example) the
888 // original lookup would not have found something because it was a
889 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000890 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +0000891 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +0000892 if (isa<CXXRecordDecl>(DC)) {
893 LookupQualifiedName(R, DC);
894
895 if (!R.empty()) {
896 // Don't give errors about ambiguities in this lookup.
897 R.suppressDiagnostics();
898
899 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
900 bool isInstance = CurMethod &&
901 CurMethod->isInstance() &&
902 DC == CurMethod->getParent();
903
904 // Give a code modification hint to insert 'this->'.
905 // TODO: fixit for inserting 'Base<T>::' in the other cases.
906 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000907 if (isInstance) {
John McCalld681c392009-12-16 08:11:27 +0000908 Diag(R.getNameLoc(), diagnostic) << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000909 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000910
911 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
912 CallsUndergoingInstantiation.back()->getCallee());
913 CXXMethodDecl *DepMethod = cast<CXXMethodDecl>(
914 CurMethod->getInstantiatedFromMemberFunction());
915 QualType DepThisType = DepMethod->getThisType(Context);
916 CXXThisExpr *DepThis = new (Context) CXXThisExpr(R.getNameLoc(),
917 DepThisType, false);
918 TemplateArgumentListInfo TList;
919 if (ULE->hasExplicitTemplateArgs())
920 ULE->copyTemplateArgumentsInto(TList);
921 CXXDependentScopeMemberExpr *DepExpr =
922 CXXDependentScopeMemberExpr::Create(
923 Context, DepThis, DepThisType, true, SourceLocation(),
924 ULE->getQualifier(), ULE->getQualifierRange(), NULL, Name,
925 R.getNameLoc(), &TList);
926 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
927 } else {
John McCalld681c392009-12-16 08:11:27 +0000928 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000929 }
John McCalld681c392009-12-16 08:11:27 +0000930
931 // Do we really want to note all of these?
932 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
933 Diag((*I)->getLocation(), diag::note_dependent_var_use);
934
935 // Tell the callee to try to recover.
936 return false;
937 }
938 }
939 }
940
Douglas Gregor598b08f2009-12-31 05:20:13 +0000941 // We didn't find anything, so try to correct for a typo.
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000942 DeclarationName Corrected;
Daniel Dunbarf7ced252010-06-02 15:46:52 +0000943 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000944 if (!R.empty()) {
945 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
946 if (SS.isEmpty())
947 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
948 << FixItHint::CreateReplacement(R.getNameLoc(),
949 R.getLookupName().getAsString());
950 else
951 Diag(R.getNameLoc(), diag::err_no_member_suggest)
952 << Name << computeDeclContext(SS, false) << R.getLookupName()
953 << SS.getRange()
954 << FixItHint::CreateReplacement(R.getNameLoc(),
955 R.getLookupName().getAsString());
956 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
957 Diag(ND->getLocation(), diag::note_previous_decl)
958 << ND->getDeclName();
959
960 // Tell the callee to try to recover.
961 return false;
962 }
Alexis Huntc46382e2010-04-28 23:02:27 +0000963
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000964 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
965 // FIXME: If we ended up with a typo for a type name or
966 // Objective-C class name, we're in trouble because the parser
967 // is in the wrong place to recover. Suggest the typo
968 // correction, but don't make it a fix-it since we're not going
969 // to recover well anyway.
970 if (SS.isEmpty())
971 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
972 else
973 Diag(R.getNameLoc(), diag::err_no_member_suggest)
974 << Name << computeDeclContext(SS, false) << R.getLookupName()
975 << SS.getRange();
976
977 // Don't try to recover; it won't work.
978 return true;
979 }
980 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +0000981 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000982 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +0000983 if (SS.isEmpty())
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000984 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000985 else
Douglas Gregor25363982010-01-01 00:15:04 +0000986 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000987 << Name << computeDeclContext(SS, false) << Corrected
988 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +0000989 return true;
990 }
Douglas Gregor25363982010-01-01 00:15:04 +0000991 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +0000992 }
993
994 // Emit a special diagnostic for failed member lookups.
995 // FIXME: computing the declaration context might fail here (?)
996 if (!SS.isEmpty()) {
997 Diag(R.getNameLoc(), diag::err_no_member)
998 << Name << computeDeclContext(SS, false)
999 << SS.getRange();
1000 return true;
1001 }
1002
John McCalld681c392009-12-16 08:11:27 +00001003 // Give up, we can't recover.
1004 Diag(R.getNameLoc(), diagnostic) << Name;
1005 return true;
1006}
1007
Fariborz Jahanian18722982010-07-17 00:59:30 +00001008static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
1009 ASTContext &Context,
1010 IdentifierInfo *II,
1011 SourceLocation NameLoc) {
1012 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
1013 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1014 if (!IDecl)
1015 return 0;
1016 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1017 assert(ClassImpDecl && "Method not inside @implementation");
1018 bool DynamicImplSeen = false;
1019 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1020 if (!property)
1021 return 0;
1022 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
1023 DynamicImplSeen =
1024 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
1025 if (!DynamicImplSeen) {
1026 QualType PropType = Context.getCanonicalType(property->getType());
1027 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
1028 NameLoc,
1029 II, PropType, /*Dinfo=*/0,
1030 ObjCIvarDecl::Protected,
1031 (Expr *)0, true);
1032 ClassImpDecl->addDecl(Ivar);
1033 IDecl->makeDeclVisibleInContext(Ivar, false);
1034 property->setPropertyIvarDecl(Ivar);
1035 return Ivar;
1036 }
1037 return 0;
1038}
1039
John McCalle66edc12009-11-24 19:00:30 +00001040Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001041 CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +00001042 UnqualifiedId &Id,
1043 bool HasTrailingLParen,
1044 bool isAddressOfOperand) {
1045 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1046 "cannot be direct & operand and have a trailing lparen");
1047
1048 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001049 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001050
John McCall10eae182009-11-30 22:42:35 +00001051 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001052
1053 // Decompose the UnqualifiedId into the following data.
1054 DeclarationName Name;
1055 SourceLocation NameLoc;
1056 const TemplateArgumentListInfo *TemplateArgs;
John McCall10eae182009-11-30 22:42:35 +00001057 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
1058 Name, NameLoc, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001059
Douglas Gregor4ea80432008-11-18 15:03:34 +00001060 IdentifierInfo *II = Name.getAsIdentifierInfo();
John McCalld14a8642009-11-21 08:51:07 +00001061
John McCalle66edc12009-11-24 19:00:30 +00001062 // C++ [temp.dep.expr]p3:
1063 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001064 // -- an identifier that was declared with a dependent type,
1065 // (note: handled after lookup)
1066 // -- a template-id that is dependent,
1067 // (note: handled in BuildTemplateIdExpr)
1068 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001069 // -- a nested-name-specifier that contains a class-name that
1070 // names a dependent type.
1071 // Determine whether this is a member of an unknown specialization;
1072 // we need to handle these differently.
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001073 if ((Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1074 Name.getCXXNameType()->isDependentType()) ||
1075 (SS.isSet() && IsDependentIdExpression(*this, SS))) {
John McCalle66edc12009-11-24 19:00:30 +00001076 return ActOnDependentIdExpression(SS, Name, NameLoc,
John McCallcd4b4772009-12-02 03:53:29 +00001077 isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001078 TemplateArgs);
1079 }
John McCalld14a8642009-11-21 08:51:07 +00001080
John McCalle66edc12009-11-24 19:00:30 +00001081 // Perform the required lookup.
1082 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1083 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001084 // Lookup the template name again to correctly establish the context in
1085 // which it was found. This is really unfortunate as we already did the
1086 // lookup to determine that it was a template name in the first place. If
1087 // this becomes a performance hit, we can work harder to preserve those
1088 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001089 bool MemberOfUnknownSpecialization;
1090 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1091 MemberOfUnknownSpecialization);
John McCalle66edc12009-11-24 19:00:30 +00001092 } else {
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001093 bool IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
1094 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001095
John McCalle66edc12009-11-24 19:00:30 +00001096 // If this reference is in an Objective-C method, then we need to do
1097 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001098 if (IvarLookupFollowUp) {
1099 OwningExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001100 if (E.isInvalid())
1101 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001102
John McCalle66edc12009-11-24 19:00:30 +00001103 Expr *Ex = E.takeAs<Expr>();
1104 if (Ex) return Owned(Ex);
Fariborz Jahanian18722982010-07-17 00:59:30 +00001105 // Synthesize ivars lazily
1106 if (getLangOptions().ObjCNonFragileABI2) {
1107 if (SynthesizeProvisionalIvar(*this, Context, II, NameLoc))
1108 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1109 isAddressOfOperand);
1110 }
Steve Naroffebf4cb42008-06-02 23:03:37 +00001111 }
Chris Lattner59a25942008-03-31 00:36:02 +00001112 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001113
John McCalle66edc12009-11-24 19:00:30 +00001114 if (R.isAmbiguous())
1115 return ExprError();
1116
Douglas Gregor171c45a2009-02-18 21:56:37 +00001117 // Determine whether this name might be a candidate for
1118 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001119 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001120
John McCalle66edc12009-11-24 19:00:30 +00001121 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001122 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001123 // in C90, extension in C99, forbidden in C++).
1124 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1125 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1126 if (D) R.addDecl(D);
1127 }
1128
1129 // If this name wasn't predeclared and if this is not a function
1130 // call, diagnose the problem.
1131 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001132 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001133 return ExprError();
1134
1135 assert(!R.empty() &&
1136 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001137
1138 // If we found an Objective-C instance variable, let
1139 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001140 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001141 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1142 R.clear();
1143 OwningExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1144 assert(E.isInvalid() || E.get());
1145 return move(E);
1146 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001147 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001148 }
Mike Stump11289f42009-09-09 15:08:12 +00001149
John McCalle66edc12009-11-24 19:00:30 +00001150 // This is guaranteed from this point on.
1151 assert(!R.empty() || ADL);
1152
1153 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001154 // Warn about constructs like:
1155 // if (void *X = foo()) { ... } else { X }.
1156 // In the else block, the pointer is always false.
Douglas Gregor3256d042009-06-30 15:47:41 +00001157 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
1158 Scope *CheckS = S;
Douglas Gregor13a2c032009-11-05 17:49:26 +00001159 while (CheckS && CheckS->getControlParent()) {
Chris Lattnerdf742642010-04-12 06:12:50 +00001160 if ((CheckS->getFlags() & Scope::ElseScope) &&
Douglas Gregor3256d042009-06-30 15:47:41 +00001161 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
John McCalle66edc12009-11-24 19:00:30 +00001162 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
Douglas Gregor13a2c032009-11-05 17:49:26 +00001163 << Var->getDeclName()
Chris Lattnerdf742642010-04-12 06:12:50 +00001164 << (Var->getType()->isPointerType() ? 2 :
1165 Var->getType()->isBooleanType() ? 1 : 0));
Douglas Gregor3256d042009-06-30 15:47:41 +00001166 break;
1167 }
Mike Stump11289f42009-09-09 15:08:12 +00001168
Douglas Gregor13a2c032009-11-05 17:49:26 +00001169 // Move to the parent of this scope.
1170 CheckS = CheckS->getParent();
Douglas Gregor3256d042009-06-30 15:47:41 +00001171 }
1172 }
John McCalle66edc12009-11-24 19:00:30 +00001173 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001174 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1175 // C99 DR 316 says that, if a function type comes from a
1176 // function definition (without a prototype), that type is only
1177 // used for checking compatibility. Therefore, when referencing
1178 // the function, we pretend that we don't have the full function
1179 // type.
John McCalle66edc12009-11-24 19:00:30 +00001180 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor3256d042009-06-30 15:47:41 +00001181 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001182
Douglas Gregor3256d042009-06-30 15:47:41 +00001183 QualType T = Func->getType();
1184 QualType NoProtoType = T;
John McCall9dd450b2009-09-21 23:43:11 +00001185 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Eli Friedmanb41ad0f2010-05-17 02:50:18 +00001186 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType(),
1187 Proto->getExtInfo());
John McCalle66edc12009-11-24 19:00:30 +00001188 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor3256d042009-06-30 15:47:41 +00001189 }
1190 }
Mike Stump11289f42009-09-09 15:08:12 +00001191
John McCall2d74de92009-12-01 22:10:20 +00001192 // Check whether this might be a C++ implicit instance member access.
1193 // C++ [expr.prim.general]p6:
1194 // Within the definition of a non-static member function, an
1195 // identifier that names a non-static member is transformed to a
1196 // class member access expression.
1197 // But note that &SomeClass::foo is grammatically distinct, even
1198 // though we don't parse it that way.
John McCall57500772009-12-16 12:17:52 +00001199 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCalle66edc12009-11-24 19:00:30 +00001200 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCall57500772009-12-16 12:17:52 +00001201 if (!isAbstractMemberPointer)
1202 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001203 }
1204
John McCalle66edc12009-11-24 19:00:30 +00001205 if (TemplateArgs)
1206 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001207
John McCalle66edc12009-11-24 19:00:30 +00001208 return BuildDeclarationNameExpr(SS, R, ADL);
1209}
1210
John McCall57500772009-12-16 12:17:52 +00001211/// Builds an expression which might be an implicit member expression.
1212Sema::OwningExprResult
1213Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1214 LookupResult &R,
1215 const TemplateArgumentListInfo *TemplateArgs) {
1216 switch (ClassifyImplicitMemberAccess(*this, R)) {
1217 case IMA_Instance:
1218 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1219
1220 case IMA_AnonymousMember:
1221 assert(R.isSingleResult());
1222 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1223 R.getAsSingle<FieldDecl>());
1224
1225 case IMA_Mixed:
1226 case IMA_Mixed_Unrelated:
1227 case IMA_Unresolved:
1228 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1229
1230 case IMA_Static:
1231 case IMA_Mixed_StaticContext:
1232 case IMA_Unresolved_StaticContext:
1233 if (TemplateArgs)
1234 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1235 return BuildDeclarationNameExpr(SS, R, false);
1236
1237 case IMA_Error_StaticContext:
1238 case IMA_Error_Unrelated:
1239 DiagnoseInstanceReference(*this, SS, R);
1240 return ExprError();
1241 }
1242
1243 llvm_unreachable("unexpected instance member access kind");
1244 return ExprError();
1245}
1246
John McCall10eae182009-11-30 22:42:35 +00001247/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1248/// declaration name, generally during template instantiation.
1249/// There's a large number of things which don't need to be done along
1250/// this path.
John McCalle66edc12009-11-24 19:00:30 +00001251Sema::OwningExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001252Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +00001253 DeclarationName Name,
1254 SourceLocation NameLoc) {
1255 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001256 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
John McCalle66edc12009-11-24 19:00:30 +00001257 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
1258
John McCall0b66eb32010-05-01 00:40:08 +00001259 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001260 return ExprError();
1261
John McCalle66edc12009-11-24 19:00:30 +00001262 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1263 LookupQualifiedName(R, DC);
1264
1265 if (R.isAmbiguous())
1266 return ExprError();
1267
1268 if (R.empty()) {
1269 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
1270 return ExprError();
1271 }
1272
1273 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1274}
1275
1276/// LookupInObjCMethod - The parser has read a name in, and Sema has
1277/// detected that we're currently inside an ObjC method. Perform some
1278/// additional lookup.
1279///
1280/// Ideally, most of this would be done by lookup, but there's
1281/// actually quite a lot of extra work involved.
1282///
1283/// Returns a null sentinel to indicate trivial success.
1284Sema::OwningExprResult
1285Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001286 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001287 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001288 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001289
John McCalle66edc12009-11-24 19:00:30 +00001290 // There are two cases to handle here. 1) scoped lookup could have failed,
1291 // in which case we should look for an ivar. 2) scoped lookup could have
1292 // found a decl, but that decl is outside the current instance method (i.e.
1293 // a global variable). In these two cases, we do a lookup for an ivar with
1294 // this name, if the lookup sucedes, we replace it our current decl.
1295
1296 // If we're in a class method, we don't normally want to look for
1297 // ivars. But if we don't find anything else, and there's an
1298 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001299 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001300
1301 bool LookForIvars;
1302 if (Lookup.empty())
1303 LookForIvars = true;
1304 else if (IsClassMethod)
1305 LookForIvars = false;
1306 else
1307 LookForIvars = (Lookup.isSingleResult() &&
1308 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001309 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001310 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001311 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001312 ObjCInterfaceDecl *ClassDeclared;
1313 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1314 // Diagnose using an ivar in a class method.
1315 if (IsClassMethod)
1316 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1317 << IV->getDeclName());
1318
1319 // If we're referencing an invalid decl, just return this as a silent
1320 // error node. The error diagnostic was already emitted on the decl.
1321 if (IV->isInvalidDecl())
1322 return ExprError();
1323
1324 // Check if referencing a field with __attribute__((deprecated)).
1325 if (DiagnoseUseOfDecl(IV, Loc))
1326 return ExprError();
1327
1328 // Diagnose the use of an ivar outside of the declaring class.
1329 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1330 ClassDeclared != IFace)
1331 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1332
1333 // FIXME: This should use a new expr for a direct reference, don't
1334 // turn this into Self->ivar, just return a BareIVarExpr or something.
1335 IdentifierInfo &II = Context.Idents.get("self");
1336 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001337 SelfName.setIdentifier(&II, SourceLocation());
John McCalle66edc12009-11-24 19:00:30 +00001338 CXXScopeSpec SelfScopeSpec;
1339 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1340 SelfName, false, false);
1341 MarkDeclarationReferenced(Loc, IV);
1342 return Owned(new (Context)
1343 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1344 SelfExpr.takeAs<Expr>(), true, true));
1345 }
Chris Lattner87313662010-04-12 05:10:17 +00001346 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001347 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001348 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001349 ObjCInterfaceDecl *ClassDeclared;
1350 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1351 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1352 IFace == ClassDeclared)
1353 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1354 }
1355 }
1356
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001357 if (Lookup.empty() && II && AllowBuiltinCreation) {
1358 // FIXME. Consolidate this with similar code in LookupName.
1359 if (unsigned BuiltinID = II->getBuiltinID()) {
1360 if (!(getLangOptions().CPlusPlus &&
1361 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1362 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1363 S, Lookup.isForRedeclaration(),
1364 Lookup.getNameLoc());
1365 if (D) Lookup.addDecl(D);
1366 }
1367 }
1368 }
John McCalle66edc12009-11-24 19:00:30 +00001369 // Sentinel value saying that we didn't do anything special.
1370 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001371}
John McCalld14a8642009-11-21 08:51:07 +00001372
John McCall16df1e52010-03-30 21:47:33 +00001373/// \brief Cast a base object to a member's actual type.
1374///
1375/// Logically this happens in three phases:
1376///
1377/// * First we cast from the base type to the naming class.
1378/// The naming class is the class into which we were looking
1379/// when we found the member; it's the qualifier type if a
1380/// qualifier was provided, and otherwise it's the base type.
1381///
1382/// * Next we cast from the naming class to the declaring class.
1383/// If the member we found was brought into a class's scope by
1384/// a using declaration, this is that class; otherwise it's
1385/// the class declaring the member.
1386///
1387/// * Finally we cast from the declaring class to the "true"
1388/// declaring class of the member. This conversion does not
1389/// obey access control.
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001390bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001391Sema::PerformObjectMemberConversion(Expr *&From,
1392 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001393 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001394 NamedDecl *Member) {
1395 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1396 if (!RD)
1397 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001398
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001399 QualType DestRecordType;
1400 QualType DestType;
1401 QualType FromRecordType;
1402 QualType FromType = From->getType();
1403 bool PointerConversions = false;
1404 if (isa<FieldDecl>(Member)) {
1405 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001406
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001407 if (FromType->getAs<PointerType>()) {
1408 DestType = Context.getPointerType(DestRecordType);
1409 FromRecordType = FromType->getPointeeType();
1410 PointerConversions = true;
1411 } else {
1412 DestType = DestRecordType;
1413 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001414 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001415 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1416 if (Method->isStatic())
1417 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001418
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001419 DestType = Method->getThisType(Context);
1420 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001421
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001422 if (FromType->getAs<PointerType>()) {
1423 FromRecordType = FromType->getPointeeType();
1424 PointerConversions = true;
1425 } else {
1426 FromRecordType = FromType;
1427 DestType = DestRecordType;
1428 }
1429 } else {
1430 // No conversion necessary.
1431 return false;
1432 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001433
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001434 if (DestType->isDependentType() || FromType->isDependentType())
1435 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001436
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001437 // If the unqualified types are the same, no conversion is necessary.
1438 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1439 return false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001440
John McCall16df1e52010-03-30 21:47:33 +00001441 SourceRange FromRange = From->getSourceRange();
1442 SourceLocation FromLoc = FromRange.getBegin();
1443
Douglas Gregoraae38d62010-05-22 05:17:18 +00001444 bool isLvalue
1445 = (From->isLvalue(Context) == Expr::LV_Valid) && !PointerConversions;
1446
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001447 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001448 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001449 // class name.
1450 //
1451 // If the member was a qualified name and the qualified referred to a
1452 // specific base subobject type, we'll cast to that intermediate type
1453 // first and then to the object in which the member is declared. That allows
1454 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1455 //
1456 // class Base { public: int x; };
1457 // class Derived1 : public Base { };
1458 // class Derived2 : public Base { };
1459 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1460 //
1461 // void VeryDerived::f() {
1462 // x = 17; // error: ambiguous base subobjects
1463 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1464 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001465 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00001466 QualType QType = QualType(Qualifier->getAsType(), 0);
1467 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1468 assert(QType->isRecordType() && "lookup done with non-record type");
1469
1470 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1471
1472 // In C++98, the qualifier type doesn't actually have to be a base
1473 // type of the object type, in which case we just ignore it.
1474 // Otherwise build the appropriate casts.
1475 if (IsDerivedFrom(FromRecordType, QRecordType)) {
Anders Carlssonb78feca2010-04-24 19:22:20 +00001476 CXXBaseSpecifierArray BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001477 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001478 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00001479 return true;
1480
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001481 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00001482 QType = Context.getPointerType(QType);
John McCalld9c7c6562010-03-30 23:58:03 +00001483 ImpCastExprToType(From, QType, CastExpr::CK_UncheckedDerivedToBase,
Douglas Gregoraae38d62010-05-22 05:17:18 +00001484 isLvalue, BasePath);
John McCall16df1e52010-03-30 21:47:33 +00001485
1486 FromType = QType;
1487 FromRecordType = QRecordType;
1488
1489 // If the qualifier type was the same as the destination type,
1490 // we're done.
1491 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1492 return false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001493 }
1494 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001495
John McCall16df1e52010-03-30 21:47:33 +00001496 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001497
John McCall16df1e52010-03-30 21:47:33 +00001498 // If we actually found the member through a using declaration, cast
1499 // down to the using declaration's type.
1500 //
1501 // Pointer equality is fine here because only one declaration of a
1502 // class ever has member declarations.
1503 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
1504 assert(isa<UsingShadowDecl>(FoundDecl));
1505 QualType URecordType = Context.getTypeDeclType(
1506 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
1507
1508 // We only need to do this if the naming-class to declaring-class
1509 // conversion is non-trivial.
1510 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
1511 assert(IsDerivedFrom(FromRecordType, URecordType));
Anders Carlssonb78feca2010-04-24 19:22:20 +00001512 CXXBaseSpecifierArray BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001513 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001514 FromLoc, FromRange, &BasePath))
John McCall16df1e52010-03-30 21:47:33 +00001515 return true;
Alexis Huntc46382e2010-04-28 23:02:27 +00001516
John McCall16df1e52010-03-30 21:47:33 +00001517 QualType UType = URecordType;
1518 if (PointerConversions)
1519 UType = Context.getPointerType(UType);
John McCalld9c7c6562010-03-30 23:58:03 +00001520 ImpCastExprToType(From, UType, CastExpr::CK_UncheckedDerivedToBase,
Douglas Gregoraae38d62010-05-22 05:17:18 +00001521 isLvalue, BasePath);
John McCall16df1e52010-03-30 21:47:33 +00001522 FromType = UType;
1523 FromRecordType = URecordType;
1524 }
1525
1526 // We don't do access control for the conversion from the
1527 // declaring class to the true declaring class.
1528 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001529 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001530
Anders Carlssonb78feca2010-04-24 19:22:20 +00001531 CXXBaseSpecifierArray BasePath;
1532 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
1533 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00001534 IgnoreAccess))
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001535 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001536
John McCalld9c7c6562010-03-30 23:58:03 +00001537 ImpCastExprToType(From, DestType, CastExpr::CK_UncheckedDerivedToBase,
Douglas Gregoraae38d62010-05-22 05:17:18 +00001538 isLvalue, BasePath);
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001539 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001540}
Douglas Gregor3256d042009-06-30 15:47:41 +00001541
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001542/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00001543static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00001544 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalla8ae2222010-04-06 21:38:20 +00001545 DeclAccessPair FoundDecl,
1546 SourceLocation Loc, QualType Ty,
John McCalle66edc12009-11-24 19:00:30 +00001547 const TemplateArgumentListInfo *TemplateArgs = 0) {
1548 NestedNameSpecifier *Qualifier = 0;
1549 SourceRange QualifierRange;
John McCall10eae182009-11-30 22:42:35 +00001550 if (SS.isSet()) {
1551 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1552 QualifierRange = SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001553 }
Mike Stump11289f42009-09-09 15:08:12 +00001554
John McCalle66edc12009-11-24 19:00:30 +00001555 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
John McCall16df1e52010-03-30 21:47:33 +00001556 Member, FoundDecl, Loc, TemplateArgs, Ty);
Douglas Gregorc1905232009-08-26 22:36:53 +00001557}
1558
John McCall2d74de92009-12-01 22:10:20 +00001559/// Builds an implicit member access expression. The current context
1560/// is known to be an instance method, and the given unqualified lookup
1561/// set is known to contain only instance members, at least one of which
1562/// is from an appropriate type.
John McCallb53bbd42009-11-22 01:44:31 +00001563Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00001564Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1565 LookupResult &R,
1566 const TemplateArgumentListInfo *TemplateArgs,
1567 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00001568 assert(!R.empty() && !R.isAmbiguous());
1569
John McCalld14a8642009-11-21 08:51:07 +00001570 SourceLocation Loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00001571
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001572 // We may have found a field within an anonymous union or struct
1573 // (C++ [class.union]).
Douglas Gregor6493d9c2009-10-22 07:08:30 +00001574 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCalle66edc12009-11-24 19:00:30 +00001575 // FIXME: template-ids inside anonymous structs?
John McCall10eae182009-11-30 22:42:35 +00001576 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001577 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCallb53bbd42009-11-22 01:44:31 +00001578 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001579
John McCall2d74de92009-12-01 22:10:20 +00001580 // If this is known to be an instance access, go ahead and build a
1581 // 'this' expression now.
John McCall87fe5d52010-05-20 01:18:31 +00001582 DeclContext *DC = getFunctionLevelDeclContext();
1583 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCall2d74de92009-12-01 22:10:20 +00001584 Expr *This = 0; // null signifies implicit access
1585 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00001586 SourceLocation Loc = R.getNameLoc();
1587 if (SS.getRange().isValid())
1588 Loc = SS.getRange().getBegin();
1589 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00001590 }
1591
John McCall2d74de92009-12-01 22:10:20 +00001592 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1593 /*OpLoc*/ SourceLocation(),
1594 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00001595 SS,
1596 /*FirstQualifierInScope*/ 0,
1597 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00001598}
1599
John McCalle66edc12009-11-24 19:00:30 +00001600bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001601 const LookupResult &R,
1602 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00001603 // Only when used directly as the postfix-expression of a call.
1604 if (!HasTrailingLParen)
1605 return false;
1606
1607 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00001608 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00001609 return false;
1610
1611 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00001612 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00001613 return false;
1614
1615 // Turn off ADL when we find certain kinds of declarations during
1616 // normal lookup:
1617 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1618 NamedDecl *D = *I;
1619
1620 // C++0x [basic.lookup.argdep]p3:
1621 // -- a declaration of a class member
1622 // Since using decls preserve this property, we check this on the
1623 // original decl.
John McCall57500772009-12-16 12:17:52 +00001624 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00001625 return false;
1626
1627 // C++0x [basic.lookup.argdep]p3:
1628 // -- a block-scope function declaration that is not a
1629 // using-declaration
1630 // NOTE: we also trigger this for function templates (in fact, we
1631 // don't check the decl type at all, since all other decl types
1632 // turn off ADL anyway).
1633 if (isa<UsingShadowDecl>(D))
1634 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1635 else if (D->getDeclContext()->isFunctionOrMethod())
1636 return false;
1637
1638 // C++0x [basic.lookup.argdep]p3:
1639 // -- a declaration that is neither a function or a function
1640 // template
1641 // And also for builtin functions.
1642 if (isa<FunctionDecl>(D)) {
1643 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1644
1645 // But also builtin functions.
1646 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1647 return false;
1648 } else if (!isa<FunctionTemplateDecl>(D))
1649 return false;
1650 }
1651
1652 return true;
1653}
1654
1655
John McCalld14a8642009-11-21 08:51:07 +00001656/// Diagnoses obvious problems with the use of the given declaration
1657/// as an expression. This is only actually called for lookups that
1658/// were not overloaded, and it doesn't promise that the declaration
1659/// will in fact be used.
1660static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1661 if (isa<TypedefDecl>(D)) {
1662 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1663 return true;
1664 }
1665
1666 if (isa<ObjCInterfaceDecl>(D)) {
1667 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1668 return true;
1669 }
1670
1671 if (isa<NamespaceDecl>(D)) {
1672 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1673 return true;
1674 }
1675
1676 return false;
1677}
1678
1679Sema::OwningExprResult
John McCalle66edc12009-11-24 19:00:30 +00001680Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001681 LookupResult &R,
1682 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00001683 // If this is a single, fully-resolved result and we don't need ADL,
1684 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00001685 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
John McCallb53bbd42009-11-22 01:44:31 +00001686 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00001687
1688 // We only need to check the declaration if there's exactly one
1689 // result, because in the overloaded case the results can only be
1690 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00001691 if (R.isSingleResult() &&
1692 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00001693 return ExprError();
1694
John McCall58cc69d2010-01-27 01:50:18 +00001695 // Otherwise, just build an unresolved lookup expression. Suppress
1696 // any lookup-related diagnostics; we'll hash these out later, when
1697 // we've picked a target.
1698 R.suppressDiagnostics();
1699
John McCalle66edc12009-11-24 19:00:30 +00001700 bool Dependent
1701 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCalld14a8642009-11-21 08:51:07 +00001702 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001703 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001704 (NestedNameSpecifier*) SS.getScopeRep(),
1705 SS.getRange(),
John McCallb53bbd42009-11-22 01:44:31 +00001706 R.getLookupName(), R.getNameLoc(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00001707 NeedsADL, R.isOverloadedResult(),
1708 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00001709
1710 return Owned(ULE);
1711}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001712
John McCalld14a8642009-11-21 08:51:07 +00001713
1714/// \brief Complete semantic analysis for a reference to the given declaration.
1715Sema::OwningExprResult
John McCalle66edc12009-11-24 19:00:30 +00001716Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCalld14a8642009-11-21 08:51:07 +00001717 SourceLocation Loc, NamedDecl *D) {
1718 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00001719 assert(!isa<FunctionTemplateDecl>(D) &&
1720 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00001721
1722 if (CheckDeclInExpr(*this, Loc, D))
1723 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00001724
Douglas Gregore7488b92009-12-01 16:58:18 +00001725 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1726 // Specifically diagnose references to class templates that are missing
1727 // a template argument list.
1728 Diag(Loc, diag::err_template_decl_ref)
1729 << Template << SS.getRange();
1730 Diag(Template->getLocation(), diag::note_template_decl_here);
1731 return ExprError();
1732 }
1733
1734 // Make sure that we're referring to a value.
1735 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1736 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001737 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00001738 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00001739 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00001740 return ExprError();
1741 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001742
Douglas Gregor171c45a2009-02-18 21:56:37 +00001743 // Check whether this declaration can be used. Note that we suppress
1744 // this check when we're going to perform argument-dependent lookup
1745 // on this function name, because this might not be the function
1746 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00001747 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00001748 return ExprError();
1749
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001750 // Only create DeclRefExpr's for valid Decl's.
1751 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001752 return ExprError();
1753
Chris Lattner2a9d9892008-10-20 05:16:36 +00001754 // If the identifier reference is inside a block, and it refers to a value
1755 // that is outside the block, create a BlockDeclRefExpr instead of a
1756 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1757 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001758 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00001759 // We do not do this for things like enum constants, global variables, etc,
1760 // as they do not get snapshotted.
1761 //
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001762 if (getCurBlock() &&
Douglas Gregor9a28e842010-03-01 23:15:13 +00001763 ShouldSnapshotBlockValueReference(*this, getCurBlock(), VD)) {
Mike Stump7dafa0d2010-01-05 02:56:35 +00001764 if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
1765 Diag(Loc, diag::err_ref_vm_type);
1766 Diag(D->getLocation(), diag::note_declared_at);
1767 return ExprError();
1768 }
1769
Fariborz Jahanianfa24e102010-03-16 23:39:51 +00001770 if (VD->getType()->isArrayType()) {
Mike Stump8971a862010-01-05 03:10:36 +00001771 Diag(Loc, diag::err_ref_array_type);
1772 Diag(D->getLocation(), diag::note_declared_at);
1773 return ExprError();
1774 }
1775
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001776 MarkDeclarationReferenced(Loc, VD);
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001777 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001778 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001779 if (VD->getAttr<BlocksAttr>())
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001780 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001781 // This is to record that a 'const' was actually synthesize and added.
1782 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001783 // Variable will be bound by-copy, make it const within the closure.
Mike Stump11289f42009-09-09 15:08:12 +00001784
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001785 ExprTy.addConst();
Fariborz Jahanian70c0b082010-07-12 17:26:57 +00001786 QualType T = VD->getType();
Fariborz Jahanianea882cd2010-06-04 21:35:44 +00001787 BlockDeclRefExpr *BDRE = new (Context) BlockDeclRefExpr(VD,
1788 ExprTy, Loc, false,
Fariborz Jahanianc289bce2010-07-12 18:12:03 +00001789 constAdded);
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00001790 if (getLangOptions().CPlusPlus) {
1791 if (!T->isDependentType() && !T->isReferenceType()) {
1792 Expr *E = new (Context)
1793 DeclRefExpr(const_cast<ValueDecl*>(BDRE->getDecl()), T,
1794 SourceLocation());
Fariborz Jahanianea882cd2010-06-04 21:35:44 +00001795
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00001796 OwningExprResult Res = PerformCopyInitialization(
1797 InitializedEntity::InitializeBlock(VD->getLocation(),
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00001798 T, false),
Fariborz Jahanian4239aa12010-07-09 22:21:32 +00001799 SourceLocation(),
1800 Owned(E));
1801 if (!Res.isInvalid()) {
1802 Res = MaybeCreateCXXExprWithTemporaries(move(Res));
1803 Expr *Init = Res.takeAs<Expr>();
1804 BDRE->setCopyConstructorExpr(Init);
1805 }
Fariborz Jahanianea882cd2010-06-04 21:35:44 +00001806 }
1807 }
1808 return Owned(BDRE);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001809 }
1810 // If this reference is not in a block or if the referenced variable is
1811 // within the block, create a normal DeclRefExpr.
Douglas Gregor4619e432008-12-05 23:32:09 +00001812
John McCalle66edc12009-11-24 19:00:30 +00001813 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
Chris Lattner17ed4872006-11-20 04:58:19 +00001814}
Chris Lattnere168f762006-11-10 05:29:30 +00001815
Sebastian Redlffbcf962009-01-18 18:53:16 +00001816Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1817 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00001818 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001819
Chris Lattnere168f762006-11-10 05:29:30 +00001820 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00001821 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00001822 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1823 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1824 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00001825 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00001826
Chris Lattnera81a0272008-01-12 08:14:25 +00001827 // Pre-defined identifiers are of type char[x], where x is the length of the
1828 // string.
Mike Stump11289f42009-09-09 15:08:12 +00001829
Anders Carlsson2fb08242009-09-08 18:24:21 +00001830 Decl *currentDecl = getCurFunctionOrMethodDecl();
1831 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001832 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00001833 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001834 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001835
Anders Carlsson0b209a82009-09-11 01:22:35 +00001836 QualType ResTy;
1837 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1838 ResTy = Context.DependentTy;
1839 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00001840 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001841
Anders Carlsson0b209a82009-09-11 01:22:35 +00001842 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00001843 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00001844 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1845 }
Steve Narofff6009ed2009-01-21 00:14:39 +00001846 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00001847}
1848
Sebastian Redlffbcf962009-01-18 18:53:16 +00001849Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001850 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00001851 bool Invalid = false;
1852 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
1853 if (Invalid)
1854 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001855
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001856 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
1857 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00001858 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001859 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00001860
Chris Lattnerc3847ba2009-12-30 21:19:39 +00001861 QualType Ty;
1862 if (!getLangOptions().CPlusPlus)
1863 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
1864 else if (Literal.isWide())
1865 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00001866 else if (Literal.isMultiChar())
1867 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00001868 else
1869 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00001870
Sebastian Redl20614a72009-01-20 22:23:13 +00001871 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1872 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00001873 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00001874}
1875
Sebastian Redlffbcf962009-01-18 18:53:16 +00001876Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1877 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00001878 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1879 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00001880 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00001881 unsigned IntSize = Context.Target.getIntWidth();
Steve Narofff6009ed2009-01-21 00:14:39 +00001882 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00001883 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00001884 }
Ted Kremeneke9814182009-01-13 23:19:12 +00001885
Chris Lattner23b7eb62007-06-15 23:05:46 +00001886 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00001887 // Add padding so that NumericLiteralParser can overread by one character.
1888 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00001889 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00001890
Chris Lattner67ca9252007-05-21 01:08:44 +00001891 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00001892 bool Invalid = false;
1893 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
1894 if (Invalid)
1895 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001896
Mike Stump11289f42009-09-09 15:08:12 +00001897 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00001898 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00001899 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001900 return ExprError();
1901
Chris Lattner1c20a172007-08-26 03:42:43 +00001902 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001903
Chris Lattner1c20a172007-08-26 03:42:43 +00001904 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001905 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001906 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001907 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001908 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001909 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001910 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00001911 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001912
1913 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1914
John McCall53b93a02009-12-24 09:08:04 +00001915 using llvm::APFloat;
1916 APFloat Val(Format);
1917
1918 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00001919
1920 // Overflow is always an error, but underflow is only an error if
1921 // we underflowed to zero (APFloat reports denormals as underflow).
1922 if ((result & APFloat::opOverflow) ||
1923 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00001924 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001925 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00001926 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00001927 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00001928 APFloat::getLargest(Format).toString(buffer);
1929 } else {
John McCall62abc942010-02-26 23:35:57 +00001930 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00001931 APFloat::getSmallest(Format).toString(buffer);
1932 }
1933
1934 Diag(Tok.getLocation(), diagnostic)
1935 << Ty
1936 << llvm::StringRef(buffer.data(), buffer.size());
1937 }
1938
1939 bool isExact = (result == APFloat::opOK);
Chris Lattnere4edb8e2009-06-29 17:34:55 +00001940 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00001941
Chris Lattner1c20a172007-08-26 03:42:43 +00001942 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00001943 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00001944 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001945 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00001946
Neil Boothac582c52007-08-29 22:00:19 +00001947 // long long is a C99 feature.
1948 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00001949 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00001950 Diag(Tok.getLocation(), diag::ext_longlong);
1951
Chris Lattner67ca9252007-05-21 01:08:44 +00001952 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00001953 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001954
Chris Lattner67ca9252007-05-21 01:08:44 +00001955 if (Literal.GetIntegerValue(ResultVal)) {
1956 // If this value didn't fit into uintmax_t, warn and force to ull.
1957 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001958 Ty = Context.UnsignedLongLongTy;
1959 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00001960 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00001961 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00001962 // If this value fits into a ULL, try to figure out what else it fits into
1963 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001964
Chris Lattner67ca9252007-05-21 01:08:44 +00001965 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1966 // be an unsigned int.
1967 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1968
1969 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00001970 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00001971 if (!Literal.isLong && !Literal.isLongLong) {
1972 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00001973 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001974
Chris Lattner67ca9252007-05-21 01:08:44 +00001975 // Does it fit in a unsigned int?
1976 if (ResultVal.isIntN(IntSize)) {
1977 // Does it fit in a signed int?
1978 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001979 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001980 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001981 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001982 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001983 }
Chris Lattner67ca9252007-05-21 01:08:44 +00001984 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001985
Chris Lattner67ca9252007-05-21 01:08:44 +00001986 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001987 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001988 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001989
Chris Lattner67ca9252007-05-21 01:08:44 +00001990 // Does it fit in a unsigned long?
1991 if (ResultVal.isIntN(LongSize)) {
1992 // Does it fit in a signed long?
1993 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001994 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001995 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001996 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001997 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001998 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001999 }
2000
Chris Lattner67ca9252007-05-21 01:08:44 +00002001 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002002 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002003 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002004
Chris Lattner67ca9252007-05-21 01:08:44 +00002005 // Does it fit in a unsigned long long?
2006 if (ResultVal.isIntN(LongLongSize)) {
2007 // Does it fit in a signed long long?
2008 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002009 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002010 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002011 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002012 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002013 }
2014 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002015
Chris Lattner67ca9252007-05-21 01:08:44 +00002016 // If we still couldn't decide a type, we probably have something that
2017 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002018 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002019 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002020 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002021 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002022 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002023
Chris Lattner55258cf2008-05-09 05:59:00 +00002024 if (ResultVal.getBitWidth() != Width)
2025 ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002026 }
Sebastian Redl20614a72009-01-20 22:23:13 +00002027 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002028 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002029
Chris Lattner1c20a172007-08-26 03:42:43 +00002030 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2031 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002032 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002033 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002034
2035 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002036}
2037
Sebastian Redlffbcf962009-01-18 18:53:16 +00002038Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
2039 SourceLocation R, ExprArg Val) {
Anders Carlssonb781bcd2009-05-01 19:49:17 +00002040 Expr *E = Val.takeAs<Expr>();
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002041 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002042 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002043}
2044
Steve Naroff71b59a92007-06-04 22:22:31 +00002045/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00002046/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002047bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl6f282892008-11-11 17:56:53 +00002048 SourceLocation OpLoc,
2049 const SourceRange &ExprRange,
2050 bool isSizeof) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002051 if (exprType->isDependentType())
2052 return false;
2053
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002054 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2055 // the result is the size of the referenced type."
2056 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2057 // result shall be the alignment of the referenced type."
2058 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2059 exprType = Ref->getPointeeType();
2060
Steve Naroff043d45d2007-05-15 02:32:35 +00002061 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00002062 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002063 // alignof(function) is allowed as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00002064 if (isSizeof)
2065 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2066 return false;
2067 }
Mike Stump11289f42009-09-09 15:08:12 +00002068
Chris Lattner62975a72009-04-24 00:30:45 +00002069 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00002070 if (exprType->isVoidType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002071 Diag(OpLoc, diag::ext_sizeof_void_type)
2072 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00002073 return false;
2074 }
Mike Stump11289f42009-09-09 15:08:12 +00002075
Chris Lattner62975a72009-04-24 00:30:45 +00002076 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002077 PDiag(diag::err_sizeof_alignof_incomplete_type)
2078 << int(!isSizeof) << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002079 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002080
Chris Lattner62975a72009-04-24 00:30:45 +00002081 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCall8b07ec22010-05-15 11:32:37 +00002082 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00002083 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002084 << exprType << isSizeof << ExprRange;
2085 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00002086 }
Mike Stump11289f42009-09-09 15:08:12 +00002087
Douglas Gregor27887822010-05-23 19:43:23 +00002088 if (Context.hasSameUnqualifiedType(exprType, Context.OverloadTy)) {
2089 Diag(OpLoc, diag::err_sizeof_alignof_overloaded_function_type)
2090 << !isSizeof << ExprRange;
2091 return true;
2092 }
2093
Chris Lattner62975a72009-04-24 00:30:45 +00002094 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002095}
2096
Chris Lattner8dff0172009-01-24 20:17:12 +00002097bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
2098 const SourceRange &ExprRange) {
2099 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002100
Mike Stump11289f42009-09-09 15:08:12 +00002101 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002102 if (isa<DeclRefExpr>(E))
2103 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002104
2105 // Cannot know anything else if the expression is dependent.
2106 if (E->isTypeDependent())
2107 return false;
2108
Douglas Gregor71235ec2009-05-02 02:18:30 +00002109 if (E->getBitField()) {
2110 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
2111 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002112 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002113
2114 // Alignment of a field access is always okay, so long as it isn't a
2115 // bit-field.
2116 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002117 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002118 return false;
2119
Chris Lattner8dff0172009-01-24 20:17:12 +00002120 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
2121}
2122
Douglas Gregor0950e412009-03-13 21:01:28 +00002123/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump11289f42009-09-09 15:08:12 +00002124Action::OwningExprResult
John McCallbcd03502009-12-07 02:54:59 +00002125Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall4c98fd82009-11-04 07:28:41 +00002126 SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00002127 bool isSizeOf, SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002128 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002129 return ExprError();
2130
John McCallbcd03502009-12-07 02:54:59 +00002131 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002132
Douglas Gregor0950e412009-03-13 21:01:28 +00002133 if (!T->isDependentType() &&
2134 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2135 return ExprError();
2136
2137 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCallbcd03502009-12-07 02:54:59 +00002138 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregor0950e412009-03-13 21:01:28 +00002139 Context.getSizeType(), OpLoc,
2140 R.getEnd()));
2141}
2142
2143/// \brief Build a sizeof or alignof expression given an expression
2144/// operand.
Mike Stump11289f42009-09-09 15:08:12 +00002145Action::OwningExprResult
2146Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00002147 bool isSizeOf, SourceRange R) {
2148 // Verify that the operand is valid.
2149 bool isInvalid = false;
2150 if (E->isTypeDependent()) {
2151 // Delay type-checking for type-dependent expressions.
2152 } else if (!isSizeOf) {
2153 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002154 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00002155 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2156 isInvalid = true;
2157 } else {
2158 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2159 }
2160
2161 if (isInvalid)
2162 return ExprError();
2163
2164 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2165 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2166 Context.getSizeType(), OpLoc,
2167 R.getEnd()));
2168}
2169
Sebastian Redl6f282892008-11-11 17:56:53 +00002170/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2171/// the same for @c alignof and @c __alignof
2172/// Note that the ArgRange is invalid if isType is false.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002173Action::OwningExprResult
Sebastian Redl6f282892008-11-11 17:56:53 +00002174Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2175 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002176 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002177 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002178
Sebastian Redl6f282892008-11-11 17:56:53 +00002179 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002180 TypeSourceInfo *TInfo;
2181 (void) GetTypeFromParser(TyOrEx, &TInfo);
2182 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002183 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002184
Douglas Gregor0950e412009-03-13 21:01:28 +00002185 Expr *ArgEx = (Expr *)TyOrEx;
2186 Action::OwningExprResult Result
2187 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2188
2189 if (Result.isInvalid())
2190 DeleteExpr(ArgEx);
2191
2192 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002193}
2194
Chris Lattner709322b2009-02-17 08:12:06 +00002195QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002196 if (V->isTypeDependent())
2197 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002198
Chris Lattnere267f5d2007-08-26 05:39:26 +00002199 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00002200 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002201 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002202
Chris Lattnere267f5d2007-08-26 05:39:26 +00002203 // Otherwise they pass through real integer and floating point types here.
2204 if (V->getType()->isArithmeticType())
2205 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002206
Chris Lattnere267f5d2007-08-26 05:39:26 +00002207 // Reject anything else.
Chris Lattner709322b2009-02-17 08:12:06 +00002208 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
2209 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002210 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002211}
2212
2213
Chris Lattnere168f762006-11-10 05:29:30 +00002214
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002215Action::OwningExprResult
2216Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
2217 tok::TokenKind Kind, ExprArg Input) {
Chris Lattnere168f762006-11-10 05:29:30 +00002218 UnaryOperator::Opcode Opc;
2219 switch (Kind) {
2220 default: assert(0 && "Unknown unary op!");
2221 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
2222 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
2223 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002224
Eli Friedmancfdd40c2009-11-18 03:38:04 +00002225 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Chris Lattnere168f762006-11-10 05:29:30 +00002226}
2227
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002228Action::OwningExprResult
2229Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
2230 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002231 // Since this might be a postfix expression, get rid of ParenListExprs.
2232 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
2233
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002234 Expr *LHSExp = static_cast<Expr*>(Base.get()),
2235 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump11289f42009-09-09 15:08:12 +00002236
Douglas Gregor40412ac2008-11-19 17:17:41 +00002237 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002238 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
2239 Base.release();
2240 Idx.release();
2241 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
2242 Context.DependentTy, RLoc));
2243 }
2244
Mike Stump11289f42009-09-09 15:08:12 +00002245 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002246 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002247 LHSExp->getType()->isEnumeralType() ||
2248 RHSExp->getType()->isRecordType() ||
2249 RHSExp->getType()->isEnumeralType())) {
Sebastian Redladba46e2009-10-29 20:17:01 +00002250 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor40412ac2008-11-19 17:17:41 +00002251 }
2252
Sebastian Redladba46e2009-10-29 20:17:01 +00002253 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
2254}
2255
2256
2257Action::OwningExprResult
2258Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
2259 ExprArg Idx, SourceLocation RLoc) {
2260 Expr *LHSExp = static_cast<Expr*>(Base.get());
2261 Expr *RHSExp = static_cast<Expr*>(Idx.get());
2262
Chris Lattner36d572b2007-07-16 00:14:47 +00002263 // Perform default conversions.
Douglas Gregorb92a1562010-02-03 00:27:59 +00002264 if (!LHSExp->getType()->getAs<VectorType>())
2265 DefaultFunctionArrayLvalueConversion(LHSExp);
2266 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002267
Chris Lattner36d572b2007-07-16 00:14:47 +00002268 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Steve Narofff1e53692007-03-23 22:27:02 +00002269
Steve Naroffc1aadb12007-03-28 21:49:40 +00002270 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00002271 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00002272 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00002273 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00002274 Expr *BaseExpr, *IndexExpr;
2275 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002276 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2277 BaseExpr = LHSExp;
2278 IndexExpr = RHSExp;
2279 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002280 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00002281 BaseExpr = LHSExp;
2282 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002283 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002284 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00002285 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00002286 BaseExpr = RHSExp;
2287 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00002288 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002289 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002290 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002291 BaseExpr = LHSExp;
2292 IndexExpr = RHSExp;
2293 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002294 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00002295 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002296 // Handle the uncommon case of "123[Ptr]".
2297 BaseExpr = RHSExp;
2298 IndexExpr = LHSExp;
2299 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00002300 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00002301 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00002302 IndexExpr = RHSExp;
Nate Begemanc1bf0612009-01-18 00:45:31 +00002303
Chris Lattner36d572b2007-07-16 00:14:47 +00002304 // FIXME: need to deal with const...
2305 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002306 } else if (LHSTy->isArrayType()) {
2307 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00002308 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00002309 // wasn't promoted because of the C90 rule that doesn't
2310 // allow promoting non-lvalue arrays. Warn, then
2311 // force the promotion here.
2312 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2313 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002314 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
2315 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002316 LHSTy = LHSExp->getType();
2317
2318 BaseExpr = LHSExp;
2319 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002320 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00002321 } else if (RHSTy->isArrayType()) {
2322 // Same as previous, except for 123[f().a] case
2323 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2324 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002325 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
2326 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00002327 RHSTy = RHSExp->getType();
2328
2329 BaseExpr = RHSExp;
2330 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002331 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00002332 } else {
Chris Lattner003af242009-04-25 22:50:55 +00002333 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2334 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002335 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00002336 // C99 6.5.2.1p1
Nate Begeman5ec4b312009-08-10 23:49:36 +00002337 if (!(IndexExpr->getType()->isIntegerType() &&
2338 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00002339 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2340 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00002341
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002342 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00002343 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2344 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00002345 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2346
Douglas Gregorac1fb652009-03-24 19:52:54 +00002347 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00002348 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2349 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00002350 // incomplete types are not object types.
2351 if (ResultType->isFunctionType()) {
2352 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2353 << ResultType << BaseExpr->getSourceRange();
2354 return ExprError();
2355 }
Mike Stump11289f42009-09-09 15:08:12 +00002356
Douglas Gregorac1fb652009-03-24 19:52:54 +00002357 if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00002358 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00002359 PDiag(diag::err_subscript_incomplete_type)
2360 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00002361 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002362
Chris Lattner62975a72009-04-24 00:30:45 +00002363 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00002364 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00002365 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2366 << ResultType << BaseExpr->getSourceRange();
2367 return ExprError();
2368 }
Mike Stump11289f42009-09-09 15:08:12 +00002369
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002370 Base.release();
2371 Idx.release();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002372 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Narofff6009ed2009-01-21 00:14:39 +00002373 ResultType, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00002374}
2375
Steve Narofff8fd09e2007-07-27 22:15:19 +00002376QualType Sema::
Nate Begemance4d7fc2008-04-18 23:10:10 +00002377CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002378 const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00002379 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00002380 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2381 // see FIXME there.
2382 //
2383 // FIXME: This logic can be greatly simplified by splitting it along
2384 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00002385 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00002386
Steve Narofff8fd09e2007-07-27 22:15:19 +00002387 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002388 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002389
Mike Stump4e1f26a2009-02-19 03:04:26 +00002390 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00002391 // special names that indicate a subset of exactly half the elements are
2392 // to be selected.
2393 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00002394
Nate Begemanbb70bf62009-01-18 01:47:54 +00002395 // This flag determines whether or not CompName has an 's' char prefix,
2396 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00002397 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00002398
2399 // Check that we've found one of the special components, or that the component
2400 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002401 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00002402 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2403 HalvingSwizzle = true;
Nate Begemanf322eab2008-05-09 06:41:27 +00002404 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00002405 do
2406 compStr++;
2407 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begemanbb70bf62009-01-18 01:47:54 +00002408 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00002409 do
2410 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002411 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner7e152db2007-08-02 22:33:49 +00002412 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00002413
Mike Stump4e1f26a2009-02-19 03:04:26 +00002414 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00002415 // We didn't get to the end of the string. This means the component names
2416 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner3b054132008-11-19 05:08:23 +00002417 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2418 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00002419 return QualType();
2420 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002421
Nate Begemanbb70bf62009-01-18 01:47:54 +00002422 // Ensure no component accessor exceeds the width of the vector type it
2423 // operates on.
2424 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002425 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002426
2427 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00002428 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002429
2430 while (*compStr) {
2431 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2432 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2433 << baseType << SourceRange(CompLoc);
2434 return QualType();
2435 }
2436 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00002437 }
Nate Begemanf322eab2008-05-09 06:41:27 +00002438
Steve Narofff8fd09e2007-07-27 22:15:19 +00002439 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002440 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00002441 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00002442 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00002443 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00002444 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00002445 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002446 if (HexSwizzle)
2447 CompSize--;
2448
Steve Narofff8fd09e2007-07-27 22:15:19 +00002449 if (CompSize == 1)
2450 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002451
Nate Begemance4d7fc2008-04-18 23:10:10 +00002452 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00002453 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00002454 // diagostics look bad. We want extended vector types to appear built-in.
2455 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2456 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2457 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00002458 }
2459 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00002460}
2461
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002462static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00002463 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002464 const Selector &Sel,
2465 ASTContext &Context) {
Mike Stump11289f42009-09-09 15:08:12 +00002466
Anders Carlssonf571c112009-08-26 18:25:21 +00002467 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002468 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002469 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002470 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00002471
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002472 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2473 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00002474 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002475 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002476 return D;
2477 }
2478 return 0;
2479}
2480
Steve Narofffb4330f2009-06-17 22:40:22 +00002481static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlssonf571c112009-08-26 18:25:21 +00002482 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002483 const Selector &Sel,
2484 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002485 // Check protocols on qualified interfaces.
2486 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00002487 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002488 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002489 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002490 GDecl = PD;
2491 break;
2492 }
2493 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002494 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002495 GDecl = OMD;
2496 break;
2497 }
2498 }
2499 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00002500 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002501 E = QIdTy->qual_end(); I != E; ++I) {
2502 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002503 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002504 if (GDecl)
2505 return GDecl;
2506 }
2507 }
2508 return GDecl;
2509}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00002510
John McCall10eae182009-11-30 22:42:35 +00002511Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002512Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2513 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002514 const CXXScopeSpec &SS,
2515 NamedDecl *FirstQualifierInScope,
2516 DeclarationName Name, SourceLocation NameLoc,
2517 const TemplateArgumentListInfo *TemplateArgs) {
2518 Expr *BaseExpr = Base.takeAs<Expr>();
2519
2520 // Even in dependent contexts, try to diagnose base expressions with
2521 // obviously wrong types, e.g.:
2522 //
2523 // T* t;
2524 // t.f;
2525 //
2526 // In Obj-C++, however, the above expression is valid, since it could be
2527 // accessing the 'f' property if T is an Obj-C interface. The extra check
2528 // allows this, while still reporting an error if T is a struct pointer.
2529 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00002530 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00002531 if (PT && (!getLangOptions().ObjC1 ||
2532 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00002533 assert(BaseExpr && "cannot happen with implicit member accesses");
John McCall10eae182009-11-30 22:42:35 +00002534 Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00002535 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00002536 return ExprError();
2537 }
2538 }
2539
Alexis Huntc46382e2010-04-28 23:02:27 +00002540 assert(BaseType->isDependentType() || Name.isDependentName() ||
Douglas Gregor41f90302010-04-12 20:54:26 +00002541 isDependentScopeSpecifier(SS));
John McCall10eae182009-11-30 22:42:35 +00002542
2543 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2544 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00002545 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00002546 IsArrow, OpLoc,
2547 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2548 SS.getRange(),
2549 FirstQualifierInScope,
2550 Name, NameLoc,
2551 TemplateArgs));
2552}
2553
2554/// We know that the given qualified member reference points only to
2555/// declarations which do not belong to the static type of the base
2556/// expression. Diagnose the problem.
2557static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2558 Expr *BaseExpr,
2559 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00002560 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002561 const LookupResult &R) {
John McCallcd4b4772009-12-02 03:53:29 +00002562 // If this is an implicit member access, use a different set of
2563 // diagnostics.
2564 if (!BaseExpr)
2565 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall10eae182009-11-30 22:42:35 +00002566
John McCall1e67dd62010-04-27 01:43:38 +00002567 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_of_unrelated)
2568 << SS.getRange() << R.getRepresentativeDecl() << BaseType;
John McCall10eae182009-11-30 22:42:35 +00002569}
2570
2571// Check whether the declarations we found through a nested-name
2572// specifier in a member expression are actually members of the base
2573// type. The restriction here is:
2574//
2575// C++ [expr.ref]p2:
2576// ... In these cases, the id-expression shall name a
2577// member of the class or of one of its base classes.
2578//
2579// So it's perfectly legitimate for the nested-name specifier to name
2580// an unrelated class, and for us to find an overload set including
2581// decls from classes which are not superclasses, as long as the decl
2582// we actually pick through overload resolution is from a superclass.
2583bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2584 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00002585 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002586 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00002587 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2588 if (!BaseRT) {
2589 // We can't check this yet because the base type is still
2590 // dependent.
2591 assert(BaseType->isDependentType());
2592 return false;
2593 }
2594 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00002595
2596 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00002597 // If this is an implicit member reference and we find a
2598 // non-instance member, it's not an error.
John McCalla8ae2222010-04-06 21:38:20 +00002599 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCall2d74de92009-12-01 22:10:20 +00002600 return false;
John McCall10eae182009-11-30 22:42:35 +00002601
John McCall2d74de92009-12-01 22:10:20 +00002602 // Note that we use the DC of the decl, not the underlying decl.
2603 CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
2604 while (RecordD->isAnonymousStructOrUnion())
2605 RecordD = cast<CXXRecordDecl>(RecordD->getParent());
2606
2607 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
2608 MemberRecord.insert(RecordD->getCanonicalDecl());
2609
2610 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2611 return false;
2612 }
2613
John McCallcd4b4772009-12-02 03:53:29 +00002614 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCall2d74de92009-12-01 22:10:20 +00002615 return true;
2616}
2617
2618static bool
2619LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2620 SourceRange BaseRange, const RecordType *RTy,
John McCalle9cccd82010-06-16 08:42:20 +00002621 SourceLocation OpLoc, CXXScopeSpec &SS,
2622 bool HasTemplateArgs) {
John McCall2d74de92009-12-01 22:10:20 +00002623 RecordDecl *RDecl = RTy->getDecl();
2624 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor89336232010-03-29 23:34:08 +00002625 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCall2d74de92009-12-01 22:10:20 +00002626 << BaseRange))
2627 return true;
2628
John McCalle9cccd82010-06-16 08:42:20 +00002629 if (HasTemplateArgs) {
2630 // LookupTemplateName doesn't expect these both to exist simultaneously.
2631 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
2632
2633 bool MOUS;
2634 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
2635 return false;
2636 }
2637
John McCall2d74de92009-12-01 22:10:20 +00002638 DeclContext *DC = RDecl;
2639 if (SS.isSet()) {
2640 // If the member name was a qualified-id, look into the
2641 // nested-name-specifier.
2642 DC = SemaRef.computeDeclContext(SS, false);
2643
John McCall0b66eb32010-05-01 00:40:08 +00002644 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCallcd4b4772009-12-02 03:53:29 +00002645 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2646 << SS.getRange() << DC;
2647 return true;
2648 }
2649
John McCall2d74de92009-12-01 22:10:20 +00002650 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002651
John McCall2d74de92009-12-01 22:10:20 +00002652 if (!isa<TypeDecl>(DC)) {
2653 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2654 << DC << SS.getRange();
2655 return true;
John McCall10eae182009-11-30 22:42:35 +00002656 }
2657 }
2658
John McCall2d74de92009-12-01 22:10:20 +00002659 // The record definition is complete, now look up the member.
2660 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00002661
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002662 if (!R.empty())
2663 return false;
2664
2665 // We didn't find anything with the given name, so try to correct
2666 // for typos.
2667 DeclarationName Name = R.getLookupName();
Alexis Huntc46382e2010-04-28 23:02:27 +00002668 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002669 !R.empty() &&
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002670 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
2671 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
2672 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00002673 << FixItHint::CreateReplacement(R.getNameLoc(),
2674 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00002675 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
2676 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
2677 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002678 return false;
2679 } else {
2680 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002681 R.setLookupName(Name);
Douglas Gregoraf2bd472009-12-31 07:42:17 +00002682 }
2683
John McCall10eae182009-11-30 22:42:35 +00002684 return false;
2685}
2686
2687Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002688Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00002689 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002690 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002691 NamedDecl *FirstQualifierInScope,
2692 DeclarationName Name, SourceLocation NameLoc,
2693 const TemplateArgumentListInfo *TemplateArgs) {
2694 Expr *Base = BaseArg.takeAs<Expr>();
2695
John McCallcd4b4772009-12-02 03:53:29 +00002696 if (BaseType->isDependentType() ||
2697 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCall2d74de92009-12-01 22:10:20 +00002698 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
John McCall10eae182009-11-30 22:42:35 +00002699 IsArrow, OpLoc,
2700 SS, FirstQualifierInScope,
2701 Name, NameLoc,
2702 TemplateArgs);
2703
2704 LookupResult R(*this, Name, NameLoc, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00002705
John McCall2d74de92009-12-01 22:10:20 +00002706 // Implicit member accesses.
2707 if (!Base) {
2708 QualType RecordTy = BaseType;
2709 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2710 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2711 RecordTy->getAs<RecordType>(),
John McCalle9cccd82010-06-16 08:42:20 +00002712 OpLoc, SS, TemplateArgs != 0))
John McCall2d74de92009-12-01 22:10:20 +00002713 return ExprError();
2714
2715 // Explicit member accesses.
2716 } else {
2717 OwningExprResult Result =
2718 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCalle9cccd82010-06-16 08:42:20 +00002719 SS, /*ObjCImpDecl*/ DeclPtrTy(), TemplateArgs != 0);
John McCall2d74de92009-12-01 22:10:20 +00002720
2721 if (Result.isInvalid()) {
2722 Owned(Base);
2723 return ExprError();
2724 }
2725
2726 if (Result.get())
2727 return move(Result);
Sebastian Redlfa1f70f2010-05-07 09:25:11 +00002728
2729 // LookupMemberExpr can modify Base, and thus change BaseType
2730 BaseType = Base->getType();
John McCall10eae182009-11-30 22:42:35 +00002731 }
2732
Sebastian Redl0b4e3122010-05-07 09:09:23 +00002733 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
John McCall38836f02010-01-15 08:34:02 +00002734 OpLoc, IsArrow, SS, FirstQualifierInScope,
2735 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002736}
2737
2738Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002739Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2740 SourceLocation OpLoc, bool IsArrow,
2741 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00002742 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00002743 LookupResult &R,
Douglas Gregorb139cd52010-05-01 20:49:11 +00002744 const TemplateArgumentListInfo *TemplateArgs,
2745 bool SuppressQualifierCheck) {
John McCall10eae182009-11-30 22:42:35 +00002746 Expr *BaseExpr = Base.takeAs<Expr>();
John McCall2d74de92009-12-01 22:10:20 +00002747 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00002748 if (IsArrow) {
2749 assert(BaseType->isPointerType());
2750 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2751 }
John McCalla8ae2222010-04-06 21:38:20 +00002752 R.setBaseObjectType(BaseType);
John McCall10eae182009-11-30 22:42:35 +00002753
2754 NestedNameSpecifier *Qualifier =
2755 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2756 DeclarationName MemberName = R.getLookupName();
2757 SourceLocation MemberLoc = R.getNameLoc();
2758
2759 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00002760 return ExprError();
2761
John McCall10eae182009-11-30 22:42:35 +00002762 if (R.empty()) {
2763 // Rederive where we looked up.
2764 DeclContext *DC = (SS.isSet()
2765 ? computeDeclContext(SS, false)
2766 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00002767
John McCall10eae182009-11-30 22:42:35 +00002768 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00002769 << MemberName << DC
2770 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00002771 return ExprError();
2772 }
2773
John McCall38836f02010-01-15 08:34:02 +00002774 // Diagnose lookups that find only declarations from a non-base
2775 // type. This is possible for either qualified lookups (which may
2776 // have been qualified with an unrelated type) or implicit member
2777 // expressions (which were found with unqualified lookup and thus
2778 // may have come from an enclosing scope). Note that it's okay for
2779 // lookup to find declarations from a non-base type as long as those
2780 // aren't the ones picked by overload resolution.
2781 if ((SS.isSet() || !BaseExpr ||
2782 (isa<CXXThisExpr>(BaseExpr) &&
2783 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00002784 !SuppressQualifierCheck &&
John McCall38836f02010-01-15 08:34:02 +00002785 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00002786 return ExprError();
2787
2788 // Construct an unresolved result if we in fact got an unresolved
2789 // result.
2790 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall2d74de92009-12-01 22:10:20 +00002791 bool Dependent =
John McCall71739032009-12-19 02:05:44 +00002792 BaseExprType->isDependentType() ||
John McCall2d74de92009-12-01 22:10:20 +00002793 R.isUnresolvableResult() ||
John McCall1acbbb52010-02-02 06:20:04 +00002794 OverloadExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002795
John McCall58cc69d2010-01-27 01:50:18 +00002796 // Suppress any lookup-related diagnostics; we'll do these when we
2797 // pick a member.
2798 R.suppressDiagnostics();
2799
John McCall10eae182009-11-30 22:42:35 +00002800 UnresolvedMemberExpr *MemExpr
2801 = UnresolvedMemberExpr::Create(Context, Dependent,
2802 R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00002803 BaseExpr, BaseExprType,
2804 IsArrow, OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002805 Qualifier, SS.getRange(),
2806 MemberName, MemberLoc,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002807 TemplateArgs, R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00002808
2809 return Owned(MemExpr);
2810 }
2811
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002812 assert(R.isSingleResult());
John McCalla8ae2222010-04-06 21:38:20 +00002813 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall10eae182009-11-30 22:42:35 +00002814 NamedDecl *MemberDecl = R.getFoundDecl();
2815
2816 // FIXME: diagnose the presence of template arguments now.
2817
2818 // If the decl being referenced had an error, return an error for this
2819 // sub-expr without emitting another error, in order to avoid cascading
2820 // error cases.
2821 if (MemberDecl->isInvalidDecl())
2822 return ExprError();
2823
John McCall2d74de92009-12-01 22:10:20 +00002824 // Handle the implicit-member-access case.
2825 if (!BaseExpr) {
2826 // If this is not an instance member, convert to a non-member access.
John McCalla8ae2222010-04-06 21:38:20 +00002827 if (!MemberDecl->isCXXInstanceMember())
John McCall2d74de92009-12-01 22:10:20 +00002828 return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
2829
Douglas Gregorb15af892010-01-07 23:12:05 +00002830 SourceLocation Loc = R.getNameLoc();
2831 if (SS.getRange().isValid())
2832 Loc = SS.getRange().getBegin();
2833 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00002834 }
2835
John McCall10eae182009-11-30 22:42:35 +00002836 bool ShouldCheckUse = true;
2837 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2838 // Don't diagnose the use of a virtual member function unless it's
2839 // explicitly qualified.
2840 if (MD->isVirtual() && !SS.isSet())
2841 ShouldCheckUse = false;
2842 }
2843
2844 // Check the use of this member.
2845 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2846 Owned(BaseExpr);
2847 return ExprError();
2848 }
2849
2850 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2851 // We may have found a field within an anonymous union or struct
2852 // (C++ [class.union]).
Eli Friedman78cde142009-12-04 07:18:51 +00002853 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2854 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
John McCall10eae182009-11-30 22:42:35 +00002855 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2856 BaseExpr, OpLoc);
2857
2858 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2859 QualType MemberType = FD->getType();
2860 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2861 MemberType = Ref->getPointeeType();
2862 else {
2863 Qualifiers BaseQuals = BaseType.getQualifiers();
2864 BaseQuals.removeObjCGCAttr();
2865 if (FD->isMutable()) BaseQuals.removeConst();
2866
2867 Qualifiers MemberQuals
2868 = Context.getCanonicalType(MemberType).getQualifiers();
2869
2870 Qualifiers Combined = BaseQuals + MemberQuals;
2871 if (Combined != MemberQuals)
2872 MemberType = Context.getQualifiedType(MemberType, Combined);
2873 }
2874
2875 MarkDeclarationReferenced(MemberLoc, FD);
John McCall16df1e52010-03-30 21:47:33 +00002876 if (PerformObjectMemberConversion(BaseExpr, Qualifier, FoundDecl, FD))
John McCall10eae182009-11-30 22:42:35 +00002877 return ExprError();
2878 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
John McCall16df1e52010-03-30 21:47:33 +00002879 FD, FoundDecl, MemberLoc, MemberType));
John McCall10eae182009-11-30 22:42:35 +00002880 }
2881
2882 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2883 MarkDeclarationReferenced(MemberLoc, Var);
2884 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
John McCall16df1e52010-03-30 21:47:33 +00002885 Var, FoundDecl, MemberLoc,
John McCall10eae182009-11-30 22:42:35 +00002886 Var->getType().getNonReferenceType()));
2887 }
2888
2889 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2890 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2891 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
John McCall16df1e52010-03-30 21:47:33 +00002892 MemberFn, FoundDecl, MemberLoc,
John McCall10eae182009-11-30 22:42:35 +00002893 MemberFn->getType()));
2894 }
2895
2896 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2897 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2898 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
John McCall16df1e52010-03-30 21:47:33 +00002899 Enum, FoundDecl, MemberLoc, Enum->getType()));
John McCall10eae182009-11-30 22:42:35 +00002900 }
2901
2902 Owned(BaseExpr);
2903
Douglas Gregor861eb802010-04-25 20:55:08 +00002904 // We found something that we didn't expect. Complain.
John McCall10eae182009-11-30 22:42:35 +00002905 if (isa<TypeDecl>(MemberDecl))
Douglas Gregor861eb802010-04-25 20:55:08 +00002906 Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2907 << MemberName << BaseType << int(IsArrow);
2908 else
2909 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
2910 << MemberName << BaseType << int(IsArrow);
John McCall10eae182009-11-30 22:42:35 +00002911
Douglas Gregor861eb802010-04-25 20:55:08 +00002912 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
2913 << MemberName;
Douglas Gregor516d6722010-04-25 21:15:30 +00002914 R.suppressDiagnostics();
Douglas Gregor861eb802010-04-25 20:55:08 +00002915 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00002916}
2917
2918/// Look up the given member of the given non-type-dependent
2919/// expression. This can return in one of two ways:
2920/// * If it returns a sentinel null-but-valid result, the caller will
2921/// assume that lookup was performed and the results written into
2922/// the provided structure. It will take over from there.
2923/// * Otherwise, the returned expression will be produced in place of
2924/// an ordinary member expression.
2925///
2926/// The ObjCImpDecl bit is a gross hack that will need to be properly
2927/// fixed for ObjC++.
2928Sema::OwningExprResult
2929Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00002930 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002931 CXXScopeSpec &SS,
John McCalle9cccd82010-06-16 08:42:20 +00002932 DeclPtrTy ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00002933 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00002934
Steve Naroffeaaae462007-12-16 21:42:28 +00002935 // Perform default conversions.
2936 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002937
Steve Naroff185616f2007-07-26 03:11:44 +00002938 QualType BaseType = BaseExpr->getType();
John McCall10eae182009-11-30 22:42:35 +00002939 assert(!BaseType->isDependentType());
2940
2941 DeclarationName MemberName = R.getLookupName();
2942 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00002943
2944 // If the user is trying to apply -> or . to a function pointer
John McCall10eae182009-11-30 22:42:35 +00002945 // type, it's probably because they forgot parentheses to call that
Douglas Gregord82ae382009-11-06 06:30:47 +00002946 // function. Suggest the addition of those parentheses, build the
2947 // call, and continue on.
2948 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2949 if (const FunctionProtoType *Fun
2950 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2951 QualType ResultTy = Fun->getResultType();
2952 if (Fun->getNumArgs() == 0 &&
John McCall10eae182009-11-30 22:42:35 +00002953 ((!IsArrow && ResultTy->isRecordType()) ||
2954 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregord82ae382009-11-06 06:30:47 +00002955 ResultTy->getAs<PointerType>()->getPointeeType()
2956 ->isRecordType()))) {
2957 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2958 Diag(Loc, diag::err_member_reference_needs_call)
2959 << QualType(Fun, 0)
Douglas Gregora771f462010-03-31 17:46:05 +00002960 << FixItHint::CreateInsertion(Loc, "()");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002961
Douglas Gregord82ae382009-11-06 06:30:47 +00002962 OwningExprResult NewBase
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002963 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
Douglas Gregord82ae382009-11-06 06:30:47 +00002964 MultiExprArg(*this, 0, 0), 0, Loc);
Douglas Gregor143d3672010-06-21 22:46:46 +00002965 BaseExpr = 0;
Douglas Gregord82ae382009-11-06 06:30:47 +00002966 if (NewBase.isInvalid())
John McCall10eae182009-11-30 22:42:35 +00002967 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002968
Douglas Gregord82ae382009-11-06 06:30:47 +00002969 BaseExpr = NewBase.takeAs<Expr>();
2970 DefaultFunctionArrayConversion(BaseExpr);
2971 BaseType = BaseExpr->getType();
2972 }
2973 }
2974 }
2975
David Chisnall9f57c292009-08-17 16:35:33 +00002976 // If this is an Objective-C pseudo-builtin and a definition is provided then
2977 // use that.
2978 if (BaseType->isObjCIdType()) {
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00002979 if (IsArrow) {
2980 // Handle the following exceptional case PObj->isa.
2981 if (const ObjCObjectPointerType *OPT =
2982 BaseType->getAs<ObjCObjectPointerType>()) {
John McCall8b07ec22010-05-15 11:32:37 +00002983 if (OPT->getObjectType()->isObjCId() &&
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00002984 MemberName.getAsIdentifierInfo()->isStr("isa"))
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00002985 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
2986 Context.getObjCClassType()));
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00002987 }
2988 }
David Chisnall9f57c292009-08-17 16:35:33 +00002989 // We have an 'id' type. Rather than fall through, we check if this
2990 // is a reference to 'isa'.
2991 if (BaseType != Context.ObjCIdRedefinitionType) {
2992 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002993 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00002994 }
David Chisnall9f57c292009-08-17 16:35:33 +00002995 }
John McCall10eae182009-11-30 22:42:35 +00002996
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00002997 // If this is an Objective-C pseudo-builtin and a definition is provided then
2998 // use that.
2999 if (Context.isObjCSelType(BaseType)) {
3000 // We have an 'SEL' type. Rather than fall through, we check if this
3001 // is a reference to 'sel_id'.
3002 if (BaseType != Context.ObjCSelRedefinitionType) {
3003 BaseType = Context.ObjCSelRedefinitionType;
3004 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
3005 }
3006 }
John McCall10eae182009-11-30 22:42:35 +00003007
Steve Naroff185616f2007-07-26 03:11:44 +00003008 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003009
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003010 // Handle properties on ObjC 'Class' types.
John McCall10eae182009-11-30 22:42:35 +00003011 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003012 // Also must look for a getter name which uses property syntax.
3013 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3014 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3015 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
3016 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3017 ObjCMethodDecl *Getter;
3018 // FIXME: need to also look locally in the implementation.
3019 if ((Getter = IFace->lookupClassMethod(Sel))) {
3020 // Check the use of this method.
3021 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3022 return ExprError();
3023 }
3024 // If we found a getter then this may be a valid dot-reference, we
3025 // will look for the matching setter, in case it is needed.
3026 Selector SetterSel =
3027 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3028 PP.getSelectorTable(), Member);
3029 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3030 if (!Setter) {
3031 // If this reference is in an @implementation, also check for 'private'
3032 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00003033 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003034 }
3035 // Look through local category implementations associated with the class.
3036 if (!Setter)
3037 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003038
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003039 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3040 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003041
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003042 if (Getter || Setter) {
3043 QualType PType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003044
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003045 if (Getter)
Douglas Gregor603d81b2010-07-13 08:18:22 +00003046 PType = Getter->getSendResultType();
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003047 else
3048 // Get the expression type from Setter's incoming parameter.
3049 PType = (*(Setter->param_end() -1))->getType();
3050 // FIXME: we must check that the setter has property type.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003051 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003052 PType,
3053 Setter, MemberLoc, BaseExpr));
3054 }
3055 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3056 << MemberName << BaseType);
3057 }
3058 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003059
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003060 if (BaseType->isObjCClassType() &&
3061 BaseType != Context.ObjCClassRedefinitionType) {
3062 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00003063 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00003064 }
Mike Stump11289f42009-09-09 15:08:12 +00003065
John McCall10eae182009-11-30 22:42:35 +00003066 if (IsArrow) {
3067 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff185616f2007-07-26 03:11:44 +00003068 BaseType = PT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00003069 else if (BaseType->isObjCObjectPointerType())
3070 ;
John McCalla928c652009-12-07 22:46:59 +00003071 else if (BaseType->isRecordType()) {
3072 // Recover from arrow accesses to records, e.g.:
3073 // struct MyRecord foo;
3074 // foo->bar
3075 // This is actually well-formed in C++ if MyRecord has an
3076 // overloaded operator->, but that should have been dealt with
3077 // by now.
3078 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3079 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003080 << FixItHint::CreateReplacement(OpLoc, ".");
John McCalla928c652009-12-07 22:46:59 +00003081 IsArrow = false;
3082 } else {
John McCall10eae182009-11-30 22:42:35 +00003083 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3084 << BaseType << BaseExpr->getSourceRange();
3085 return ExprError();
Anders Carlsson524d5a42009-05-16 20:31:20 +00003086 }
John McCalla928c652009-12-07 22:46:59 +00003087 } else {
3088 // Recover from dot accesses to pointers, e.g.:
3089 // type *foo;
3090 // foo.bar
3091 // This is actually well-formed in two cases:
3092 // - 'type' is an Objective C type
3093 // - 'bar' is a pseudo-destructor name which happens to refer to
3094 // the appropriate pointer type
3095 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
3096 const PointerType *PT = BaseType->getAs<PointerType>();
3097 if (PT && PT->getPointeeType()->isRecordType()) {
3098 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3099 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003100 << FixItHint::CreateReplacement(OpLoc, "->");
John McCalla928c652009-12-07 22:46:59 +00003101 BaseType = PT->getPointeeType();
3102 IsArrow = true;
3103 }
3104 }
John McCall10eae182009-11-30 22:42:35 +00003105 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003106
John McCall8b07ec22010-05-15 11:32:37 +00003107 // Handle field access to simple records.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003108 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCall2d74de92009-12-01 22:10:20 +00003109 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
John McCalle9cccd82010-06-16 08:42:20 +00003110 RTy, OpLoc, SS, HasTemplateArgs))
Douglas Gregordd430f72009-01-19 19:26:10 +00003111 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00003112 return Owned((Expr*) 0);
Chris Lattnerb63a7452008-07-21 04:28:12 +00003113 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003114
Chris Lattnerdc420f42008-07-21 04:59:05 +00003115 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
3116 // (*Obj).ivar.
John McCall10eae182009-11-30 22:42:35 +00003117 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
John McCall8b07ec22010-05-15 11:32:37 +00003118 (!IsArrow && BaseType->isObjCObjectType())) {
John McCall9dd450b2009-09-21 23:43:11 +00003119 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
John McCall8b07ec22010-05-15 11:32:37 +00003120 ObjCInterfaceDecl *IDecl =
3121 OPT ? OPT->getInterfaceDecl()
3122 : BaseType->getAs<ObjCObjectType>()->getInterface();
3123 if (IDecl) {
Anders Carlssonf571c112009-08-26 18:25:21 +00003124 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3125
Steve Naroffa057ba92009-07-16 00:25:06 +00003126 ObjCInterfaceDecl *ClassDeclared;
Anders Carlssonf571c112009-08-26 18:25:21 +00003127 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump11289f42009-09-09 15:08:12 +00003128
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003129 if (!IV) {
3130 // Attempt to correct for typos in ivar names.
3131 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3132 LookupMemberName);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003133 if (CorrectTypo(Res, 0, 0, IDecl, false, CTC_MemberLookup) &&
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003134 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003135 Diag(R.getNameLoc(),
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003136 diag::err_typecheck_member_reference_ivar_suggest)
3137 << IDecl->getDeclName() << MemberName << IV->getDeclName()
Douglas Gregora771f462010-03-31 17:46:05 +00003138 << FixItHint::CreateReplacement(R.getNameLoc(),
3139 IV->getNameAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003140 Diag(IV->getLocation(), diag::note_previous_decl)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003141 << IV->getDeclName();
Douglas Gregorc048c522010-06-29 19:27:42 +00003142 } else {
3143 Res.clear();
3144 Res.setLookupName(Member);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00003145 }
3146 }
3147
Steve Naroffa057ba92009-07-16 00:25:06 +00003148 if (IV) {
3149 // If the decl being referenced had an error, return an error for this
3150 // sub-expr without emitting another error, in order to avoid cascading
3151 // error cases.
3152 if (IV->isInvalidDecl())
3153 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003154
Steve Naroffa057ba92009-07-16 00:25:06 +00003155 // Check whether we can reference this field.
3156 if (DiagnoseUseOfDecl(IV, MemberLoc))
3157 return ExprError();
3158 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3159 IV->getAccessControl() != ObjCIvarDecl::Package) {
3160 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3161 if (ObjCMethodDecl *MD = getCurMethodDecl())
3162 ClassOfMethodDecl = MD->getClassInterface();
3163 else if (ObjCImpDecl && getCurFunctionDecl()) {
3164 // Case of a c-function declared inside an objc implementation.
3165 // FIXME: For a c-style function nested inside an objc implementation
3166 // class, there is no implementation context available, so we pass
3167 // down the context as argument to this routine. Ideally, this context
3168 // need be passed down in the AST node and somehow calculated from the
3169 // AST for a function decl.
3170 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump11289f42009-09-09 15:08:12 +00003171 if (ObjCImplementationDecl *IMPD =
Steve Naroffa057ba92009-07-16 00:25:06 +00003172 dyn_cast<ObjCImplementationDecl>(ImplDecl))
3173 ClassOfMethodDecl = IMPD->getClassInterface();
3174 else if (ObjCCategoryImplDecl* CatImplClass =
3175 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
3176 ClassOfMethodDecl = CatImplClass->getClassInterface();
3177 }
Mike Stump11289f42009-09-09 15:08:12 +00003178
3179 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3180 if (ClassDeclared != IDecl ||
Steve Naroffa057ba92009-07-16 00:25:06 +00003181 ClassOfMethodDecl != ClassDeclared)
Mike Stump11289f42009-09-09 15:08:12 +00003182 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00003183 << IV->getDeclName();
Mike Stump12b8ce12009-08-04 21:02:39 +00003184 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3185 // @protected
Mike Stump11289f42009-09-09 15:08:12 +00003186 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00003187 << IV->getDeclName();
Steve Naroffd1b64be2009-03-04 18:34:24 +00003188 }
Steve Naroffa057ba92009-07-16 00:25:06 +00003189
3190 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3191 MemberLoc, BaseExpr,
John McCall10eae182009-11-30 22:42:35 +00003192 IsArrow));
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +00003193 }
Steve Naroffa057ba92009-07-16 00:25:06 +00003194 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlssonf571c112009-08-26 18:25:21 +00003195 << IDecl->getDeclName() << MemberName
Steve Naroffa057ba92009-07-16 00:25:06 +00003196 << BaseExpr->getSourceRange());
Fariborz Jahanianb1378f92008-12-13 22:20:28 +00003197 }
Chris Lattnerb63a7452008-07-21 04:28:12 +00003198 }
Steve Naroff1329fa02009-07-15 18:40:39 +00003199 // Handle properties on 'id' and qualified "id".
John McCall10eae182009-11-30 22:42:35 +00003200 if (!IsArrow && (BaseType->isObjCIdType() ||
3201 BaseType->isObjCQualifiedIdType())) {
John McCall9dd450b2009-09-21 23:43:11 +00003202 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlssonf571c112009-08-26 18:25:21 +00003203 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00003204
Steve Naroff7cae42b2009-07-10 23:34:53 +00003205 // Check protocols on qualified interfaces.
Anders Carlssonf571c112009-08-26 18:25:21 +00003206 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003207 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
3208 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3209 // Check the use of this declaration
3210 if (DiagnoseUseOfDecl(PD, MemberLoc))
3211 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003212
Steve Naroff7cae42b2009-07-10 23:34:53 +00003213 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3214 MemberLoc, BaseExpr));
3215 }
3216 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3217 // Check the use of this method.
3218 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3219 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003220
Alexis Huntc46382e2010-04-28 23:02:27 +00003221 return Owned(ObjCMessageExpr::Create(Context,
Douglas Gregor603d81b2010-07-13 08:18:22 +00003222 OMD->getSendResultType(),
Douglas Gregor9a129192010-04-21 00:45:42 +00003223 OpLoc, BaseExpr, Sel,
3224 OMD, NULL, 0, MemberLoc));
Steve Naroff7cae42b2009-07-10 23:34:53 +00003225 }
3226 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003227
Steve Naroff7cae42b2009-07-10 23:34:53 +00003228 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00003229 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003230 }
Alexis Huntc46382e2010-04-28 23:02:27 +00003231
Chris Lattnerdc420f42008-07-21 04:59:05 +00003232 // Handle Objective-C property access, which is "Obj.property" where Obj is a
3233 // pointer to a (potentially qualified) interface type.
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00003234 if (!IsArrow)
3235 if (const ObjCObjectPointerType *OPT =
3236 BaseType->getAsObjCInterfacePointerType())
Chris Lattner90c58fa2010-04-11 07:51:10 +00003237 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003238
Steve Naroffe87026a2009-07-24 17:54:45 +00003239 // Handle the following exceptional case (*Obj).isa.
John McCall10eae182009-11-30 22:42:35 +00003240 if (!IsArrow &&
John McCall8b07ec22010-05-15 11:32:37 +00003241 BaseType->isObjCObjectType() &&
3242 BaseType->getAs<ObjCObjectType>()->isObjCId() &&
Anders Carlssonf571c112009-08-26 18:25:21 +00003243 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroffe87026a2009-07-24 17:54:45 +00003244 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahaniana5fee262009-12-09 19:05:56 +00003245 Context.getObjCClassType()));
Steve Naroffe87026a2009-07-24 17:54:45 +00003246
Chris Lattnerb63a7452008-07-21 04:28:12 +00003247 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003248 if (BaseType->isExtVectorType()) {
Anders Carlssonf571c112009-08-26 18:25:21 +00003249 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerb63a7452008-07-21 04:28:12 +00003250 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
3251 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003252 return ExprError();
Anders Carlssonf571c112009-08-26 18:25:21 +00003253 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Narofff6009ed2009-01-21 00:14:39 +00003254 MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00003255 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003256
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003257 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3258 << BaseType << BaseExpr->getSourceRange();
3259
Douglas Gregor0b08ba42009-03-27 06:00:30 +00003260 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00003261}
3262
John McCall10eae182009-11-30 22:42:35 +00003263/// The main callback when the parser finds something like
3264/// expression . [nested-name-specifier] identifier
3265/// expression -> [nested-name-specifier] identifier
3266/// where 'identifier' encompasses a fairly broad spectrum of
3267/// possibilities, including destructor and operator references.
3268///
3269/// \param OpKind either tok::arrow or tok::period
3270/// \param HasTrailingLParen whether the next token is '(', which
3271/// is used to diagnose mis-uses of special members that can
3272/// only be called
3273/// \param ObjCImpDecl the current ObjC @implementation decl;
3274/// this is an ugly hack around the fact that ObjC @implementations
3275/// aren't properly put in the context chain
3276Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
3277 SourceLocation OpLoc,
3278 tok::TokenKind OpKind,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003279 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003280 UnqualifiedId &Id,
3281 DeclPtrTy ObjCImpDecl,
3282 bool HasTrailingLParen) {
3283 if (SS.isSet() && SS.isInvalid())
3284 return ExprError();
3285
3286 TemplateArgumentListInfo TemplateArgsBuffer;
3287
3288 // Decompose the name into its component parts.
3289 DeclarationName Name;
3290 SourceLocation NameLoc;
3291 const TemplateArgumentListInfo *TemplateArgs;
3292 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
3293 Name, NameLoc, TemplateArgs);
3294
3295 bool IsArrow = (OpKind == tok::arrow);
3296
3297 NamedDecl *FirstQualifierInScope
3298 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3299 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3300
3301 // This is a postfix expression, so get rid of ParenListExprs.
3302 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
3303
3304 Expr *Base = BaseArg.takeAs<Expr>();
3305 OwningExprResult Result(*this);
Douglas Gregor41f90302010-04-12 20:54:26 +00003306 if (Base->getType()->isDependentType() || Name.isDependentName() ||
3307 isDependentScopeSpecifier(SS)) {
John McCall2d74de92009-12-01 22:10:20 +00003308 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00003309 IsArrow, OpLoc,
3310 SS, FirstQualifierInScope,
3311 Name, NameLoc,
3312 TemplateArgs);
3313 } else {
3314 LookupResult R(*this, Name, NameLoc, LookupMemberName);
John McCalle9cccd82010-06-16 08:42:20 +00003315 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3316 SS, ObjCImpDecl, TemplateArgs != 0);
Alexis Huntc46382e2010-04-28 23:02:27 +00003317
John McCalle9cccd82010-06-16 08:42:20 +00003318 if (Result.isInvalid()) {
3319 Owned(Base);
3320 return ExprError();
3321 }
John McCall10eae182009-11-30 22:42:35 +00003322
John McCalle9cccd82010-06-16 08:42:20 +00003323 if (Result.get()) {
3324 // The only way a reference to a destructor can be used is to
3325 // immediately call it, which falls into this case. If the
3326 // next token is not a '(', produce a diagnostic and build the
3327 // call now.
3328 if (!HasTrailingLParen &&
3329 Id.getKind() == UnqualifiedId::IK_DestructorName)
3330 return DiagnoseDtorReference(NameLoc, move(Result));
John McCall10eae182009-11-30 22:42:35 +00003331
John McCalle9cccd82010-06-16 08:42:20 +00003332 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00003333 }
3334
John McCall2d74de92009-12-01 22:10:20 +00003335 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00003336 OpLoc, IsArrow, SS, FirstQualifierInScope,
3337 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003338 }
3339
3340 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00003341}
3342
Anders Carlsson355933d2009-08-25 03:49:14 +00003343Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3344 FunctionDecl *FD,
3345 ParmVarDecl *Param) {
3346 if (Param->hasUnparsedDefaultArg()) {
3347 Diag (CallLoc,
3348 diag::err_use_of_default_argument_to_function_declared_later) <<
3349 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003350 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson355933d2009-08-25 03:49:14 +00003351 diag::note_default_argument_declared_here);
3352 } else {
3353 if (Param->hasUninstantiatedDefaultArg()) {
3354 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3355
3356 // Instantiate the expression.
Douglas Gregor8c702532010-02-05 07:33:43 +00003357 MultiLevelTemplateArgumentList ArgList
3358 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003359
Douglas Gregor9961ce92010-07-08 18:37:38 +00003360 std::pair<const TemplateArgument *, unsigned> Innermost
3361 = ArgList.getInnermost();
3362 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3363 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003364
John McCall76d824f2009-08-25 22:02:44 +00003365 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump11289f42009-09-09 15:08:12 +00003366 if (Result.isInvalid())
Anders Carlsson355933d2009-08-25 03:49:14 +00003367 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003368
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003369 // Check the expression as an initializer for the parameter.
3370 InitializedEntity Entity
3371 = InitializedEntity::InitializeParameter(Param);
3372 InitializationKind Kind
3373 = InitializationKind::CreateCopy(Param->getLocation(),
3374 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3375 Expr *ResultE = Result.takeAs<Expr>();
3376
3377 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003378 Result = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003379 MultiExprArg(*this, (void**)&ResultE, 1));
3380 if (Result.isInvalid())
Anders Carlsson355933d2009-08-25 03:49:14 +00003381 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003382
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003383 // Build the default argument expression.
Douglas Gregor033f6752009-12-23 23:03:06 +00003384 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003385 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003386 }
Mike Stump11289f42009-09-09 15:08:12 +00003387
Anders Carlsson355933d2009-08-25 03:49:14 +00003388 // If the default expression creates temporaries, we need to
3389 // push them to the current stack of expression temporaries so they'll
3390 // be properly destroyed.
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003391 // FIXME: We should really be rebuilding the default argument with new
3392 // bound temporaries; see the comment in PR5810.
Anders Carlsson714d0962009-12-15 19:16:31 +00003393 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i)
3394 ExprTemporaries.push_back(Param->getDefaultArgTemporary(i));
Anders Carlsson355933d2009-08-25 03:49:14 +00003395 }
3396
3397 // We already type-checked the argument, so we know it works.
Douglas Gregor033f6752009-12-23 23:03:06 +00003398 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003399}
3400
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003401/// ConvertArgumentsForCall - Converts the arguments specified in
3402/// Args/NumArgs to the parameter types of the function FDecl with
3403/// function prototype Proto. Call is the call expression itself, and
3404/// Fn is the function expression. For a C++ member function, this
3405/// routine does not attempt to convert the object argument. Returns
3406/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003407bool
3408Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003409 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003410 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003411 Expr **Args, unsigned NumArgs,
3412 SourceLocation RParenLoc) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003413 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003414 // assignment, to the types of the corresponding parameter, ...
3415 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003416 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003417
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003418 // If too few arguments are available (and we don't have default
3419 // arguments for the remaining parameters), don't make the call.
3420 if (NumArgs < NumArgsInProto) {
3421 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3422 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003423 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00003424 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00003425 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003426 }
3427
3428 // If too many are passed and not variadic, error on the extras and drop
3429 // them.
3430 if (NumArgs > NumArgsInProto) {
3431 if (!Proto->isVariadic()) {
3432 Diag(Args[NumArgsInProto]->getLocStart(),
3433 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003434 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003435 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003436 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3437 Args[NumArgs-1]->getLocEnd());
3438 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003439 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003440 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003441 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003442 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003443 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003444 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003445 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3446 if (Fn->getType()->isBlockPointerType())
3447 CallType = VariadicBlock; // Block
3448 else if (isa<MemberExpr>(Fn))
3449 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003450 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003451 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003452 if (Invalid)
3453 return true;
3454 unsigned TotalNumArgs = AllArgs.size();
3455 for (unsigned i = 0; i < TotalNumArgs; ++i)
3456 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003457
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003458 return false;
3459}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003460
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003461bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3462 FunctionDecl *FDecl,
3463 const FunctionProtoType *Proto,
3464 unsigned FirstProtoArg,
3465 Expr **Args, unsigned NumArgs,
3466 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003467 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003468 unsigned NumArgsInProto = Proto->getNumArgs();
3469 unsigned NumArgsToCheck = NumArgs;
3470 bool Invalid = false;
3471 if (NumArgs != NumArgsInProto)
3472 // Use default arguments for missing arguments
3473 NumArgsToCheck = NumArgsInProto;
3474 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003475 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003476 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003477 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003478
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003479 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003480 if (ArgIx < NumArgs) {
3481 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003482
Eli Friedman3164fb12009-03-22 22:00:50 +00003483 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3484 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003485 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003486 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003487 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003488
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003489 // Pass the argument
3490 ParmVarDecl *Param = 0;
3491 if (FDecl && i < FDecl->getNumParams())
3492 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003493
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003494
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003495 InitializedEntity Entity =
3496 Param? InitializedEntity::InitializeParameter(Param)
3497 : InitializedEntity::InitializeParameter(ProtoArgType);
3498 OwningExprResult ArgE = PerformCopyInitialization(Entity,
3499 SourceLocation(),
3500 Owned(Arg));
3501 if (ArgE.isInvalid())
3502 return true;
3503
3504 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003505 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003506 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003507
Mike Stump11289f42009-09-09 15:08:12 +00003508 OwningExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003509 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003510 if (ArgExpr.isInvalid())
3511 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003512
Anders Carlsson355933d2009-08-25 03:49:14 +00003513 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003514 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003515 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003516 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003517
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003518 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003519 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003520 // Promote the arguments (C99 6.5.2.2p7).
Chris Lattnerbb53efb2010-05-16 04:01:30 +00003521 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003522 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00003523 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003524 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003525 }
3526 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003527 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003528}
3529
Steve Naroff83895f72007-09-16 03:34:24 +00003530/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003531/// This provides the location of the left/right parens and a list of comma
3532/// locations.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003533Action::OwningExprResult
3534Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3535 MultiExprArg args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003536 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003537 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003538
3539 // Since this might be a postfix expression, get rid of ParenListExprs.
3540 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump11289f42009-09-09 15:08:12 +00003541
Anders Carlsson3cbc8592009-05-01 19:30:39 +00003542 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003543 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner38dbdb22007-07-21 03:03:59 +00003544 assert(Fn && "no function call expression");
Mike Stump11289f42009-09-09 15:08:12 +00003545
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003546 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003547 // If this is a pseudo-destructor expression, build the call immediately.
3548 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3549 if (NumArgs > 0) {
3550 // Pseudo-destructor calls should not have any arguments.
3551 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003552 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003553 SourceRange(Args[0]->getLocStart(),
3554 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003555
Douglas Gregorad8a3362009-09-04 17:36:40 +00003556 for (unsigned I = 0; I != NumArgs; ++I)
3557 Args[I]->Destroy(Context);
Mike Stump11289f42009-09-09 15:08:12 +00003558
Douglas Gregorad8a3362009-09-04 17:36:40 +00003559 NumArgs = 0;
3560 }
Mike Stump11289f42009-09-09 15:08:12 +00003561
Douglas Gregorad8a3362009-09-04 17:36:40 +00003562 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3563 RParenLoc));
3564 }
Mike Stump11289f42009-09-09 15:08:12 +00003565
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003566 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003567 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003568 // FIXME: Will need to cache the results of name lookup (including ADL) in
3569 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003570 bool Dependent = false;
3571 if (Fn->isTypeDependent())
3572 Dependent = true;
3573 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3574 Dependent = true;
3575
3576 if (Dependent)
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003577 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003578 Context.DependentTy, RParenLoc));
3579
3580 // Determine whether this is a call to an object (C++ [over.call.object]).
3581 if (Fn->getType()->isRecordType())
3582 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3583 CommaLocs, RParenLoc));
3584
John McCall10eae182009-11-30 22:42:35 +00003585 Expr *NakedFn = Fn->IgnoreParens();
3586
3587 // Determine whether this is a call to an unresolved member function.
3588 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3589 // If lookup was unresolved but not dependent (i.e. didn't find
3590 // an unresolved using declaration), it has to be an overloaded
3591 // function set, which means it must contain either multiple
3592 // declarations (all methods or method templates) or a single
3593 // method template.
3594 assert((MemE->getNumDecls() > 1) ||
Douglas Gregor516d6722010-04-25 21:15:30 +00003595 isa<FunctionTemplateDecl>(
3596 (*MemE->decls_begin())->getUnderlyingDecl()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00003597 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00003598
John McCall2d74de92009-12-01 22:10:20 +00003599 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3600 CommaLocs, RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003601 }
3602
Douglas Gregore254f902009-02-04 00:32:51 +00003603 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00003604 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003605 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00003606 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00003607 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3608 CommaLocs, RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003609 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003610
Anders Carlsson61914b52009-10-03 17:40:22 +00003611 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00003612 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson61914b52009-10-03 17:40:22 +00003613 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3614 BO->getOpcode() == BinaryOperator::PtrMemI) {
Douglas Gregorc8be9522010-05-04 18:18:31 +00003615 if (const FunctionProtoType *FPT
3616 = BO->getType()->getAs<FunctionProtoType>()) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00003617 QualType ResultTy = FPT->getCallResultType(Context);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003618
3619 ExprOwningPtr<CXXMemberCallExpr>
3620 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003621 NumArgs, ResultTy,
3622 RParenLoc));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003623
3624 if (CheckCallReturnType(FPT->getResultType(),
3625 BO->getRHS()->getSourceRange().getBegin(),
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003626 TheCall.get(), 0))
3627 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00003628
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003629 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003630 RParenLoc))
3631 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00003632
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003633 return Owned(MaybeBindToTemporary(TheCall.release()).release());
3634 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003635 return ExprError(Diag(Fn->getLocStart(),
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003636 diag::err_typecheck_call_not_function)
3637 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson61914b52009-10-03 17:40:22 +00003638 }
3639 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003640 }
3641
Douglas Gregore254f902009-02-04 00:32:51 +00003642 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003643 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00003644 // lookup and whether there were any explicitly-specified template arguments.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003645
Eli Friedmane14b1992009-12-26 03:35:45 +00003646 Expr *NakedFn = Fn->IgnoreParens();
John McCall57500772009-12-16 12:17:52 +00003647 if (isa<UnresolvedLookupExpr>(NakedFn)) {
3648 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
Douglas Gregor2fb18b72010-04-14 20:27:54 +00003649 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall57500772009-12-16 12:17:52 +00003650 CommaLocs, RParenLoc);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003651 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003652
John McCall57500772009-12-16 12:17:52 +00003653 NamedDecl *NDecl = 0;
3654 if (isa<DeclRefExpr>(NakedFn))
3655 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3656
John McCall2d74de92009-12-01 22:10:20 +00003657 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3658}
3659
John McCall57500772009-12-16 12:17:52 +00003660/// BuildResolvedCallExpr - Build a call to a resolved expression,
3661/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003662/// unary-convert to an expression of function-pointer or
3663/// block-pointer type.
3664///
3665/// \param NDecl the declaration being called, if available
3666Sema::OwningExprResult
3667Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3668 SourceLocation LParenLoc,
3669 Expr **Args, unsigned NumArgs,
3670 SourceLocation RParenLoc) {
3671 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3672
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003673 // Promote the function operand.
3674 UsualUnaryConversions(Fn);
3675
Chris Lattner08464942007-12-28 05:29:59 +00003676 // Make the call expr early, before semantic checks. This guarantees cleanup
3677 // of arguments and function on error.
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003678 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3679 Args, NumArgs,
3680 Context.BoolTy,
3681 RParenLoc));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003682
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003683 const FunctionType *FuncT;
3684 if (!Fn->getType()->isBlockPointerType()) {
3685 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3686 // have type pointer to function".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003687 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003688 if (PT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003689 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3690 << Fn->getType() << Fn->getSourceRange());
John McCall9dd450b2009-09-21 23:43:11 +00003691 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003692 } else { // This is a block call.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003693 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall9dd450b2009-09-21 23:43:11 +00003694 getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003695 }
Chris Lattner08464942007-12-28 05:29:59 +00003696 if (FuncT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003697 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3698 << Fn->getType() << Fn->getSourceRange());
3699
Eli Friedman3164fb12009-03-22 22:00:50 +00003700 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003701 if (CheckCallReturnType(FuncT->getResultType(),
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003702 Fn->getSourceRange().getBegin(), TheCall.get(),
3703 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003704 return ExprError();
3705
Chris Lattner08464942007-12-28 05:29:59 +00003706 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003707 TheCall->setType(FuncT->getCallResultType(Context));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003708
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003709 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003710 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003711 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003712 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003713 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003714 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003715
Douglas Gregord8e97de2009-04-02 15:37:10 +00003716 if (FDecl) {
3717 // Check if we have too few/too many template arguments, based
3718 // on our knowledge of the function definition.
3719 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003720 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003721 const FunctionProtoType *Proto =
John McCall9dd450b2009-09-21 23:43:11 +00003722 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003723 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3724 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3725 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3726 }
3727 }
Douglas Gregord8e97de2009-04-02 15:37:10 +00003728 }
3729
Steve Naroff0b661582007-08-28 23:30:39 +00003730 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003731 for (unsigned i = 0; i != NumArgs; i++) {
3732 Expr *Arg = Args[i];
3733 DefaultArgumentPromotion(Arg);
Eli Friedman3164fb12009-03-22 22:00:50 +00003734 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3735 Arg->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00003736 PDiag(diag::err_call_incomplete_argument)
3737 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003738 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003739 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003740 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003741 }
Chris Lattner08464942007-12-28 05:29:59 +00003742
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003743 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3744 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003745 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3746 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003747
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003748 // Check for sentinels
3749 if (NDecl)
3750 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003751
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003752 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003753 if (FDecl) {
3754 if (CheckFunctionCall(FDecl, TheCall.get()))
3755 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003756
Douglas Gregor15fc9562009-09-12 00:22:50 +00003757 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003758 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3759 } else if (NDecl) {
3760 if (CheckBlockCall(NDecl, TheCall.get()))
3761 return ExprError();
3762 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003763
Anders Carlssonf8984012009-08-16 03:06:32 +00003764 return MaybeBindToTemporary(TheCall.take());
Chris Lattnere168f762006-11-10 05:29:30 +00003765}
3766
Sebastian Redlb5d49352009-01-19 22:31:54 +00003767Action::OwningExprResult
3768Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3769 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003770 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003771 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003772 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003773
3774 TypeSourceInfo *TInfo;
3775 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3776 if (!TInfo)
3777 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3778
3779 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, move(InitExpr));
3780}
3781
3782Action::OwningExprResult
3783Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
3784 SourceLocation RParenLoc, ExprArg InitExpr) {
3785 QualType literalType = TInfo->getType();
Sebastian Redlb5d49352009-01-19 22:31:54 +00003786 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003787
Eli Friedman37a186d2008-05-20 05:22:08 +00003788 if (literalType->isArrayType()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003789 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003790 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3791 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003792 } else if (!literalType->isDependentType() &&
3793 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003794 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003795 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003796 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003797 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003798
Douglas Gregor85dabae2009-12-16 01:38:02 +00003799 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003800 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003801 InitializationKind Kind
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003802 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor85dabae2009-12-16 01:38:02 +00003803 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00003804 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
3805 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3806 MultiExprArg(*this, (void**)&literalExpr, 1),
3807 &literalType);
3808 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003809 return ExprError();
Eli Friedmana553d4a2009-12-22 02:35:53 +00003810 InitExpr.release();
3811 literalExpr = static_cast<Expr*>(Result.get());
Steve Naroffd32419d2008-01-14 18:19:28 +00003812
Chris Lattner79413952008-12-04 23:50:19 +00003813 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003814 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003815 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003816 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003817 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003818
3819 Result.release();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003820
John McCall5d7aa7f2010-01-19 22:33:45 +00003821 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Steve Narofff6009ed2009-01-21 00:14:39 +00003822 literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003823}
3824
Sebastian Redlb5d49352009-01-19 22:31:54 +00003825Action::OwningExprResult
3826Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003827 SourceLocation RBraceLoc) {
3828 unsigned NumInit = initlist.size();
3829 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson4692db02007-08-31 04:56:16 +00003830
Steve Naroff30d242c2007-09-15 18:49:24 +00003831 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003832 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003833
Ted Kremenekac034612010-04-13 23:39:13 +00003834 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3835 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003836 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003837 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003838}
3839
Anders Carlsson094c4592009-10-18 18:12:03 +00003840static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3841 QualType SrcTy, QualType DestTy) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003842 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson094c4592009-10-18 18:12:03 +00003843 return CastExpr::CK_NoOp;
3844
3845 if (SrcTy->hasPointerRepresentation()) {
3846 if (DestTy->hasPointerRepresentation())
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003847 return DestTy->isObjCObjectPointerType() ?
3848 CastExpr::CK_AnyPointerToObjCPointerCast :
Fariborz Jahanian2b9fc832009-12-15 21:34:52 +00003849 CastExpr::CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00003850 if (DestTy->isIntegerType())
3851 return CastExpr::CK_PointerToIntegral;
3852 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003853
Anders Carlsson094c4592009-10-18 18:12:03 +00003854 if (SrcTy->isIntegerType()) {
3855 if (DestTy->isIntegerType())
3856 return CastExpr::CK_IntegralCast;
3857 if (DestTy->hasPointerRepresentation())
3858 return CastExpr::CK_IntegralToPointer;
3859 if (DestTy->isRealFloatingType())
3860 return CastExpr::CK_IntegralToFloating;
3861 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003862
Anders Carlsson094c4592009-10-18 18:12:03 +00003863 if (SrcTy->isRealFloatingType()) {
3864 if (DestTy->isRealFloatingType())
3865 return CastExpr::CK_FloatingCast;
3866 if (DestTy->isIntegerType())
3867 return CastExpr::CK_FloatingToIntegral;
3868 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003869
Anders Carlsson094c4592009-10-18 18:12:03 +00003870 // FIXME: Assert here.
3871 // assert(false && "Unhandled cast combination!");
3872 return CastExpr::CK_Unknown;
3873}
3874
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003875/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redl955a0672009-07-29 13:50:23 +00003876bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump11289f42009-09-09 15:08:12 +00003877 CastExpr::CastKind& Kind,
Anders Carlssona70cff62010-04-24 19:06:50 +00003878 CXXBaseSpecifierArray &BasePath,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003879 bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00003880 if (getLangOptions().CPlusPlus)
Anders Carlssona70cff62010-04-24 19:06:50 +00003881 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, BasePath,
3882 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003883
Douglas Gregorb92a1562010-02-03 00:27:59 +00003884 DefaultFunctionArrayLvalueConversion(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003885
3886 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3887 // type needs to be scalar.
3888 if (castType->isVoidType()) {
3889 // Cast to void allows any expr type.
Anders Carlssonef918ac2009-10-16 02:35:04 +00003890 Kind = CastExpr::CK_ToVoid;
3891 return false;
3892 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003893
Eli Friedmane98194d2010-07-17 20:43:49 +00003894 if (RequireCompleteType(TyR.getBegin(), castType,
3895 diag::err_typecheck_cast_to_incomplete))
3896 return true;
3897
Anders Carlssonef918ac2009-10-16 02:35:04 +00003898 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003899 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003900 (castType->isStructureType() || castType->isUnionType())) {
3901 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00003902 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003903 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3904 << castType << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003905 Kind = CastExpr::CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003906 return false;
3907 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003908
Anders Carlsson525b76b2009-10-16 02:48:28 +00003909 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003910 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003911 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003912 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003913 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003914 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003915 if (Context.hasSameUnqualifiedType(Field->getType(),
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003916 castExpr->getType())) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003917 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3918 << castExpr->getSourceRange();
3919 break;
3920 }
3921 }
3922 if (Field == FieldEnd)
3923 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3924 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003925 Kind = CastExpr::CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003926 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003927 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003928
Anders Carlsson525b76b2009-10-16 02:48:28 +00003929 // Reject any other conversions to non-scalar types.
3930 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3931 << castType << castExpr->getSourceRange();
3932 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003933
3934 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00003935 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003936 return Diag(castExpr->getLocStart(),
3937 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003938 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00003939 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003940
3941 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00003942 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003943
Anders Carlsson525b76b2009-10-16 02:48:28 +00003944 if (castType->isVectorType())
3945 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3946 if (castExpr->getType()->isVectorType())
3947 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3948
Anders Carlsson43d70f82009-10-16 05:23:41 +00003949 if (isa<ObjCSelectorExpr>(castExpr))
3950 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003951
Anders Carlsson525b76b2009-10-16 02:48:28 +00003952 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00003953 QualType castExprType = castExpr->getType();
Douglas Gregor6972a622010-06-16 00:35:25 +00003954 if (!castExprType->isIntegralType(Context) &&
Douglas Gregorb90df602010-06-16 00:17:44 +00003955 castExprType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00003956 return Diag(castExpr->getLocStart(),
3957 diag::err_cast_pointer_from_non_pointer_int)
3958 << castExprType << castExpr->getSourceRange();
3959 } else if (!castExpr->getType()->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00003960 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00003961 return Diag(castExpr->getLocStart(),
3962 diag::err_cast_pointer_to_non_pointer_int)
3963 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003964 }
Anders Carlsson094c4592009-10-18 18:12:03 +00003965
3966 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003967 return false;
3968}
3969
Anders Carlsson525b76b2009-10-16 02:48:28 +00003970bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3971 CastExpr::CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00003972 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00003973
Anders Carlssonde71adf2007-11-27 05:51:55 +00003974 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00003975 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00003976 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00003977 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00003978 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00003979 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003980 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003981 } else
3982 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003983 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003984 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003985
Anders Carlsson525b76b2009-10-16 02:48:28 +00003986 Kind = CastExpr::CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003987 return false;
3988}
3989
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003990bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
Anders Carlsson43d70f82009-10-16 05:23:41 +00003991 CastExpr::CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00003992 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003993
Anders Carlsson43d70f82009-10-16 05:23:41 +00003994 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003995
Nate Begemanc8961a42009-06-27 22:05:55 +00003996 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3997 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00003998 if (SrcTy->isVectorType()) {
3999 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
4000 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4001 << DestTy << SrcTy << R;
Anders Carlsson43d70f82009-10-16 05:23:41 +00004002 Kind = CastExpr::CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00004003 return false;
4004 }
4005
Nate Begemanbd956c42009-06-28 02:36:38 +00004006 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004007 // conversion will take place first from scalar to elt type, and then
4008 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004009 if (SrcTy->isPointerType())
4010 return Diag(R.getBegin(),
4011 diag::err_invalid_conversion_between_vector_and_scalar)
4012 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004013
4014 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4015 ImpCastExprToType(CastExpr, DestElemTy,
4016 getScalarCastKind(Context, SrcTy, DestElemTy));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004017
Anders Carlsson43d70f82009-10-16 05:23:41 +00004018 Kind = CastExpr::CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00004019 return false;
4020}
4021
Sebastian Redlb5d49352009-01-19 22:31:54 +00004022Action::OwningExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00004023Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004024 SourceLocation RParenLoc, ExprArg Op) {
4025 assert((Ty != 0) && (Op.get() != 0) &&
4026 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004027
John McCall97513962010-01-15 18:39:57 +00004028 TypeSourceInfo *castTInfo;
4029 QualType castType = GetTypeFromParser(Ty, &castTInfo);
4030 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00004031 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00004032
Nate Begeman5ec4b312009-08-10 23:49:36 +00004033 // If the Expr being casted is a ParenListExpr, handle it specially.
John McCallebe54742010-01-15 18:56:44 +00004034 Expr *castExpr = (Expr *)Op.get();
Nate Begeman5ec4b312009-08-10 23:49:36 +00004035 if (isa<ParenListExpr>(castExpr))
John McCalle15bbff2010-01-18 19:35:47 +00004036 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),
4037 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00004038
4039 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, move(Op));
4040}
4041
4042Action::OwningExprResult
4043Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
4044 SourceLocation RParenLoc, ExprArg Op) {
4045 Expr *castExpr = static_cast<Expr*>(Op.get());
4046
John McCallebe54742010-01-15 18:56:44 +00004047 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson5d270e82010-04-24 18:38:56 +00004048 CXXBaseSpecifierArray BasePath;
John McCallebe54742010-01-15 18:56:44 +00004049 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
Anders Carlssona70cff62010-04-24 19:06:50 +00004050 Kind, BasePath))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004051 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00004052
Douglas Gregorb33eed02010-04-16 22:09:46 +00004053 Op.release();
Douglas Gregora8a089b2010-07-13 18:40:04 +00004054 return Owned(new (Context) CStyleCastExpr(
4055 Ty->getType().getNonLValueExprType(Context),
Anders Carlsson5d270e82010-04-24 18:38:56 +00004056 Kind, castExpr, BasePath, Ty,
Anders Carlssonf10e4142009-08-07 22:21:05 +00004057 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004058}
4059
Nate Begeman5ec4b312009-08-10 23:49:36 +00004060/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4061/// of comma binary operators.
4062Action::OwningExprResult
4063Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
4064 Expr *expr = EA.takeAs<Expr>();
4065 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4066 if (!E)
4067 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00004068
Nate Begeman5ec4b312009-08-10 23:49:36 +00004069 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004070
Nate Begeman5ec4b312009-08-10 23:49:36 +00004071 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
4072 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
4073 Owned(E->getExpr(i)));
Mike Stump11289f42009-09-09 15:08:12 +00004074
Nate Begeman5ec4b312009-08-10 23:49:36 +00004075 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
4076}
4077
4078Action::OwningExprResult
4079Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
4080 SourceLocation RParenLoc, ExprArg Op,
John McCalle15bbff2010-01-18 19:35:47 +00004081 TypeSourceInfo *TInfo) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004082 ParenListExpr *PE = (ParenListExpr *)Op.get();
John McCalle15bbff2010-01-18 19:35:47 +00004083 QualType Ty = TInfo->getType();
John Thompson781ad172010-06-30 22:55:51 +00004084 bool isAltiVecLiteral = false;
Mike Stump11289f42009-09-09 15:08:12 +00004085
John Thompson781ad172010-06-30 22:55:51 +00004086 // Check for an altivec literal,
4087 // i.e. all the elements are integer constants.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004088 if (getLangOptions().AltiVec && Ty->isVectorType()) {
4089 if (PE->getNumExprs() == 0) {
4090 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
4091 return ExprError();
4092 }
John Thompson781ad172010-06-30 22:55:51 +00004093 if (PE->getNumExprs() == 1) {
4094 if (!PE->getExpr(0)->getType()->isVectorType())
4095 isAltiVecLiteral = true;
4096 }
4097 else
4098 isAltiVecLiteral = true;
4099 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00004100
John Thompson781ad172010-06-30 22:55:51 +00004101 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
4102 // then handle it as such.
4103 if (isAltiVecLiteral) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004104 llvm::SmallVector<Expr *, 8> initExprs;
4105 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
4106 initExprs.push_back(PE->getExpr(i));
4107
4108 // FIXME: This means that pretty-printing the final AST will produce curly
4109 // braces instead of the original commas.
4110 Op.release();
Ted Kremenekac034612010-04-13 23:39:13 +00004111 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
4112 &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00004113 initExprs.size(), RParenLoc);
4114 E->setType(Ty);
John McCalle15bbff2010-01-18 19:35:47 +00004115 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, Owned(E));
Nate Begeman5ec4b312009-08-10 23:49:36 +00004116 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004117 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00004118 // sequence of BinOp comma operators.
4119 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
John McCalle15bbff2010-01-18 19:35:47 +00004120 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, move(Op));
Nate Begeman5ec4b312009-08-10 23:49:36 +00004121 }
4122}
4123
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004124Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00004125 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004126 MultiExprArg Val,
4127 TypeTy *TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004128 unsigned nexprs = Val.size();
4129 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004130 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4131 Expr *expr;
4132 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4133 expr = new (Context) ParenExpr(L, R, exprs[0]);
4134 else
4135 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004136 return Owned(expr);
4137}
4138
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004139/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4140/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004141/// C99 6.5.15
4142QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
4143 SourceLocation QuestionLoc) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004144 // C++ is sufficiently different to merit its own checker.
4145 if (getLangOptions().CPlusPlus)
4146 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
4147
Chris Lattner432cff52009-02-18 04:28:32 +00004148 UsualUnaryConversions(Cond);
4149 UsualUnaryConversions(LHS);
4150 UsualUnaryConversions(RHS);
4151 QualType CondTy = Cond->getType();
4152 QualType LHSTy = LHS->getType();
4153 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004154
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004155 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004156 if (!CondTy->isScalarType()) { // C99 6.5.15p2
4157 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4158 << CondTy;
4159 return QualType();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004160 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004161
Chris Lattnere2949f42008-01-06 22:42:25 +00004162 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004163 if (LHSTy->isVectorType() || RHSTy->isVectorType())
4164 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00004165
Chris Lattnere2949f42008-01-06 22:42:25 +00004166 // If both operands have arithmetic type, do the usual arithmetic conversions
4167 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004168 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4169 UsualArithmeticConversions(LHS, RHS);
4170 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004171 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004172
Chris Lattnere2949f42008-01-06 22:42:25 +00004173 // If both operands are the same structure or union type, the result is that
4174 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004175 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4176 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004177 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004178 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004179 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004180 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004181 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004182 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004183
Chris Lattnere2949f42008-01-06 22:42:25 +00004184 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004185 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004186 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4187 if (!LHSTy->isVoidType())
4188 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4189 << RHS->getSourceRange();
4190 if (!RHSTy->isVoidType())
4191 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4192 << LHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004193 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
4194 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00004195 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00004196 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00004197 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4198 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00004199 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004200 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004201 // promote the null to a pointer.
4202 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00004203 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004204 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004205 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004206 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004207 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00004208 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004209 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004210
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004211 // All objective-c pointer type analysis is done here.
4212 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4213 QuestionLoc);
4214 if (!compositeType.isNull())
4215 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004216
4217
Steve Naroff05efa972009-07-01 14:36:47 +00004218 // Handle block pointer types.
4219 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4220 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4221 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4222 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004223 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4224 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004225 return destType;
4226 }
4227 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004228 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004229 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00004230 }
Steve Naroff05efa972009-07-01 14:36:47 +00004231 // We have 2 block pointer types.
4232 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4233 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00004234 return LHSTy;
4235 }
Steve Naroff05efa972009-07-01 14:36:47 +00004236 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004237 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4238 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004239
Steve Naroff05efa972009-07-01 14:36:47 +00004240 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4241 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00004242 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004243 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00004244 // In this situation, we assume void* type. No especially good
4245 // reason, but this is what gcc does, and we do have to pick
4246 // to get a consistent AST.
4247 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004248 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4249 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00004250 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004251 }
Steve Naroff05efa972009-07-01 14:36:47 +00004252 // The block pointer types are compatible.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004253 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4254 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00004255 return LHSTy;
4256 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004257
Steve Naroff05efa972009-07-01 14:36:47 +00004258 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4259 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4260 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004261 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4262 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00004263
4264 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4265 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4266 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00004267 QualType destPointee
4268 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004269 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004270 // Add qualifiers if necessary.
4271 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4272 // Promote to void*.
4273 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004274 return destType;
4275 }
4276 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004277 QualType destPointee
4278 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004279 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004280 // Add qualifiers if necessary.
Eli Friedmanb0bc5592009-11-17 01:22:05 +00004281 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004282 // Promote to void*.
Eli Friedmanb0bc5592009-11-17 01:22:05 +00004283 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004284 return destType;
4285 }
4286
4287 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4288 // Two identical pointer types are always compatible.
4289 return LHSTy;
4290 }
4291 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4292 rhptee.getUnqualifiedType())) {
4293 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4294 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4295 // In this situation, we assume void* type. No especially good
4296 // reason, but this is what gcc does, and we do have to pick
4297 // to get a consistent AST.
4298 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004299 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4300 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004301 return incompatTy;
4302 }
4303 // The pointer types are compatible.
4304 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4305 // differently qualified versions of compatible types, the result type is
4306 // a pointer to an appropriately qualified version of the *composite*
4307 // type.
4308 // FIXME: Need to calculate the composite type.
4309 // FIXME: Need to add qualifiers
Eli Friedman06ed2a52009-10-20 08:27:19 +00004310 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4311 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004312 return LHSTy;
4313 }
Mike Stump11289f42009-09-09 15:08:12 +00004314
Steve Naroff05efa972009-07-01 14:36:47 +00004315 // GCC compatibility: soften pointer/integer mismatch.
4316 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4317 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4318 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004319 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004320 return RHSTy;
4321 }
4322 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4323 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4324 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004325 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004326 return LHSTy;
4327 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00004328
Chris Lattnere2949f42008-01-06 22:42:25 +00004329 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004330 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4331 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004332 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004333}
4334
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004335/// FindCompositeObjCPointerType - Helper method to find composite type of
4336/// two objective-c pointer types of the two input expressions.
4337QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4338 SourceLocation QuestionLoc) {
4339 QualType LHSTy = LHS->getType();
4340 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004341
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004342 // Handle things like Class and struct objc_class*. Here we case the result
4343 // to the pseudo-builtin, because that will be implicitly cast back to the
4344 // redefinition type if an attempt is made to access its fields.
4345 if (LHSTy->isObjCClassType() &&
4346 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4347 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4348 return LHSTy;
4349 }
4350 if (RHSTy->isObjCClassType() &&
4351 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4352 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4353 return RHSTy;
4354 }
4355 // And the same for struct objc_object* / id
4356 if (LHSTy->isObjCIdType() &&
4357 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4358 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4359 return LHSTy;
4360 }
4361 if (RHSTy->isObjCIdType() &&
4362 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4363 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4364 return RHSTy;
4365 }
4366 // And the same for struct objc_selector* / SEL
4367 if (Context.isObjCSelType(LHSTy) &&
4368 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4369 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4370 return LHSTy;
4371 }
4372 if (Context.isObjCSelType(RHSTy) &&
4373 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4374 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4375 return RHSTy;
4376 }
4377 // Check constraints for Objective-C object pointers types.
4378 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004379
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004380 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4381 // Two identical object pointer types are always compatible.
4382 return LHSTy;
4383 }
4384 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4385 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4386 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004387
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004388 // If both operands are interfaces and either operand can be
4389 // assigned to the other, use that type as the composite
4390 // type. This allows
4391 // xxx ? (A*) a : (B*) b
4392 // where B is a subclass of A.
4393 //
4394 // Additionally, as for assignment, if either type is 'id'
4395 // allow silent coercion. Finally, if the types are
4396 // incompatible then make sure to use 'id' as the composite
4397 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004398
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004399 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4400 // It could return the composite type.
4401 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4402 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4403 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4404 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4405 } else if ((LHSTy->isObjCQualifiedIdType() ||
4406 RHSTy->isObjCQualifiedIdType()) &&
4407 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4408 // Need to handle "id<xx>" explicitly.
4409 // GCC allows qualified id and any Objective-C type to devolve to
4410 // id. Currently localizing to here until clear this should be
4411 // part of ObjCQualifiedIdTypesAreCompatible.
4412 compositeType = Context.getObjCIdType();
4413 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4414 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004415 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004416 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4417 ;
4418 else {
4419 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4420 << LHSTy << RHSTy
4421 << LHS->getSourceRange() << RHS->getSourceRange();
4422 QualType incompatTy = Context.getObjCIdType();
4423 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4424 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4425 return incompatTy;
4426 }
4427 // The object pointer types are compatible.
4428 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4429 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
4430 return compositeType;
4431 }
4432 // Check Objective-C object pointer types and 'void *'
4433 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4434 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4435 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4436 QualType destPointee
4437 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4438 QualType destType = Context.getPointerType(destPointee);
4439 // Add qualifiers if necessary.
4440 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4441 // Promote to void*.
4442 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4443 return destType;
4444 }
4445 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4446 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4447 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4448 QualType destPointee
4449 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4450 QualType destType = Context.getPointerType(destPointee);
4451 // Add qualifiers if necessary.
4452 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4453 // Promote to void*.
4454 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4455 return destType;
4456 }
4457 return QualType();
4458}
4459
Steve Naroff83895f72007-09-16 03:34:24 +00004460/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004461/// in the case of a the GNU conditional expr extension.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004462Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4463 SourceLocation ColonLoc,
4464 ExprArg Cond, ExprArg LHS,
4465 ExprArg RHS) {
4466 Expr *CondExpr = (Expr *) Cond.get();
4467 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner2ab40a62007-11-26 01:40:58 +00004468
4469 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4470 // was the condition.
4471 bool isLHSNull = LHSExpr == 0;
4472 if (isLHSNull)
4473 LHSExpr = CondExpr;
Sebastian Redlb5d49352009-01-19 22:31:54 +00004474
4475 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattnerdaaa9f22007-07-16 21:39:03 +00004476 RHSExpr, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00004477 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004478 return ExprError();
4479
4480 Cond.release();
4481 LHS.release();
4482 RHS.release();
Douglas Gregor7e112b02009-08-26 14:37:04 +00004483 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Narofff6009ed2009-01-21 00:14:39 +00004484 isLHSNull ? 0 : LHSExpr,
Douglas Gregor7e112b02009-08-26 14:37:04 +00004485 ColonLoc, RHSExpr, result));
Chris Lattnere168f762006-11-10 05:29:30 +00004486}
4487
Steve Naroff3f597292007-05-11 22:18:03 +00004488// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00004489// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00004490// routine is it effectively iqnores the qualifiers on the top level pointee.
4491// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4492// FIXME: add a couple examples in this comment.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004493Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00004494Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Steve Naroff3f597292007-05-11 22:18:03 +00004495 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004496
David Chisnall9f57c292009-08-17 16:35:33 +00004497 if ((lhsType->isObjCClassType() &&
4498 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4499 (rhsType->isObjCClassType() &&
4500 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4501 return Compatible;
4502 }
4503
Steve Naroff1f4d7272007-05-11 04:00:31 +00004504 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004505 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4506 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004507
Steve Naroff1f4d7272007-05-11 04:00:31 +00004508 // make sure we operate on the canonical type
Chris Lattner574dee62008-07-26 22:17:49 +00004509 lhptee = Context.getCanonicalType(lhptee);
4510 rhptee = Context.getCanonicalType(rhptee);
Steve Naroff1f4d7272007-05-11 04:00:31 +00004511
Chris Lattner9bad62c2008-01-04 18:04:52 +00004512 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004513
4514 // C99 6.5.16.1p1: This following citation is common to constraints
4515 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4516 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianece85822009-02-17 18:27:45 +00004517 // FIXME: Handle ExtQualType
Douglas Gregor9a657932008-10-21 23:43:52 +00004518 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner9bad62c2008-01-04 18:04:52 +00004519 ConvTy = CompatiblePointerDiscardsQualifiers;
Steve Naroff3f597292007-05-11 22:18:03 +00004520
Mike Stump4e1f26a2009-02-19 03:04:26 +00004521 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4522 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00004523 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00004524 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004525 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004526 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004527
Chris Lattner0a788432008-01-03 22:56:36 +00004528 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004529 assert(rhptee->isFunctionType());
4530 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004531 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004532
Chris Lattner0a788432008-01-03 22:56:36 +00004533 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004534 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004535 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00004536
4537 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004538 assert(lhptee->isFunctionType());
4539 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004540 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004541 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00004542 // unqualified versions of compatible types, ...
Eli Friedman80160bd2009-03-22 23:59:44 +00004543 lhptee = lhptee.getUnqualifiedType();
4544 rhptee = rhptee.getUnqualifiedType();
4545 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4546 // Check if the pointee types are compatible ignoring the sign.
4547 // We explicitly check for char so that we catch "char" vs
4548 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00004549 if (lhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004550 lhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00004551 else if (lhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004552 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004553
Chris Lattnerec3a1562009-10-17 20:33:28 +00004554 if (rhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004555 rhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00004556 else if (rhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004557 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00004558
Eli Friedman80160bd2009-03-22 23:59:44 +00004559 if (lhptee == rhptee) {
4560 // Types are compatible ignoring the sign. Qualifier incompatibility
4561 // takes priority over sign incompatibility because the sign
4562 // warning can be disabled.
4563 if (ConvTy != Compatible)
4564 return ConvTy;
4565 return IncompatiblePointerSign;
4566 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004567
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004568 // If we are a multi-level pointer, it's possible that our issue is simply
4569 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4570 // the eventual target type is the same and the pointers have the same
4571 // level of indirection, this must be the issue.
4572 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4573 do {
4574 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4575 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004576
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004577 lhptee = Context.getCanonicalType(lhptee);
4578 rhptee = Context.getCanonicalType(rhptee);
4579 } while (lhptee->isPointerType() && rhptee->isPointerType());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004580
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004581 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Alexis Hunt6f3de502009-11-08 07:46:34 +00004582 return IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004583 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004584
Eli Friedman80160bd2009-03-22 23:59:44 +00004585 // General pointer incompatibility takes priority over qualifiers.
Mike Stump11289f42009-09-09 15:08:12 +00004586 return IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00004587 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00004588 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00004589}
4590
Steve Naroff081c7422008-09-04 15:10:53 +00004591/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4592/// block pointer types are compatible or whether a block and normal pointer
4593/// are compatible. It is more restrict than comparing two function pointer
4594// types.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004595Sema::AssignConvertType
4596Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff081c7422008-09-04 15:10:53 +00004597 QualType rhsType) {
4598 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004599
Steve Naroff081c7422008-09-04 15:10:53 +00004600 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004601 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4602 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004603
Steve Naroff081c7422008-09-04 15:10:53 +00004604 // make sure we operate on the canonical type
4605 lhptee = Context.getCanonicalType(lhptee);
4606 rhptee = Context.getCanonicalType(rhptee);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004607
Steve Naroff081c7422008-09-04 15:10:53 +00004608 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004609
Steve Naroff081c7422008-09-04 15:10:53 +00004610 // For blocks we enforce that qualifiers are identical.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004611 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff081c7422008-09-04 15:10:53 +00004612 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004613
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004614 if (!getLangOptions().CPlusPlus) {
4615 if (!Context.typesAreBlockPointerCompatible(lhsType, rhsType))
4616 return IncompatibleBlockPointer;
4617 }
4618 else if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump4e1f26a2009-02-19 03:04:26 +00004619 return IncompatibleBlockPointer;
Steve Naroff081c7422008-09-04 15:10:53 +00004620 return ConvTy;
4621}
4622
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004623/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4624/// for assignment compatibility.
4625Sema::AssignConvertType
4626Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00004627 if (lhsType->isObjCBuiltinType()) {
4628 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00004629 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
4630 !rhsType->isObjCQualifiedClassType())
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00004631 return IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004632 return Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00004633 }
4634 if (rhsType->isObjCBuiltinType()) {
4635 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00004636 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
4637 !lhsType->isObjCQualifiedClassType())
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00004638 return IncompatiblePointer;
4639 return Compatible;
4640 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004641 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004642 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004643 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004644 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4645 // make sure we operate on the canonical type
4646 lhptee = Context.getCanonicalType(lhptee);
4647 rhptee = Context.getCanonicalType(rhptee);
4648 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4649 return CompatiblePointerDiscardsQualifiers;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004650
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004651 if (Context.typesAreCompatible(lhsType, rhsType))
4652 return Compatible;
4653 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4654 return IncompatibleObjCQualifiedId;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004655 return IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004656}
4657
Mike Stump4e1f26a2009-02-19 03:04:26 +00004658/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4659/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00004660/// pointers. Here are some objectionable examples that GCC considers warnings:
4661///
4662/// int a, *pint;
4663/// short *pshort;
4664/// struct foo *pfoo;
4665///
4666/// pint = pshort; // warning: assignment from incompatible pointer type
4667/// a = pint; // warning: assignment makes integer from pointer without a cast
4668/// pint = a; // warning: assignment makes pointer from integer without a cast
4669/// pint = pfoo; // warning: assignment from incompatible pointer type
4670///
4671/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00004672/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00004673///
Chris Lattner9bad62c2008-01-04 18:04:52 +00004674Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00004675Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnera52c2f22008-01-04 23:18:45 +00004676 // Get canonical types. We're not formatting these types, just comparing
4677 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00004678 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4679 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00004680
4681 if (lhsType == rhsType)
Chris Lattnerf5c973d2008-01-07 17:51:46 +00004682 return Compatible; // Common case: fast path an exact match.
Steve Naroff44fd8ff2007-07-24 21:46:40 +00004683
David Chisnall9f57c292009-08-17 16:35:33 +00004684 if ((lhsType->isObjCClassType() &&
4685 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4686 (rhsType->isObjCClassType() &&
4687 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4688 return Compatible;
4689 }
4690
Douglas Gregor6b754842008-10-28 00:22:11 +00004691 // If the left-hand side is a reference type, then we are in a
4692 // (rare!) case where we've allowed the use of references in C,
4693 // e.g., as a parameter type in a built-in function. In this case,
4694 // just make sure that the type referenced is compatible with the
4695 // right-hand side type. The caller is responsible for adjusting
4696 // lhsType so that the resulting expression does not have reference
4697 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004698 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor6b754842008-10-28 00:22:11 +00004699 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson24ebce62007-10-12 23:56:29 +00004700 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004701 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00004702 }
Nate Begemanbd956c42009-06-28 02:36:38 +00004703 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4704 // to the same ExtVector type.
4705 if (lhsType->isExtVectorType()) {
4706 if (rhsType->isExtVectorType())
4707 return lhsType == rhsType ? Compatible : Incompatible;
Douglas Gregora3208f92010-06-22 23:41:02 +00004708 if (rhsType->isArithmeticType())
Nate Begemanbd956c42009-06-28 02:36:38 +00004709 return Compatible;
4710 }
Mike Stump11289f42009-09-09 15:08:12 +00004711
Nate Begeman191a6b12008-07-14 18:02:46 +00004712 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004713 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump4e1f26a2009-02-19 03:04:26 +00004714 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begeman191a6b12008-07-14 18:02:46 +00004715 // no bits are changed but the result type is different.
Chris Lattner881a2122008-01-04 23:32:24 +00004716 if (getLangOptions().LaxVectorConversions &&
4717 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004718 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004719 return IncompatibleVectors;
Chris Lattner881a2122008-01-04 23:32:24 +00004720 }
4721 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004722 }
Eli Friedman3360d892008-05-30 18:07:22 +00004723
Douglas Gregorbea453a2010-05-23 21:53:47 +00004724 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
4725 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType()))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004726 return Compatible;
Eli Friedman3360d892008-05-30 18:07:22 +00004727
Chris Lattnerec646832008-04-07 06:49:41 +00004728 if (isa<PointerType>(lhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00004729 if (rhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00004730 return IntToPointer;
Eli Friedman3360d892008-05-30 18:07:22 +00004731
Chris Lattnerec646832008-04-07 06:49:41 +00004732 if (isa<PointerType>(rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004733 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004734
Steve Naroffaccc4882009-07-20 17:56:53 +00004735 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004736 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004737 if (lhsType->isVoidPointerType()) // an exception to the rule.
4738 return Compatible;
4739 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004740 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004741 if (rhsType->getAs<BlockPointerType>()) {
4742 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004743 return Compatible;
Steve Naroff32d072c2008-09-29 18:10:17 +00004744
4745 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004746 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00004747 return Compatible;
4748 }
Steve Naroff081c7422008-09-04 15:10:53 +00004749 return Incompatible;
4750 }
4751
4752 if (isa<BlockPointerType>(lhsType)) {
4753 if (rhsType->isIntegerType())
Eli Friedman8163b7a2009-02-25 04:20:42 +00004754 return IntToBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004755
Steve Naroff32d072c2008-09-29 18:10:17 +00004756 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004757 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00004758 return Compatible;
4759
Steve Naroff081c7422008-09-04 15:10:53 +00004760 if (rhsType->isBlockPointerType())
4761 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004762
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004763 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff081c7422008-09-04 15:10:53 +00004764 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004765 return Compatible;
Steve Naroff081c7422008-09-04 15:10:53 +00004766 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00004767 return Incompatible;
4768 }
4769
Steve Naroff7cae42b2009-07-10 23:34:53 +00004770 if (isa<ObjCObjectPointerType>(lhsType)) {
4771 if (rhsType->isIntegerType())
4772 return IntToPointer;
Mike Stump11289f42009-09-09 15:08:12 +00004773
Steve Naroffaccc4882009-07-20 17:56:53 +00004774 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004775 if (isa<PointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004776 if (rhsType->isVoidPointerType()) // an exception to the rule.
4777 return Compatible;
4778 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004779 }
4780 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00004781 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004782 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004783 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004784 if (RHSPT->getPointeeType()->isVoidType())
4785 return Compatible;
4786 }
4787 // Treat block pointers as objects.
4788 if (rhsType->isBlockPointerType())
4789 return Compatible;
4790 return Incompatible;
4791 }
Chris Lattnerec646832008-04-07 06:49:41 +00004792 if (isa<PointerType>(rhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00004793 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman3360d892008-05-30 18:07:22 +00004794 if (lhsType == Context.BoolTy)
4795 return Compatible;
4796
4797 if (lhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00004798 return PointerToInt;
Steve Naroff98cf3e92007-06-06 18:38:38 +00004799
Mike Stump4e1f26a2009-02-19 03:04:26 +00004800 if (isa<PointerType>(lhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004801 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004802
4803 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004804 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004805 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004806 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004807 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004808 if (isa<ObjCObjectPointerType>(rhsType)) {
4809 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4810 if (lhsType == Context.BoolTy)
4811 return Compatible;
4812
4813 if (lhsType->isIntegerType())
4814 return PointerToInt;
4815
Steve Naroffaccc4882009-07-20 17:56:53 +00004816 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004817 if (isa<PointerType>(lhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004818 if (lhsType->isVoidPointerType()) // an exception to the rule.
4819 return Compatible;
4820 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004821 }
4822 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004823 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004824 return Compatible;
4825 return Incompatible;
4826 }
Eli Friedman3360d892008-05-30 18:07:22 +00004827
Chris Lattnera52c2f22008-01-04 23:18:45 +00004828 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattnerec646832008-04-07 06:49:41 +00004829 if (Context.typesAreCompatible(lhsType, rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004830 return Compatible;
Bill Wendling216423b2007-05-30 06:30:29 +00004831 }
Steve Naroff98cf3e92007-06-06 18:38:38 +00004832 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00004833}
4834
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004835/// \brief Constructs a transparent union from an expression that is
4836/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00004837static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004838 QualType UnionType, FieldDecl *Field) {
4839 // Build an initializer list that designates the appropriate member
4840 // of the transparent union.
Ted Kremenekac034612010-04-13 23:39:13 +00004841 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00004842 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004843 SourceLocation());
4844 Initializer->setType(UnionType);
4845 Initializer->setInitializedFieldInUnion(Field);
4846
4847 // Build a compound literal constructing a value of the transparent
4848 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00004849 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall5d7aa7f2010-01-19 22:33:45 +00004850 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCalle15bbff2010-01-18 19:35:47 +00004851 Initializer, false);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004852}
4853
4854Sema::AssignConvertType
4855Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4856 QualType FromType = rExpr->getType();
4857
Mike Stump11289f42009-09-09 15:08:12 +00004858 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004859 // transparent_union GCC extension.
4860 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004861 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004862 return Incompatible;
4863
4864 // The field to initialize within the transparent union.
4865 RecordDecl *UD = UT->getDecl();
4866 FieldDecl *InitField = 0;
4867 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004868 for (RecordDecl::field_iterator it = UD->field_begin(),
4869 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004870 it != itend; ++it) {
4871 if (it->getType()->isPointerType()) {
4872 // If the transparent union contains a pointer type, we allow:
4873 // 1) void pointer
4874 // 2) null pointer constant
4875 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004876 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004877 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004878 InitField = *it;
4879 break;
4880 }
Mike Stump11289f42009-09-09 15:08:12 +00004881
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004882 if (rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00004883 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004884 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004885 InitField = *it;
4886 break;
4887 }
4888 }
4889
4890 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4891 == Compatible) {
4892 InitField = *it;
4893 break;
4894 }
4895 }
4896
4897 if (!InitField)
4898 return Incompatible;
4899
4900 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4901 return Compatible;
4902}
4903
Chris Lattner9bad62c2008-01-04 18:04:52 +00004904Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004905Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00004906 if (getLangOptions().CPlusPlus) {
4907 if (!lhsType->isRecordType()) {
4908 // C++ 5.17p3: If the left operand is not of class type, the
4909 // expression is implicitly converted (C++ 4) to the
4910 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00004911 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00004912 AA_Assigning))
Douglas Gregor9a657932008-10-21 23:43:52 +00004913 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00004914 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00004915 }
4916
4917 // FIXME: Currently, we fall through and treat C++ classes like C
4918 // structures.
4919 }
4920
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004921 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4922 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00004923 if ((lhsType->isPointerType() ||
4924 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00004925 lhsType->isBlockPointerType())
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004926 && rExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00004927 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004928 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004929 return Compatible;
4930 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004931
Chris Lattnere6dcd502007-10-16 02:55:40 +00004932 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004933 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00004934 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004935 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00004936 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00004937 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00004938 if (!lhsType->isReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +00004939 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004940
Chris Lattner9bad62c2008-01-04 18:04:52 +00004941 Sema::AssignConvertType result =
4942 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00004943
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004944 // C99 6.5.16.1p2: The value of the right operand is converted to the
4945 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00004946 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4947 // so that we can use references in built-in functions even in C.
4948 // The getNonReferenceType() call makes sure that the resulting expression
4949 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004950 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregora8a089b2010-07-13 18:40:04 +00004951 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context),
Eli Friedman06ed2a52009-10-20 08:27:19 +00004952 CastExpr::CK_Unknown);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004953 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004954}
4955
Chris Lattner326f7572008-11-18 01:30:42 +00004956QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00004957 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00004958 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004959 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00004960 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00004961}
4962
Chris Lattnerfaa54172010-01-12 21:23:57 +00004963QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00004964 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004965 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00004966 QualType lhsType =
4967 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4968 QualType rhsType =
4969 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004970
Nate Begeman191a6b12008-07-14 18:02:46 +00004971 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004972 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00004973 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00004974
Nate Begeman191a6b12008-07-14 18:02:46 +00004975 // Handle the case of a vector & extvector type of the same size and element
4976 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004977 if (getLangOptions().LaxVectorConversions) {
4978 // FIXME: Should we warn here?
John McCall9dd450b2009-09-21 23:43:11 +00004979 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4980 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begeman191a6b12008-07-14 18:02:46 +00004981 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004982 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004983 if (lhsType->isExtVectorType()) {
4984 ImpCastExprToType(rex, lhsType, CastExpr::CK_BitCast);
4985 return lhsType;
4986 }
4987
4988 ImpCastExprToType(lex, rhsType, CastExpr::CK_BitCast);
4989 return rhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004990 }
4991 }
4992 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004993
Nate Begemanbd956c42009-06-28 02:36:38 +00004994 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4995 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4996 bool swapped = false;
4997 if (rhsType->isExtVectorType()) {
4998 swapped = true;
4999 std::swap(rex, lex);
5000 std::swap(rhsType, lhsType);
5001 }
Mike Stump11289f42009-09-09 15:08:12 +00005002
Nate Begeman886448d2009-06-28 19:12:57 +00005003 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00005004 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005005 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005006 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005007 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005008 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00005009 if (swapped) std::swap(rex, lex);
5010 return lhsType;
5011 }
5012 }
5013 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5014 rhsType->isRealFloatingType()) {
5015 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005016 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00005017 if (swapped) std::swap(rex, lex);
5018 return lhsType;
5019 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005020 }
5021 }
Mike Stump11289f42009-09-09 15:08:12 +00005022
Nate Begeman886448d2009-06-28 19:12:57 +00005023 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00005024 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005025 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00005026 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005027 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005028}
5029
Chris Lattnerfaa54172010-01-12 21:23:57 +00005030QualType Sema::CheckMultiplyDivideOperands(
5031 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00005032 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005033 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005034
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005035 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005036
Chris Lattnerfaa54172010-01-12 21:23:57 +00005037 if (!lex->getType()->isArithmeticType() ||
5038 !rex->getType()->isArithmeticType())
5039 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005040
Chris Lattnerfaa54172010-01-12 21:23:57 +00005041 // Check for division by zero.
5042 if (isDiv &&
5043 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005044 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
Chris Lattner70117952010-01-12 21:30:55 +00005045 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005046
Chris Lattnerfaa54172010-01-12 21:23:57 +00005047 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005048}
5049
Chris Lattnerfaa54172010-01-12 21:23:57 +00005050QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00005051 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005052 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5053 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
5054 return CheckVectorOperands(Loc, lex, rex);
5055 return InvalidOperands(Loc, lex, rex);
5056 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005057
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005058 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005059
Chris Lattnerfaa54172010-01-12 21:23:57 +00005060 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
5061 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005062
Chris Lattnerfaa54172010-01-12 21:23:57 +00005063 // Check for remainder by zero.
5064 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattner70117952010-01-12 21:30:55 +00005065 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
5066 << rex->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005067
Chris Lattnerfaa54172010-01-12 21:23:57 +00005068 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005069}
5070
Chris Lattnerfaa54172010-01-12 21:23:57 +00005071QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00005072 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005073 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5074 QualType compType = CheckVectorOperands(Loc, lex, rex);
5075 if (CompLHSTy) *CompLHSTy = compType;
5076 return compType;
5077 }
Steve Naroff7a5af782007-07-13 16:58:59 +00005078
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005079 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00005080
Steve Naroffe4718892007-04-27 18:30:00 +00005081 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005082 if (lex->getType()->isArithmeticType() &&
5083 rex->getType()->isArithmeticType()) {
5084 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005085 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005086 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00005087
Eli Friedman8e122982008-05-18 18:08:51 +00005088 // Put any potential pointer into PExp
5089 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00005090 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00005091 std::swap(PExp, IExp);
5092
Steve Naroff6b712a72009-07-14 18:25:06 +00005093 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005094
Eli Friedman8e122982008-05-18 18:08:51 +00005095 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005096 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005097
Chris Lattner12bdebb2009-04-24 23:50:08 +00005098 // Check for arithmetic on pointers to incomplete types.
5099 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00005100 if (getLangOptions().CPlusPlus) {
5101 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00005102 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00005103 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00005104 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005105
5106 // GNU extension: arithmetic on pointer to void
5107 Diag(Loc, diag::ext_gnu_void_ptr)
5108 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00005109 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00005110 if (getLangOptions().CPlusPlus) {
5111 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
5112 << lex->getType() << lex->getSourceRange();
5113 return QualType();
5114 }
5115
5116 // GNU extension: arithmetic on pointer to function
5117 Diag(Loc, diag::ext_gnu_ptr_func_arith)
5118 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00005119 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005120 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00005121 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00005122 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005123 PExp->getType()->isObjCObjectPointerType()) &&
5124 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00005125 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5126 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005127 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005128 return QualType();
5129 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00005130 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00005131 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00005132 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5133 << PointeeTy << PExp->getSourceRange();
5134 return QualType();
5135 }
Mike Stump11289f42009-09-09 15:08:12 +00005136
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005137 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00005138 QualType LHSTy = Context.isPromotableBitField(lex);
5139 if (LHSTy.isNull()) {
5140 LHSTy = lex->getType();
5141 if (LHSTy->isPromotableIntegerType())
5142 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005143 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005144 *CompLHSTy = LHSTy;
5145 }
Eli Friedman8e122982008-05-18 18:08:51 +00005146 return PExp->getType();
5147 }
5148 }
5149
Chris Lattner326f7572008-11-18 01:30:42 +00005150 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005151}
5152
Chris Lattner2a3569b2008-04-07 05:30:13 +00005153// C99 6.5.6
5154QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005155 SourceLocation Loc, QualType* CompLHSTy) {
5156 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5157 QualType compType = CheckVectorOperands(Loc, lex, rex);
5158 if (CompLHSTy) *CompLHSTy = compType;
5159 return compType;
5160 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005161
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005162 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005163
Chris Lattner4d62f422007-12-09 21:53:25 +00005164 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005165
Chris Lattner4d62f422007-12-09 21:53:25 +00005166 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00005167 if (lex->getType()->isArithmeticType()
5168 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005169 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005170 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005171 }
Mike Stump11289f42009-09-09 15:08:12 +00005172
Chris Lattner4d62f422007-12-09 21:53:25 +00005173 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00005174 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00005175 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005176
Douglas Gregorac1fb652009-03-24 19:52:54 +00005177 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005178
Douglas Gregorac1fb652009-03-24 19:52:54 +00005179 bool ComplainAboutVoid = false;
5180 Expr *ComplainAboutFunc = 0;
5181 if (lpointee->isVoidType()) {
5182 if (getLangOptions().CPlusPlus) {
5183 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5184 << lex->getSourceRange() << rex->getSourceRange();
5185 return QualType();
5186 }
5187
5188 // GNU C extension: arithmetic on pointer to void
5189 ComplainAboutVoid = true;
5190 } else if (lpointee->isFunctionType()) {
5191 if (getLangOptions().CPlusPlus) {
5192 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005193 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00005194 return QualType();
5195 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005196
5197 // GNU C extension: arithmetic on pointer to function
5198 ComplainAboutFunc = lex;
5199 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00005200 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00005201 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00005202 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005203 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00005204 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005205
Chris Lattner12bdebb2009-04-24 23:50:08 +00005206 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00005207 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00005208 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5209 << lpointee << lex->getSourceRange();
5210 return QualType();
5211 }
Mike Stump11289f42009-09-09 15:08:12 +00005212
Chris Lattner4d62f422007-12-09 21:53:25 +00005213 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00005214 if (rex->getType()->isIntegerType()) {
5215 if (ComplainAboutVoid)
5216 Diag(Loc, diag::ext_gnu_void_ptr)
5217 << lex->getSourceRange() << rex->getSourceRange();
5218 if (ComplainAboutFunc)
5219 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00005220 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00005221 << ComplainAboutFunc->getSourceRange();
5222
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005223 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005224 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005225 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005226
Chris Lattner4d62f422007-12-09 21:53:25 +00005227 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005228 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00005229 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005230
Douglas Gregorac1fb652009-03-24 19:52:54 +00005231 // RHS must be a completely-type object type.
5232 // Handle the GNU void* extension.
5233 if (rpointee->isVoidType()) {
5234 if (getLangOptions().CPlusPlus) {
5235 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5236 << lex->getSourceRange() << rex->getSourceRange();
5237 return QualType();
5238 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005239
Douglas Gregorac1fb652009-03-24 19:52:54 +00005240 ComplainAboutVoid = true;
5241 } else if (rpointee->isFunctionType()) {
5242 if (getLangOptions().CPlusPlus) {
5243 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005244 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00005245 return QualType();
5246 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005247
5248 // GNU extension: arithmetic on pointer to function
5249 if (!ComplainAboutFunc)
5250 ComplainAboutFunc = rex;
5251 } else if (!rpointee->isDependentType() &&
5252 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00005253 PDiag(diag::err_typecheck_sub_ptr_object)
5254 << rex->getSourceRange()
5255 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00005256 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005257
Eli Friedman168fe152009-05-16 13:54:38 +00005258 if (getLangOptions().CPlusPlus) {
5259 // Pointee types must be the same: C++ [expr.add]
5260 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5261 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5262 << lex->getType() << rex->getType()
5263 << lex->getSourceRange() << rex->getSourceRange();
5264 return QualType();
5265 }
5266 } else {
5267 // Pointee types must be compatible C99 6.5.6p3
5268 if (!Context.typesAreCompatible(
5269 Context.getCanonicalType(lpointee).getUnqualifiedType(),
5270 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5271 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5272 << lex->getType() << rex->getType()
5273 << lex->getSourceRange() << rex->getSourceRange();
5274 return QualType();
5275 }
Chris Lattner4d62f422007-12-09 21:53:25 +00005276 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005277
Douglas Gregorac1fb652009-03-24 19:52:54 +00005278 if (ComplainAboutVoid)
5279 Diag(Loc, diag::ext_gnu_void_ptr)
5280 << lex->getSourceRange() << rex->getSourceRange();
5281 if (ComplainAboutFunc)
5282 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00005283 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00005284 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005285
5286 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00005287 return Context.getPointerDiffType();
5288 }
5289 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005290
Chris Lattner326f7572008-11-18 01:30:42 +00005291 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00005292}
5293
Chris Lattner2a3569b2008-04-07 05:30:13 +00005294// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00005295QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattner2a3569b2008-04-07 05:30:13 +00005296 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00005297 // C99 6.5.7p2: Each of the operands shall have integer type.
5298 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner326f7572008-11-18 01:30:42 +00005299 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005300
Nate Begemane46ee9a2009-10-25 02:26:48 +00005301 // Vector shifts promote their scalar inputs to vector type.
5302 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5303 return CheckVectorOperands(Loc, lex, rex);
5304
Chris Lattner5c11c412007-12-12 05:47:28 +00005305 // Shifts don't perform usual arithmetic conversions, they just do integer
5306 // promotions on each operand. C99 6.5.7p3
Eli Friedman629ffb92009-08-20 04:21:42 +00005307 QualType LHSTy = Context.isPromotableBitField(lex);
5308 if (LHSTy.isNull()) {
5309 LHSTy = lex->getType();
5310 if (LHSTy->isPromotableIntegerType())
5311 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005312 }
Chris Lattner3c133402007-12-13 07:28:16 +00005313 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +00005314 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005315
Chris Lattner5c11c412007-12-12 05:47:28 +00005316 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005317
Ryan Flynnf53fab82009-08-07 16:20:20 +00005318 // Sanity-check shift operands
5319 llvm::APSInt Right;
5320 // Check right/shifter operand
Daniel Dunbar687fa862009-09-17 06:31:27 +00005321 if (!rex->isValueDependent() &&
5322 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn2f085712009-08-08 19:18:23 +00005323 if (Right.isNegative())
Ryan Flynnf53fab82009-08-07 16:20:20 +00005324 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
5325 else {
5326 llvm::APInt LeftBits(Right.getBitWidth(),
5327 Context.getTypeSize(lex->getType()));
5328 if (Right.uge(LeftBits))
5329 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
5330 }
5331 }
5332
Chris Lattner5c11c412007-12-12 05:47:28 +00005333 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005334 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005335}
5336
Chandler Carruth17773fc2010-07-10 12:30:03 +00005337static bool IsWithinTemplateSpecialization(Decl *D) {
5338 if (DeclContext *DC = D->getDeclContext()) {
5339 if (isa<ClassTemplateSpecializationDecl>(DC))
5340 return true;
5341 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
5342 return FD->isFunctionTemplateSpecialization();
5343 }
5344 return false;
5345}
5346
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005347// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00005348QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005349 unsigned OpaqueOpc, bool isRelational) {
5350 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5351
Chris Lattner9a152e22009-12-05 05:40:13 +00005352 // Handle vector comparisons separately.
Nate Begeman191a6b12008-07-14 18:02:46 +00005353 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005354 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005355
Steve Naroff31090012007-07-16 21:54:35 +00005356 QualType lType = lex->getType();
5357 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005358
Douglas Gregor4ffbad12010-06-22 22:12:46 +00005359 if (!lType->hasFloatingRepresentation() &&
5360 !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00005361 // For non-floating point types, check for self-comparisons of the form
5362 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5363 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00005364 //
5365 // NOTE: Don't warn about comparison expressions resulting from macro
5366 // expansion. Also don't warn about comparisons which are only self
5367 // comparisons within a template specialization. The warnings should catch
5368 // obvious cases in the definition of the template anyways. The idea is to
5369 // warn when the typed comparison operator will always evaluate to the same
5370 // result.
Chris Lattner222b8bd2009-03-08 19:39:53 +00005371 Expr *LHSStripped = lex->IgnoreParens();
5372 Expr *RHSStripped = rex->IgnoreParens();
Chandler Carruth17773fc2010-07-10 12:30:03 +00005373 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00005374 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Chandler Carruth65a38182010-07-12 06:23:38 +00005375 if (DRL->getDecl() == DRR->getDecl() && !Loc.isMacroID() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00005376 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Douglas Gregorec170db2010-06-08 19:50:34 +00005377 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
5378 << 0 // self-
5379 << (Opc == BinaryOperator::EQ
5380 || Opc == BinaryOperator::LE
5381 || Opc == BinaryOperator::GE));
5382 } else if (lType->isArrayType() && rType->isArrayType() &&
5383 !DRL->getDecl()->getType()->isReferenceType() &&
5384 !DRR->getDecl()->getType()->isReferenceType()) {
5385 // what is it always going to eval to?
5386 char always_evals_to;
5387 switch(Opc) {
5388 case BinaryOperator::EQ: // e.g. array1 == array2
5389 always_evals_to = 0; // false
5390 break;
5391 case BinaryOperator::NE: // e.g. array1 != array2
5392 always_evals_to = 1; // true
5393 break;
5394 default:
5395 // best we can say is 'a constant'
5396 always_evals_to = 2; // e.g. array1 <= array2
5397 break;
5398 }
5399 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
5400 << 1 // array
5401 << always_evals_to);
5402 }
5403 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00005404 }
Mike Stump11289f42009-09-09 15:08:12 +00005405
Chris Lattner222b8bd2009-03-08 19:39:53 +00005406 if (isa<CastExpr>(LHSStripped))
5407 LHSStripped = LHSStripped->IgnoreParenCasts();
5408 if (isa<CastExpr>(RHSStripped))
5409 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005410
Chris Lattner222b8bd2009-03-08 19:39:53 +00005411 // Warn about comparisons against a string constant (unless the other
5412 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005413 Expr *literalString = 0;
5414 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00005415 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005416 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005417 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005418 literalString = lex;
5419 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00005420 } else if ((isa<StringLiteral>(RHSStripped) ||
5421 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005422 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005423 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005424 literalString = rex;
5425 literalStringStripped = RHSStripped;
5426 }
5427
5428 if (literalString) {
5429 std::string resultComparison;
5430 switch (Opc) {
5431 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5432 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5433 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5434 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5435 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5436 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5437 default: assert(false && "Invalid comparison operator");
5438 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005439
Douglas Gregor49862b82010-01-12 23:18:54 +00005440 DiagRuntimeBehavior(Loc,
5441 PDiag(diag::warn_stringcompare)
5442 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00005443 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005444 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00005445 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005446
Douglas Gregorec170db2010-06-08 19:50:34 +00005447 // C99 6.5.8p3 / C99 6.5.9p4
5448 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5449 UsualArithmeticConversions(lex, rex);
5450 else {
5451 UsualUnaryConversions(lex);
5452 UsualUnaryConversions(rex);
5453 }
5454
5455 lType = lex->getType();
5456 rType = rex->getType();
5457
Douglas Gregorca63811b2008-11-19 03:25:36 +00005458 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner9a152e22009-12-05 05:40:13 +00005459 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregorca63811b2008-11-19 03:25:36 +00005460
Chris Lattnerb620c342007-08-26 01:18:55 +00005461 if (isRelational) {
5462 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00005463 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00005464 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00005465 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00005466 if (lType->hasFloatingRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00005467 CheckFloatComparison(Loc,lex,rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005468
Chris Lattnerb620c342007-08-26 01:18:55 +00005469 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00005470 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00005471 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005472
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005473 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005474 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005475 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005476 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005477
Douglas Gregorf267edd2010-06-15 21:38:40 +00005478 // All of the following pointer-related warnings are GCC extensions, except
5479 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00005480 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00005481 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005482 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00005483 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005484 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00005485
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005486 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00005487 if (LCanPointeeTy == RCanPointeeTy)
5488 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00005489 if (!isRelational &&
5490 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5491 // Valid unless comparison between non-null pointer and function pointer
5492 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00005493 // In a SFINAE context, we treat this as a hard error to maintain
5494 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00005495 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5496 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00005497 Diag(Loc,
5498 isSFINAEContext()?
5499 diag::err_typecheck_comparison_of_fptr_to_void
5500 : diag::ext_typecheck_comparison_of_fptr_to_void)
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00005501 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00005502
5503 if (isSFINAEContext())
5504 return QualType();
5505
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00005506 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5507 return ResultTy;
5508 }
5509 }
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005510 // C++ [expr.rel]p2:
5511 // [...] Pointer conversions (4.10) and qualification
5512 // conversions (4.4) are performed on pointer operands (or on
5513 // a pointer operand and a null pointer constant) to bring
5514 // them to their composite pointer type. [...]
5515 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005516 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005517 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005518 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00005519 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005520 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005521 if (T.isNull()) {
5522 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5523 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5524 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005525 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005526 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005527 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005528 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005529 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005530 }
5531
Eli Friedman06ed2a52009-10-20 08:27:19 +00005532 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5533 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005534 return ResultTy;
5535 }
Eli Friedman16c209612009-08-23 00:27:47 +00005536 // C99 6.5.9p2 and C99 6.5.8p2
5537 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5538 RCanPointeeTy.getUnqualifiedType())) {
5539 // Valid unless a relational comparison of function pointers
5540 if (isRelational && LCanPointeeTy->isFunctionType()) {
5541 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5542 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5543 }
5544 } else if (!isRelational &&
5545 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5546 // Valid unless comparison between non-null pointer and function pointer
5547 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5548 && !LHSIsNull && !RHSIsNull) {
5549 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5550 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5551 }
5552 } else {
5553 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00005554 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005555 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00005556 }
Eli Friedman16c209612009-08-23 00:27:47 +00005557 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman06ed2a52009-10-20 08:27:19 +00005558 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005559 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00005560 }
Mike Stump11289f42009-09-09 15:08:12 +00005561
Sebastian Redl576fd422009-05-10 18:38:11 +00005562 if (getLangOptions().CPlusPlus) {
Mike Stump11289f42009-09-09 15:08:12 +00005563 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005564 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00005565 if (RHSIsNull &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005566 (lType->isPointerType() ||
5567 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00005568 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00005569 return ResultTy;
5570 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005571 if (LHSIsNull &&
5572 (rType->isPointerType() ||
5573 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00005574 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00005575 return ResultTy;
5576 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005577
5578 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00005579 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005580 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5581 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005582 // In addition, pointers to members can be compared, or a pointer to
5583 // member and a null pointer constant. Pointer to member conversions
5584 // (4.11) and qualification conversions (4.4) are performed to bring
5585 // them to a common type. If one operand is a null pointer constant,
5586 // the common type is the type of the other operand. Otherwise, the
5587 // common type is a pointer to member type similar (4.4) to the type
5588 // of one of the operands, with a cv-qualification signature (4.4)
5589 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005590 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005591 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00005592 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005593 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005594 if (T.isNull()) {
5595 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005596 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005597 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005598 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005599 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005600 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005601 << lType << rType << T
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005602 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005603 }
Mike Stump11289f42009-09-09 15:08:12 +00005604
Eli Friedman06ed2a52009-10-20 08:27:19 +00005605 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5606 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005607 return ResultTy;
5608 }
Mike Stump11289f42009-09-09 15:08:12 +00005609
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005610 // Comparison of nullptr_t with itself.
Sebastian Redl576fd422009-05-10 18:38:11 +00005611 if (lType->isNullPtrType() && rType->isNullPtrType())
5612 return ResultTy;
5613 }
Mike Stump11289f42009-09-09 15:08:12 +00005614
Steve Naroff081c7422008-09-04 15:10:53 +00005615 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00005616 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005617 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5618 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005619
Steve Naroff081c7422008-09-04 15:10:53 +00005620 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00005621 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005622 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005623 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00005624 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005625 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005626 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00005627 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00005628 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00005629 if (!isRelational
5630 && ((lType->isBlockPointerType() && rType->isPointerType())
5631 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00005632 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005633 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00005634 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005635 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00005636 ->getPointeeType()->isVoidType())))
5637 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5638 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00005639 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005640 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005641 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00005642 }
Steve Naroff081c7422008-09-04 15:10:53 +00005643
Steve Naroff7cae42b2009-07-10 23:34:53 +00005644 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00005645 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005646 const PointerType *LPT = lType->getAs<PointerType>();
5647 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005648 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00005649 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005650 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00005651 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005652
Steve Naroff753567f2008-11-17 19:49:16 +00005653 if (!LPtrToVoid && !RPtrToVoid &&
5654 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005655 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005656 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00005657 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005658 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005659 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00005660 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005661 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005662 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005663 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5664 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00005665 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005666 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00005667 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00005668 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00005669 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
5670 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00005671 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00005672 bool isError = false;
5673 if ((LHSIsNull && lType->isIntegerType()) ||
5674 (RHSIsNull && rType->isIntegerType())) {
5675 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00005676 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00005677 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00005678 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00005679 else if (getLangOptions().CPlusPlus) {
5680 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
5681 isError = true;
5682 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00005683 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00005684
Chris Lattnerd99bd522009-08-23 00:03:44 +00005685 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005686 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00005687 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00005688 if (isError)
5689 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00005690 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00005691
5692 if (lType->isIntegerType())
5693 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00005694 else
Douglas Gregorf267edd2010-06-15 21:38:40 +00005695 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005696 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00005697 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00005698
Steve Naroff4b191572008-09-04 16:56:14 +00005699 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00005700 if (!isRelational && RHSIsNull
5701 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005702 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005703 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00005704 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00005705 if (!isRelational && LHSIsNull
5706 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005707 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005708 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00005709 }
Chris Lattner326f7572008-11-18 01:30:42 +00005710 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005711}
5712
Nate Begeman191a6b12008-07-14 18:02:46 +00005713/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00005714/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00005715/// like a scalar comparison, a vector comparison produces a vector of integer
5716/// types.
5717QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00005718 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00005719 bool isRelational) {
5720 // Check to make sure we're operating on vectors of the same type and width,
5721 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00005722 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00005723 if (vType.isNull())
5724 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005725
Nate Begeman191a6b12008-07-14 18:02:46 +00005726 QualType lType = lex->getType();
5727 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005728
Nate Begeman191a6b12008-07-14 18:02:46 +00005729 // For non-floating point types, check for self-comparisons of the form
5730 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5731 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00005732 if (!lType->hasFloatingRepresentation()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00005733 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5734 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5735 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregorec170db2010-06-08 19:50:34 +00005736 DiagRuntimeBehavior(Loc,
5737 PDiag(diag::warn_comparison_always)
5738 << 0 // self-
5739 << 2 // "a constant"
5740 );
Nate Begeman191a6b12008-07-14 18:02:46 +00005741 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005742
Nate Begeman191a6b12008-07-14 18:02:46 +00005743 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00005744 if (!isRelational && lType->hasFloatingRepresentation()) {
5745 assert (rType->hasFloatingRepresentation());
Chris Lattner326f7572008-11-18 01:30:42 +00005746 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00005747 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005748
Nate Begeman191a6b12008-07-14 18:02:46 +00005749 // Return the type for the comparison, which is the same as vector type for
5750 // integer vectors, or an integer type of identical size and number of
5751 // elements for floating point vectors.
5752 if (lType->isIntegerType())
5753 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005754
John McCall9dd450b2009-09-21 23:43:11 +00005755 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00005756 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005757 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00005758 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00005759 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005760 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5761
Mike Stump4e1f26a2009-02-19 03:04:26 +00005762 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005763 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00005764 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5765}
5766
Steve Naroff218bc2b2007-05-04 21:54:46 +00005767inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00005768 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff94a5aca2007-07-16 22:23:01 +00005769 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005770 return CheckVectorOperands(Loc, lex, rex);
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005771
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005772 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005773
Steve Naroffdbd9e892007-07-17 00:58:39 +00005774 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005775 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00005776 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005777}
5778
Steve Naroff218bc2b2007-05-04 21:54:46 +00005779inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner8406c512010-07-13 19:41:32 +00005780 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
5781
5782 // Diagnose cases where the user write a logical and/or but probably meant a
5783 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
5784 // is a constant.
5785 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
5786 rex->getType()->isIntegerType() && rex->isEvaluatable(Context) &&
Chris Lattnerdeee7a32010-07-15 00:26:43 +00005787 // Don't warn if the RHS is a (constant folded) boolean expression like
5788 // "sizeof(int) == 4".
5789 !rex->isKnownToHaveBooleanValue() &&
5790 // Don't warn in macros.
Chris Lattner8406c512010-07-13 19:41:32 +00005791 !Loc.isMacroID())
5792 Diag(Loc, diag::warn_logical_instead_of_bitwise)
5793 << rex->getSourceRange()
5794 << (Opc == BinaryOperator::LAnd ? "&&" : "||")
5795 << (Opc == BinaryOperator::LAnd ? "&" : "|");
5796
5797
5798
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005799 if (!Context.getLangOptions().CPlusPlus) {
5800 UsualUnaryConversions(lex);
5801 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005802
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005803 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5804 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005805
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005806 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00005807 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005808
John McCall4a2429a2010-06-04 00:29:51 +00005809 // The following is safe because we only use this method for
5810 // non-overloadable operands.
5811
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005812 // C++ [expr.log.and]p1
5813 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00005814 // The operands are both contextually converted to type bool.
5815 if (PerformContextuallyConvertToBool(lex) ||
5816 PerformContextuallyConvertToBool(rex))
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005817 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005818
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005819 // C++ [expr.log.and]p2
5820 // C++ [expr.log.or]p2
5821 // The result is a bool.
5822 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00005823}
5824
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005825/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5826/// is a read-only property; return true if so. A readonly property expression
5827/// depends on various declarations and thus must be treated specially.
5828///
Mike Stump11289f42009-09-09 15:08:12 +00005829static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005830 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5831 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5832 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5833 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005834 if (const ObjCObjectPointerType *OPT =
Steve Naroff7cae42b2009-07-10 23:34:53 +00005835 BaseType->getAsObjCInterfacePointerType())
5836 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5837 if (S.isPropertyReadonly(PDecl, IFace))
5838 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005839 }
5840 }
5841 return false;
5842}
5843
Chris Lattner30bd3272008-11-18 01:22:49 +00005844/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5845/// emit an error and return true. If so, return false.
5846static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005847 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00005848 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005849 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005850 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5851 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00005852 if (IsLV == Expr::MLV_Valid)
5853 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005854
Chris Lattner30bd3272008-11-18 01:22:49 +00005855 unsigned Diag = 0;
5856 bool NeedType = false;
5857 switch (IsLV) { // C99 6.5.16p2
Chris Lattner30bd3272008-11-18 01:22:49 +00005858 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005859 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00005860 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5861 NeedType = true;
5862 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005863 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00005864 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5865 NeedType = true;
5866 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00005867 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00005868 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5869 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00005870 case Expr::MLV_Valid:
5871 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00005872 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00005873 case Expr::MLV_MemberFunction:
5874 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00005875 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5876 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005877 case Expr::MLV_IncompleteType:
5878 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00005879 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00005880 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00005881 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00005882 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00005883 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5884 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00005885 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00005886 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5887 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00005888 case Expr::MLV_ReadonlyProperty:
5889 Diag = diag::error_readonly_property_assignment;
5890 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00005891 case Expr::MLV_NoSetterProperty:
5892 Diag = diag::error_nosetter_property_assignment;
5893 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00005894 case Expr::MLV_SubObjCPropertySetting:
5895 Diag = diag::error_no_subobject_property_setting;
5896 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005897 }
Steve Naroffad373bd2007-07-31 12:34:36 +00005898
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005899 SourceRange Assign;
5900 if (Loc != OrigLoc)
5901 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00005902 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005903 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00005904 else
Mike Stump11289f42009-09-09 15:08:12 +00005905 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00005906 return true;
5907}
5908
5909
5910
5911// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00005912QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5913 SourceLocation Loc,
5914 QualType CompoundType) {
5915 // Verify that LHS is a modifiable lvalue, and emit error if not.
5916 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00005917 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00005918
5919 QualType LHSType = LHS->getType();
5920 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005921 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00005922 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00005923 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00005924 // Simple assignment "x = y".
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00005925 if (const ObjCImplicitSetterGetterRefExpr *OISGE =
5926 dyn_cast<ObjCImplicitSetterGetterRefExpr>(LHS)) {
5927 // If using property-dot syntax notation for assignment, and there is a
5928 // setter, RHS expression is being passed to the setter argument. So,
5929 // type conversion (and comparison) is RHS to setter's argument type.
5930 if (const ObjCMethodDecl *SetterMD = OISGE->getSetterMethod()) {
5931 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
5932 LHSTy = (*P)->getType();
5933 }
5934 }
5935
5936 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005937 // Special case of NSObject attributes on c-style pointer types.
5938 if (ConvTy == IncompatiblePointer &&
5939 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00005940 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005941 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00005942 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005943 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005944
Chris Lattnerea714382008-08-21 18:04:13 +00005945 // If the RHS is a unary plus or minus, check to see if they = and + are
5946 // right next to each other. If so, the user may have typo'd "x =+ 4"
5947 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00005948 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00005949 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5950 RHSCheck = ICE->getSubExpr();
5951 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5952 if ((UO->getOpcode() == UnaryOperator::Plus ||
5953 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00005954 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00005955 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00005956 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5957 // And there is a space or other character before the subexpr of the
5958 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00005959 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5960 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00005961 Diag(Loc, diag::warn_not_compound_assign)
5962 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5963 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00005964 }
Chris Lattnerea714382008-08-21 18:04:13 +00005965 }
5966 } else {
5967 // Compound assignment "x += y"
Eli Friedmanb05c41e2009-05-16 05:56:02 +00005968 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00005969 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005970
Chris Lattner326f7572008-11-18 01:30:42 +00005971 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00005972 RHS, AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00005973 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005974
Chris Lattner39561062010-07-07 06:14:23 +00005975
5976 // Check to see if the destination operand is a dereferenced null pointer. If
5977 // so, and if not volatile-qualified, this is undefined behavior that the
5978 // optimizer will delete, so warn about it. People sometimes try to use this
5979 // to get a deterministic trap and are surprised by clang's behavior. This
5980 // only handles the pattern "*null = whatever", which is a very syntactic
5981 // check.
5982 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
5983 if (UO->getOpcode() == UnaryOperator::Deref &&
5984 UO->getSubExpr()->IgnoreParenCasts()->
5985 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
5986 !UO->getType().isVolatileQualified()) {
5987 Diag(UO->getOperatorLoc(), diag::warn_indirection_through_null)
5988 << UO->getSubExpr()->getSourceRange();
5989 Diag(UO->getOperatorLoc(), diag::note_indirection_through_null);
5990 }
5991
Steve Naroff98cf3e92007-06-06 18:38:38 +00005992 // C99 6.5.16p3: The type of an assignment expression is the type of the
5993 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00005994 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00005995 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5996 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00005997 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00005998 // operand.
Chris Lattner326f7572008-11-18 01:30:42 +00005999 return LHSType.getUnqualifiedType();
Steve Naroffae4143e2007-04-26 20:39:23 +00006000}
6001
Chris Lattner326f7572008-11-18 01:30:42 +00006002// C99 6.5.17
6003QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00006004 DiagnoseUnusedExprResult(LHS);
6005
Chris Lattnerf6e1e302008-07-25 20:54:07 +00006006 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Douglas Gregorb92a1562010-02-03 00:27:59 +00006007 // C++ does not perform this conversion (C++ [expr.comma]p1).
6008 if (!getLangOptions().CPlusPlus)
6009 DefaultFunctionArrayLvalueConversion(RHS);
Eli Friedmanba961a92009-03-23 00:24:07 +00006010
6011 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
6012 // incomplete in C++).
6013
Chris Lattner326f7572008-11-18 01:30:42 +00006014 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00006015}
6016
Steve Naroff7a5af782007-07-13 16:58:59 +00006017/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
6018/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle10c2c32008-12-20 09:35:34 +00006019QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
Alexis Huntc46382e2010-04-28 23:02:27 +00006020 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006021 if (Op->isTypeDependent())
6022 return Context.DependentTy;
6023
Chris Lattner6b0cf142008-11-21 07:05:48 +00006024 QualType ResType = Op->getType();
6025 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00006026
Sebastian Redle10c2c32008-12-20 09:35:34 +00006027 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
6028 // Decrement of bool is not allowed.
6029 if (!isInc) {
6030 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
6031 return QualType();
6032 }
6033 // Increment of bool sets it to true, but is deprecated.
6034 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
6035 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00006036 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00006037 } else if (ResType->isAnyPointerType()) {
6038 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006039
Chris Lattner6b0cf142008-11-21 07:05:48 +00006040 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00006041 if (PointeeTy->isVoidType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006042 if (getLangOptions().CPlusPlus) {
6043 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
6044 << Op->getSourceRange();
6045 return QualType();
6046 }
6047
6048 // Pointer to void is a GNU extension in C.
Chris Lattner6b0cf142008-11-21 07:05:48 +00006049 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006050 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006051 if (getLangOptions().CPlusPlus) {
6052 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
6053 << Op->getType() << Op->getSourceRange();
6054 return QualType();
6055 }
6056
6057 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006058 << ResType << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006059 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlsson029fc692009-08-26 22:59:12 +00006060 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00006061 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006062 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00006063 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00006064 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006065 else if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Fariborz Jahanianca75db72009-07-16 17:59:14 +00006066 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6067 << PointeeTy << Op->getSourceRange();
6068 return QualType();
6069 }
Eli Friedman090addd2010-01-03 00:20:48 +00006070 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00006071 // C99 does not support ++/-- on complex types, we allow as an extension.
6072 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006073 << ResType << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00006074 } else {
6075 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00006076 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00006077 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00006078 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006079 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00006080 // Now make sure the operand is a modifiable lvalue.
Chris Lattner6b0cf142008-11-21 07:05:48 +00006081 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Steve Naroff35d85152007-05-07 00:24:15 +00006082 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00006083 // In C++, a prefix increment is the same type as the operand. Otherwise
6084 // (in C or with postfix), the increment is the unqualified type of the
6085 // operand.
6086 return isPrefix && getLangOptions().CPlusPlus
6087 ? ResType : ResType.getUnqualifiedType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00006088}
6089
Anders Carlsson806700f2008-02-01 07:15:58 +00006090/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00006091/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00006092/// where the declaration is needed for type checking. We only need to
6093/// handle cases when the expression references a function designator
6094/// or is an lvalue. Here are some examples:
6095/// - &(x) => x
6096/// - &*****f => f for f a function designator.
6097/// - &s.xx => s
6098/// - &s.zz[1].yy -> s, if zz is an array
6099/// - *(x + 1) -> x, if x is an array
6100/// - &"123"[2] -> 0
6101/// - & __real__ x -> x
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006102static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00006103 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00006104 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00006105 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00006106 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00006107 // If this is an arrow operator, the address is an offset from
6108 // the base's value, so the object the base refers to is
6109 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00006110 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00006111 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00006112 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00006113 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00006114 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00006115 // FIXME: This code shouldn't be necessary! We should catch the implicit
6116 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00006117 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
6118 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
6119 if (ICE->getSubExpr()->getType()->isArrayType())
6120 return getPrimaryDecl(ICE->getSubExpr());
6121 }
6122 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00006123 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00006124 case Stmt::UnaryOperatorClass: {
6125 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006126
Daniel Dunbarb692ef42008-08-04 20:02:37 +00006127 switch(UO->getOpcode()) {
Daniel Dunbarb692ef42008-08-04 20:02:37 +00006128 case UnaryOperator::Real:
6129 case UnaryOperator::Imag:
6130 case UnaryOperator::Extension:
6131 return getPrimaryDecl(UO->getSubExpr());
6132 default:
6133 return 0;
6134 }
6135 }
Steve Naroff47500512007-04-19 23:00:49 +00006136 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00006137 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00006138 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00006139 // If the result of an implicit cast is an l-value, we care about
6140 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00006141 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00006142 default:
6143 return 0;
6144 }
6145}
6146
6147/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00006148/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00006149/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006150/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00006151/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006152/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00006153/// we allow the '&' but retain the overloaded-function type.
Steve Naroff35d85152007-05-07 00:24:15 +00006154QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00006155 // Make sure to ignore parentheses in subsequent checks
6156 op = op->IgnoreParens();
6157
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00006158 if (op->isTypeDependent())
6159 return Context.DependentTy;
6160
Steve Naroff826e91a2008-01-13 17:10:08 +00006161 if (getLangOptions().C99) {
6162 // Implement C99-only parts of addressof rules.
6163 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
6164 if (uOp->getOpcode() == UnaryOperator::Deref)
6165 // Per C99 6.5.3.2, the address of a deref always returns a valid result
6166 // (assuming the deref expression is valid).
6167 return uOp->getSubExpr()->getType();
6168 }
6169 // Technically, there should be a check for array subscript
6170 // expressions here, but the result of one is always an lvalue anyway.
6171 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006172 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner67315442008-07-26 21:30:36 +00006173 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00006174
Sebastian Redl9a8dd0d2010-01-11 15:56:56 +00006175 MemberExpr *ME = dyn_cast<MemberExpr>(op);
6176 if (lval == Expr::LV_MemberFunction && ME &&
6177 isa<CXXMethodDecl>(ME->getMemberDecl())) {
6178 ValueDecl *dcl = cast<MemberExpr>(op)->getMemberDecl();
6179 // &f where f is a member of the current object, or &o.f, or &p->f
6180 // All these are not allowed, and we need to catch them before the dcl
6181 // branch of the if, below.
6182 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
6183 << dcl;
6184 // FIXME: Improve this diagnostic and provide a fixit.
6185
6186 // Now recover by acting as if the function had been accessed qualified.
6187 return Context.getMemberPointerType(op->getType(),
6188 Context.getTypeDeclType(cast<RecordDecl>(dcl->getDeclContext()))
6189 .getTypePtr());
Chris Lattner9156f1b2010-07-05 19:17:26 +00006190 }
6191
6192 if (lval == Expr::LV_ClassTemporary) {
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006193 Diag(OpLoc, isSFINAEContext()? diag::err_typecheck_addrof_class_temporary
6194 : diag::ext_typecheck_addrof_class_temporary)
6195 << op->getType() << op->getSourceRange();
6196 if (isSFINAEContext())
6197 return QualType();
Chris Lattner93b28362010-07-05 19:36:34 +00006198 } else if (isa<ObjCSelectorExpr>(op))
Chris Lattner9156f1b2010-07-05 19:17:26 +00006199 return Context.getPointerType(op->getType());
Chris Lattner93b28362010-07-05 19:36:34 +00006200 else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00006201 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00006202 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00006203 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00006204 // FIXME: emit more specific diag...
Chris Lattnerf490e152008-11-19 05:27:50 +00006205 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
6206 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00006207 return QualType();
6208 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00006209 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00006210 // The operand cannot be a bit-field
6211 Diag(OpLoc, diag::err_typecheck_address_of)
6212 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00006213 return QualType();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00006214 } else if (op->refersToVectorElement()) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00006215 // The operand cannot be an element of a vector
Chris Lattner29e812b2008-11-20 06:06:08 +00006216 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00006217 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00006218 return QualType();
Fariborz Jahanian385db802009-07-07 18:50:52 +00006219 } else if (isa<ObjCPropertyRefExpr>(op)) {
6220 // cannot take address of a property expression.
6221 Diag(OpLoc, diag::err_typecheck_address_of)
6222 << "property expression" << op->getSourceRange();
6223 return QualType();
Anders Carlsson3fa58d12009-09-14 23:15:26 +00006224 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
6225 // FIXME: Can LHS ever be null here?
Anders Carlsson01ccf992009-09-15 16:03:44 +00006226 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
6227 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00006228 } else if (isa<UnresolvedLookupExpr>(op)) {
6229 return Context.OverloadTy;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00006230 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00006231 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00006232 // with the register storage-class specifier.
6233 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Steve Naroff35d85152007-05-07 00:24:15 +00006234 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner29e812b2008-11-20 06:06:08 +00006235 Diag(OpLoc, diag::err_typecheck_address_of)
6236 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00006237 return QualType();
6238 }
John McCalld14a8642009-11-21 08:51:07 +00006239 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006240 return Context.OverloadTy;
Anders Carlsson0b675f52009-07-08 21:45:58 +00006241 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00006242 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00006243 // Could be a pointer to member, though, if there is an explicit
6244 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006245 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00006246 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00006247 if (Ctx && Ctx->isRecord()) {
6248 if (FD->getType()->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006249 Diag(OpLoc,
Anders Carlsson0b675f52009-07-08 21:45:58 +00006250 diag::err_cannot_form_pointer_to_member_of_reference_type)
6251 << FD->getDeclName() << FD->getType();
6252 return QualType();
6253 }
Mike Stump11289f42009-09-09 15:08:12 +00006254
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00006255 return Context.getMemberPointerType(op->getType(),
6256 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00006257 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00006258 }
Anders Carlsson5b535762009-05-16 21:43:42 +00006259 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes5773a1b2008-12-16 22:58:26 +00006260 // Okay: we can take the address of a function.
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006261 // As above.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006262 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
6263 MD->isInstance())
Anders Carlsson5b535762009-05-16 21:43:42 +00006264 return Context.getMemberPointerType(op->getType(),
6265 Context.getTypeDeclType(MD->getParent()).getTypePtr());
6266 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00006267 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00006268 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006269
Eli Friedmance7f9002009-05-16 23:27:50 +00006270 if (lval == Expr::LV_IncompleteVoidType) {
6271 // Taking the address of a void variable is technically illegal, but we
6272 // allow it in cases which are otherwise valid.
6273 // Example: "extern void x; void* y = &x;".
6274 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
6275 }
6276
Steve Naroff47500512007-04-19 23:00:49 +00006277 // If the operand has type "type", the result has type "pointer to type".
Steve Naroff35d85152007-05-07 00:24:15 +00006278 return Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00006279}
6280
Chris Lattner9156f1b2010-07-05 19:17:26 +00006281/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006282QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006283 if (Op->isTypeDependent())
6284 return Context.DependentTy;
6285
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00006286 UsualUnaryConversions(Op);
Chris Lattner9156f1b2010-07-05 19:17:26 +00006287 QualType OpTy = Op->getType();
6288 QualType Result;
6289
6290 // Note that per both C89 and C99, indirection is always legal, even if OpTy
6291 // is an incomplete type or void. It would be possible to warn about
6292 // dereferencing a void pointer, but it's completely well-defined, and such a
6293 // warning is unlikely to catch any mistakes.
6294 if (const PointerType *PT = OpTy->getAs<PointerType>())
6295 Result = PT->getPointeeType();
6296 else if (const ObjCObjectPointerType *OPT =
6297 OpTy->getAs<ObjCObjectPointerType>())
6298 Result = OPT->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006299
Chris Lattner9156f1b2010-07-05 19:17:26 +00006300 if (Result.isNull()) {
6301 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
6302 << OpTy << Op->getSourceRange();
6303 return QualType();
6304 }
6305
6306 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00006307}
Steve Naroff218bc2b2007-05-04 21:54:46 +00006308
6309static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
6310 tok::TokenKind Kind) {
6311 BinaryOperator::Opcode Opc;
6312 switch (Kind) {
6313 default: assert(0 && "Unknown binop!");
Sebastian Redl112a97662009-02-07 00:15:38 +00006314 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
6315 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006316 case tok::star: Opc = BinaryOperator::Mul; break;
6317 case tok::slash: Opc = BinaryOperator::Div; break;
6318 case tok::percent: Opc = BinaryOperator::Rem; break;
6319 case tok::plus: Opc = BinaryOperator::Add; break;
6320 case tok::minus: Opc = BinaryOperator::Sub; break;
6321 case tok::lessless: Opc = BinaryOperator::Shl; break;
6322 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
6323 case tok::lessequal: Opc = BinaryOperator::LE; break;
6324 case tok::less: Opc = BinaryOperator::LT; break;
6325 case tok::greaterequal: Opc = BinaryOperator::GE; break;
6326 case tok::greater: Opc = BinaryOperator::GT; break;
6327 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
6328 case tok::equalequal: Opc = BinaryOperator::EQ; break;
6329 case tok::amp: Opc = BinaryOperator::And; break;
6330 case tok::caret: Opc = BinaryOperator::Xor; break;
6331 case tok::pipe: Opc = BinaryOperator::Or; break;
6332 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
6333 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
6334 case tok::equal: Opc = BinaryOperator::Assign; break;
6335 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
6336 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
6337 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
6338 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
6339 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
6340 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
6341 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
6342 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
6343 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
6344 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
6345 case tok::comma: Opc = BinaryOperator::Comma; break;
6346 }
6347 return Opc;
6348}
6349
Steve Naroff35d85152007-05-07 00:24:15 +00006350static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
6351 tok::TokenKind Kind) {
6352 UnaryOperator::Opcode Opc;
6353 switch (Kind) {
6354 default: assert(0 && "Unknown unary op!");
6355 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
6356 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
6357 case tok::amp: Opc = UnaryOperator::AddrOf; break;
6358 case tok::star: Opc = UnaryOperator::Deref; break;
6359 case tok::plus: Opc = UnaryOperator::Plus; break;
6360 case tok::minus: Opc = UnaryOperator::Minus; break;
6361 case tok::tilde: Opc = UnaryOperator::Not; break;
6362 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Steve Naroff35d85152007-05-07 00:24:15 +00006363 case tok::kw___real: Opc = UnaryOperator::Real; break;
6364 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
Chris Lattnerd0f76512007-06-08 22:16:53 +00006365 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00006366 }
6367 return Opc;
6368}
6369
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006370/// CreateBuiltinBinOp - Creates a new built-in binary operation with
6371/// operator @p Opc at location @c TokLoc. This routine only supports
6372/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb5d49352009-01-19 22:31:54 +00006373Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
6374 unsigned Op,
6375 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006376 QualType ResultTy; // Result type of the binary operator.
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006377 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006378 // The following two variables are used for compound assignment operators
6379 QualType CompLHSTy; // Type of LHS after promotions for computation
6380 QualType CompResultTy; // Type of computation result
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006381
6382 switch (Opc) {
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006383 case BinaryOperator::Assign:
6384 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
6385 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00006386 case BinaryOperator::PtrMemD:
6387 case BinaryOperator::PtrMemI:
6388 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
6389 Opc == BinaryOperator::PtrMemI);
6390 break;
6391 case BinaryOperator::Mul:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006392 case BinaryOperator::Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00006393 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
6394 Opc == BinaryOperator::Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006395 break;
6396 case BinaryOperator::Rem:
6397 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
6398 break;
6399 case BinaryOperator::Add:
6400 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
6401 break;
6402 case BinaryOperator::Sub:
6403 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
6404 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00006405 case BinaryOperator::Shl:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006406 case BinaryOperator::Shr:
6407 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
6408 break;
6409 case BinaryOperator::LE:
6410 case BinaryOperator::LT:
6411 case BinaryOperator::GE:
6412 case BinaryOperator::GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006413 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006414 break;
6415 case BinaryOperator::EQ:
6416 case BinaryOperator::NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006417 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006418 break;
6419 case BinaryOperator::And:
6420 case BinaryOperator::Xor:
6421 case BinaryOperator::Or:
6422 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
6423 break;
6424 case BinaryOperator::LAnd:
6425 case BinaryOperator::LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00006426 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006427 break;
6428 case BinaryOperator::MulAssign:
6429 case BinaryOperator::DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00006430 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
6431 Opc == BinaryOperator::DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006432 CompLHSTy = CompResultTy;
6433 if (!CompResultTy.isNull())
6434 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006435 break;
6436 case BinaryOperator::RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006437 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
6438 CompLHSTy = CompResultTy;
6439 if (!CompResultTy.isNull())
6440 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006441 break;
6442 case BinaryOperator::AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006443 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6444 if (!CompResultTy.isNull())
6445 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006446 break;
6447 case BinaryOperator::SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006448 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6449 if (!CompResultTy.isNull())
6450 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006451 break;
6452 case BinaryOperator::ShlAssign:
6453 case BinaryOperator::ShrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006454 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6455 CompLHSTy = CompResultTy;
6456 if (!CompResultTy.isNull())
6457 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006458 break;
6459 case BinaryOperator::AndAssign:
6460 case BinaryOperator::XorAssign:
6461 case BinaryOperator::OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006462 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6463 CompLHSTy = CompResultTy;
6464 if (!CompResultTy.isNull())
6465 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006466 break;
6467 case BinaryOperator::Comma:
6468 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6469 break;
6470 }
6471 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00006472 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006473 if (CompResultTy.isNull())
Steve Narofff6009ed2009-01-21 00:14:39 +00006474 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6475 else
6476 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006477 CompLHSTy, CompResultTy,
6478 OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006479}
6480
Sebastian Redl44615072009-10-27 12:10:02 +00006481/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6482/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006483static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6484 const PartialDiagnostic &PD,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00006485 const PartialDiagnostic &FirstNote,
6486 SourceRange FirstParenRange,
6487 const PartialDiagnostic &SecondNote,
Douglas Gregor89336232010-03-29 23:34:08 +00006488 SourceRange SecondParenRange) {
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00006489 Self.Diag(Loc, PD);
6490
6491 if (!FirstNote.getDiagID())
6492 return;
6493
6494 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
6495 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6496 // We can't display the parentheses, so just return.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006497 return;
6498 }
6499
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00006500 Self.Diag(Loc, FirstNote)
6501 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregora771f462010-03-31 17:46:05 +00006502 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006503
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00006504 if (!SecondNote.getDiagID())
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006505 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006506
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006507 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
6508 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6509 // We can't display the parentheses, so just dig the
6510 // warning/error and return.
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00006511 Self.Diag(Loc, SecondNote);
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006512 return;
6513 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006514
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00006515 Self.Diag(Loc, SecondNote)
Douglas Gregora771f462010-03-31 17:46:05 +00006516 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
6517 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006518}
6519
Sebastian Redl44615072009-10-27 12:10:02 +00006520/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6521/// operators are mixed in a way that suggests that the programmer forgot that
6522/// comparison operators have higher precedence. The most typical example of
6523/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl43028242009-10-26 15:24:15 +00006524static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6525 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00006526 typedef BinaryOperator BinOp;
6527 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6528 rhsopc = static_cast<BinOp::Opcode>(-1);
6529 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00006530 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00006531 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00006532 rhsopc = BO->getOpcode();
6533
6534 // Subs are not binary operators.
6535 if (lhsopc == -1 && rhsopc == -1)
6536 return;
6537
6538 // Bitwise operations are sometimes used as eager logical ops.
6539 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00006540 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6541 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00006542 return;
6543
Sebastian Redl44615072009-10-27 12:10:02 +00006544 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006545 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00006546 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00006547 << SourceRange(lhs->getLocStart(), OpLoc)
6548 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00006549 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006550 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00006551 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
6552 Self.PDiag(diag::note_precedence_bitwise_silence)
6553 << BinOp::getOpcodeStr(lhsopc),
6554 lhs->getSourceRange());
Sebastian Redl44615072009-10-27 12:10:02 +00006555 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006556 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00006557 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00006558 << SourceRange(OpLoc, rhs->getLocEnd())
6559 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregor89336232010-03-29 23:34:08 +00006560 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00006561 << BinOp::getOpcodeStr(Opc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00006562 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
6563 Self.PDiag(diag::note_precedence_bitwise_silence)
6564 << BinOp::getOpcodeStr(rhsopc),
6565 rhs->getSourceRange());
Sebastian Redl43028242009-10-26 15:24:15 +00006566}
6567
6568/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6569/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6570/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6571static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6572 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00006573 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl43028242009-10-26 15:24:15 +00006574 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6575}
6576
Steve Naroff218bc2b2007-05-04 21:54:46 +00006577// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb5d49352009-01-19 22:31:54 +00006578Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6579 tok::TokenKind Kind,
6580 ExprArg LHS, ExprArg RHS) {
Steve Naroff218bc2b2007-05-04 21:54:46 +00006581 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssonb781bcd2009-05-01 19:49:17 +00006582 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Steve Naroff218bc2b2007-05-04 21:54:46 +00006583
Steve Naroff83895f72007-09-16 03:34:24 +00006584 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6585 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00006586
Sebastian Redl43028242009-10-26 15:24:15 +00006587 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6588 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6589
Douglas Gregor5287f092009-11-05 00:51:44 +00006590 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6591}
6592
6593Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6594 BinaryOperator::Opcode Opc,
6595 Expr *lhs, Expr *rhs) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006596 if (getLangOptions().CPlusPlus &&
Mike Stump11289f42009-09-09 15:08:12 +00006597 (lhs->getType()->isOverloadableType() ||
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006598 rhs->getType()->isOverloadableType())) {
6599 // Find all of the overloaded operators visible from this
6600 // point. We perform both an operator-name lookup from the local
6601 // scope and an argument-dependent lookup based on the types of
6602 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00006603 UnresolvedSet<16> Functions;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006604 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00006605 if (S && OverOp != OO_None)
6606 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6607 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006608
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006609 // Build the (potentially-overloaded, potentially-dependent)
6610 // binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00006611 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb5d49352009-01-19 22:31:54 +00006612 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006613
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006614 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00006615 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006616}
6617
Douglas Gregor084d8552009-03-13 23:49:33 +00006618Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006619 unsigned OpcIn,
Douglas Gregor084d8552009-03-13 23:49:33 +00006620 ExprArg InputArg) {
6621 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregord08452f2008-11-19 15:42:04 +00006622
Mike Stump87c57ac2009-05-16 07:39:55 +00006623 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregor084d8552009-03-13 23:49:33 +00006624 Expr *Input = (Expr *)InputArg.get();
Steve Naroff35d85152007-05-07 00:24:15 +00006625 QualType resultType;
6626 switch (Opc) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006627 case UnaryOperator::OffsetOf:
6628 assert(false && "Invalid unary operator");
6629 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00006630
Steve Naroff35d85152007-05-07 00:24:15 +00006631 case UnaryOperator::PreInc:
6632 case UnaryOperator::PreDec:
Eli Friedman6aea5752009-07-22 22:25:00 +00006633 case UnaryOperator::PostInc:
6634 case UnaryOperator::PostDec:
Sebastian Redle10c2c32008-12-20 09:35:34 +00006635 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman6aea5752009-07-22 22:25:00 +00006636 Opc == UnaryOperator::PreInc ||
Alexis Huntc46382e2010-04-28 23:02:27 +00006637 Opc == UnaryOperator::PostInc,
6638 Opc == UnaryOperator::PreInc ||
6639 Opc == UnaryOperator::PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00006640 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006641 case UnaryOperator::AddrOf:
Chris Lattner86554282007-06-08 22:32:33 +00006642 resultType = CheckAddressOfOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00006643 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006644 case UnaryOperator::Deref:
Douglas Gregorb92a1562010-02-03 00:27:59 +00006645 DefaultFunctionArrayLvalueConversion(Input);
Chris Lattner86554282007-06-08 22:32:33 +00006646 resultType = CheckIndirectionOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00006647 break;
6648 case UnaryOperator::Plus:
6649 case UnaryOperator::Minus:
Steve Naroff31090012007-07-16 21:54:35 +00006650 UsualUnaryConversions(Input);
6651 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006652 if (resultType->isDependentType())
6653 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00006654 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
6655 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00006656 break;
6657 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6658 resultType->isEnumeralType())
6659 break;
6660 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6661 Opc == UnaryOperator::Plus &&
6662 resultType->isPointerType())
6663 break;
6664
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006665 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6666 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00006667 case UnaryOperator::Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00006668 UsualUnaryConversions(Input);
6669 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006670 if (resultType->isDependentType())
6671 break;
Chris Lattner0d707612008-07-25 23:52:49 +00006672 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6673 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6674 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00006675 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006676 << resultType << Input->getSourceRange();
Chris Lattner0d707612008-07-25 23:52:49 +00006677 else if (!resultType->isIntegerType())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006678 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6679 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00006680 break;
6681 case UnaryOperator::LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00006682 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregorb92a1562010-02-03 00:27:59 +00006683 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroff31090012007-07-16 21:54:35 +00006684 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006685 if (resultType->isDependentType())
6686 break;
Steve Naroff35d85152007-05-07 00:24:15 +00006687 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006688 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6689 << resultType << Input->getSourceRange());
Chris Lattnerbe31ed82007-06-02 19:11:33 +00006690 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006691 // In C++, it's bool. C++ 5.3.1p8
6692 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Steve Naroff35d85152007-05-07 00:24:15 +00006693 break;
Chris Lattner30b5dd02007-08-24 21:16:53 +00006694 case UnaryOperator::Real:
Chris Lattner30b5dd02007-08-24 21:16:53 +00006695 case UnaryOperator::Imag:
Chris Lattner709322b2009-02-17 08:12:06 +00006696 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner30b5dd02007-08-24 21:16:53 +00006697 break;
Chris Lattner86554282007-06-08 22:32:33 +00006698 case UnaryOperator::Extension:
Chris Lattner86554282007-06-08 22:32:33 +00006699 resultType = Input->getType();
Steve Naroff043d45d2007-05-15 02:32:35 +00006700 break;
Steve Naroff35d85152007-05-07 00:24:15 +00006701 }
6702 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006703 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00006704
6705 InputArg.release();
Steve Narofff6009ed2009-01-21 00:14:39 +00006706 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00006707}
Chris Lattnereefa10e2007-05-28 06:56:27 +00006708
Douglas Gregor5287f092009-11-05 00:51:44 +00006709Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6710 UnaryOperator::Opcode Opc,
6711 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006712 Expr *Input = (Expr*)input.get();
Anders Carlsson461a2c02009-11-14 21:26:41 +00006713 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6714 Opc != UnaryOperator::Extension) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006715 // Find all of the overloaded operators visible from this
6716 // point. We perform both an operator-name lookup from the local
6717 // scope and an argument-dependent lookup based on the types of
6718 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00006719 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00006720 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00006721 if (S && OverOp != OO_None)
6722 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6723 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006724
Douglas Gregor084d8552009-03-13 23:49:33 +00006725 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6726 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006727
Douglas Gregor084d8552009-03-13 23:49:33 +00006728 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6729}
6730
Douglas Gregor5287f092009-11-05 00:51:44 +00006731// Unary Operators. 'Tok' is the token for the operator.
6732Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6733 tok::TokenKind Op, ExprArg input) {
6734 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6735}
6736
Steve Naroff66356bd2007-09-16 14:56:35 +00006737/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006738Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6739 SourceLocation LabLoc,
6740 IdentifierInfo *LabelII) {
Chris Lattnereefa10e2007-05-28 06:56:27 +00006741 // Look up the record for this label identifier.
Chris Lattner3318e862009-04-18 20:01:55 +00006742 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump4e1f26a2009-02-19 03:04:26 +00006743
Daniel Dunbar88402ce2008-08-04 16:51:22 +00006744 // If we haven't seen this label yet, create a forward reference. It
6745 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff846b1ec2009-03-13 15:38:40 +00006746 if (LabelDecl == 0)
Steve Narofff6009ed2009-01-21 00:14:39 +00006747 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006748
Chris Lattnereefa10e2007-05-28 06:56:27 +00006749 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006750 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6751 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00006752}
6753
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006754Sema::OwningExprResult
6755Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6756 SourceLocation RPLoc) { // "({..})"
6757 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner366727f2007-07-24 16:58:17 +00006758 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6759 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6760
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00006761 bool isFileScope
6762 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00006763 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006764 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00006765
Chris Lattner366727f2007-07-24 16:58:17 +00006766 // FIXME: there are a variety of strange constraints to enforce here, for
6767 // example, it is not possible to goto into a stmt expression apparently.
6768 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006769
Chris Lattner366727f2007-07-24 16:58:17 +00006770 // If there are sub stmts in the compound stmt, take the type of the last one
6771 // as the type of the stmtexpr.
6772 QualType Ty = Context.VoidTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006773
Chris Lattner944d3062008-07-26 19:51:01 +00006774 if (!Compound->body_empty()) {
6775 Stmt *LastStmt = Compound->body_back();
6776 // If LastStmt is a label, skip down through into the body.
6777 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6778 LastStmt = Label->getSubStmt();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006779
Chris Lattner944d3062008-07-26 19:51:01 +00006780 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner366727f2007-07-24 16:58:17 +00006781 Ty = LastExpr->getType();
Chris Lattner944d3062008-07-26 19:51:01 +00006782 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006783
Eli Friedmanba961a92009-03-23 00:24:07 +00006784 // FIXME: Check that expression type is complete/non-abstract; statement
6785 // expressions are not lvalues.
6786
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006787 substmt.release();
6788 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner366727f2007-07-24 16:58:17 +00006789}
Steve Naroff78864672007-08-01 22:05:33 +00006790
Douglas Gregor882211c2010-04-28 22:16:22 +00006791Sema::OwningExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
6792 TypeSourceInfo *TInfo,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006793 OffsetOfComponent *CompPtr,
6794 unsigned NumComponents,
Douglas Gregor882211c2010-04-28 22:16:22 +00006795 SourceLocation RParenLoc) {
6796 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006797 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006798 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00006799
Chris Lattnerf17bd422007-08-30 17:45:32 +00006800 // We must have at least one component that refers to the type, and the first
6801 // one is known to be a field designator. Verify that the ArgTy represents
6802 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006803 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00006804 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
6805 << ArgTy << TypeRange);
6806
6807 // Type must be complete per C99 7.17p3 because a declaring a variable
6808 // with an incomplete type would be ill-formed.
6809 if (!Dependent
6810 && RequireCompleteType(BuiltinLoc, ArgTy,
6811 PDiag(diag::err_offsetof_incomplete_type)
6812 << TypeRange))
6813 return ExprError();
6814
Chris Lattner78502cf2007-08-31 21:49:13 +00006815 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6816 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00006817 // FIXME: This diagnostic isn't actually visible because the location is in
6818 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00006819 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00006820 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6821 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00006822
6823 bool DidWarnAboutNonPOD = false;
6824 QualType CurrentType = ArgTy;
6825 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
6826 llvm::SmallVector<OffsetOfNode, 4> Comps;
6827 llvm::SmallVector<Expr*, 4> Exprs;
6828 for (unsigned i = 0; i != NumComponents; ++i) {
6829 const OffsetOfComponent &OC = CompPtr[i];
6830 if (OC.isBrackets) {
6831 // Offset of an array sub-field. TODO: Should we allow vector elements?
6832 if (!CurrentType->isDependentType()) {
6833 const ArrayType *AT = Context.getAsArrayType(CurrentType);
6834 if(!AT)
6835 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6836 << CurrentType);
6837 CurrentType = AT->getElementType();
6838 } else
6839 CurrentType = Context.DependentTy;
6840
6841 // The expression must be an integral expression.
6842 // FIXME: An integral constant expression?
6843 Expr *Idx = static_cast<Expr*>(OC.U.E);
6844 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
6845 !Idx->getType()->isIntegerType())
6846 return ExprError(Diag(Idx->getLocStart(),
6847 diag::err_typecheck_subscript_not_integer)
6848 << Idx->getSourceRange());
6849
6850 // Record this array index.
6851 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
6852 Exprs.push_back(Idx);
6853 continue;
6854 }
6855
6856 // Offset of a field.
6857 if (CurrentType->isDependentType()) {
6858 // We have the offset of a field, but we can't look into the dependent
6859 // type. Just record the identifier of the field.
6860 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
6861 CurrentType = Context.DependentTy;
6862 continue;
6863 }
6864
6865 // We need to have a complete type to look into.
6866 if (RequireCompleteType(OC.LocStart, CurrentType,
6867 diag::err_offsetof_incomplete_type))
6868 return ExprError();
6869
6870 // Look for the designated field.
6871 const RecordType *RC = CurrentType->getAs<RecordType>();
6872 if (!RC)
6873 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6874 << CurrentType);
6875 RecordDecl *RD = RC->getDecl();
6876
6877 // C++ [lib.support.types]p5:
6878 // The macro offsetof accepts a restricted set of type arguments in this
6879 // International Standard. type shall be a POD structure or a POD union
6880 // (clause 9).
6881 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6882 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
6883 DiagRuntimeBehavior(BuiltinLoc,
6884 PDiag(diag::warn_offsetof_non_pod_type)
6885 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6886 << CurrentType))
6887 DidWarnAboutNonPOD = true;
6888 }
6889
6890 // Look for the field.
6891 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6892 LookupQualifiedName(R, RD);
6893 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
6894 if (!MemberDecl)
6895 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6896 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
6897 OC.LocEnd));
6898
Douglas Gregor10982ea2010-04-28 22:36:06 +00006899 // C99 7.17p3:
6900 // (If the specified member is a bit-field, the behavior is undefined.)
6901 //
6902 // We diagnose this as an error.
6903 if (MemberDecl->getBitWidth()) {
6904 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
6905 << MemberDecl->getDeclName()
6906 << SourceRange(BuiltinLoc, RParenLoc);
6907 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
6908 return ExprError();
6909 }
6910
Douglas Gregord1702062010-04-29 00:18:15 +00006911 // If the member was found in a base class, introduce OffsetOfNodes for
6912 // the base class indirections.
6913 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
6914 /*DetectVirtual=*/false);
6915 if (IsDerivedFrom(CurrentType,
6916 Context.getTypeDeclType(MemberDecl->getParent()),
6917 Paths)) {
6918 CXXBasePath &Path = Paths.front();
6919 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
6920 B != BEnd; ++B)
6921 Comps.push_back(OffsetOfNode(B->Base));
6922 }
6923
Douglas Gregor882211c2010-04-28 22:16:22 +00006924 if (cast<RecordDecl>(MemberDecl->getDeclContext())->
Douglas Gregor10982ea2010-04-28 22:36:06 +00006925 isAnonymousStructOrUnion()) {
Douglas Gregor882211c2010-04-28 22:16:22 +00006926 llvm::SmallVector<FieldDecl*, 4> Path;
6927 BuildAnonymousStructUnionMemberPath(MemberDecl, Path);
6928 unsigned n = Path.size();
6929 for (int j = n - 1; j > -1; --j)
6930 Comps.push_back(OffsetOfNode(OC.LocStart, Path[j], OC.LocEnd));
6931 } else {
6932 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
6933 }
6934 CurrentType = MemberDecl->getType().getNonReferenceType();
6935 }
6936
6937 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
6938 TInfo, Comps.data(), Comps.size(),
6939 Exprs.data(), Exprs.size(), RParenLoc));
6940}
Mike Stump4e1f26a2009-02-19 03:04:26 +00006941
Douglas Gregor882211c2010-04-28 22:16:22 +00006942Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6943 SourceLocation BuiltinLoc,
6944 SourceLocation TypeLoc,
6945 TypeTy *argty,
6946 OffsetOfComponent *CompPtr,
6947 unsigned NumComponents,
6948 SourceLocation RPLoc) {
6949
6950 TypeSourceInfo *ArgTInfo;
6951 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
6952 if (ArgTy.isNull())
6953 return ExprError();
6954
6955 if (getLangOptions().CPlusPlus) {
6956 if (!ArgTInfo)
6957 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
6958
6959 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
6960 RPLoc);
6961 }
6962
6963 // FIXME: The code below is marked for death, once we have proper CodeGen
6964 // support for non-constant OffsetOf expressions.
6965
6966 bool Dependent = ArgTy->isDependentType();
6967
6968 // We must have at least one component that refers to the type, and the first
6969 // one is known to be a field designator. Verify that the ArgTy represents
6970 // a struct/union/class.
6971 if (!Dependent && !ArgTy->isRecordType())
6972 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
6973
6974 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6975 // with an incomplete type would be illegal.
6976
6977 // Otherwise, create a null pointer as the base, and iteratively process
6978 // the offsetof designators.
6979 QualType ArgTyPtr = Context.getPointerType(ArgTy);
6980 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
6981 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
6982 ArgTy, SourceLocation());
6983
6984 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6985 // GCC extension, diagnose them.
6986 // FIXME: This diagnostic isn't actually visible because the location is in
6987 // a system header!
6988 if (NumComponents != 1)
6989 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6990 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
6991
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006992 if (!Dependent) {
Eli Friedman8469bc72009-05-03 21:22:18 +00006993 bool DidWarnAboutNonPOD = false;
Douglas Gregor882211c2010-04-28 22:16:22 +00006994
John McCall9eff4e62009-11-04 03:03:43 +00006995 if (RequireCompleteType(TypeLoc, Res->getType(),
6996 diag::err_offsetof_incomplete_type))
6997 return ExprError();
Douglas Gregor882211c2010-04-28 22:16:22 +00006998
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006999 // FIXME: Dependent case loses a lot of information here. And probably
7000 // leaks like a sieve.
7001 for (unsigned i = 0; i != NumComponents; ++i) {
7002 const OffsetOfComponent &OC = CompPtr[i];
7003 if (OC.isBrackets) {
7004 // Offset of an array sub-field. TODO: Should we allow vector elements?
7005 const ArrayType *AT = Context.getAsArrayType(Res->getType());
7006 if (!AT) {
7007 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007008 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
Douglas Gregor882211c2010-04-28 22:16:22 +00007009 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007010 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007011
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007012 // FIXME: C++: Verify that operator[] isn't overloaded.
Douglas Gregor882211c2010-04-28 22:16:22 +00007013
Eli Friedman988a16b2009-02-27 06:44:11 +00007014 // Promote the array so it looks more like a normal array subscript
7015 // expression.
Douglas Gregorb92a1562010-02-03 00:27:59 +00007016 DefaultFunctionArrayLvalueConversion(Res);
Douglas Gregor882211c2010-04-28 22:16:22 +00007017
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007018 // C99 6.5.2.1p1
7019 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007020 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007021 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007022 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner003af242009-04-25 22:50:55 +00007023 diag::err_typecheck_subscript_not_integer)
Douglas Gregor882211c2010-04-28 22:16:22 +00007024 << Idx->getSourceRange());
7025
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007026 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
7027 OC.LocEnd);
7028 continue;
Chris Lattnerf17bd422007-08-30 17:45:32 +00007029 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007030
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007031 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007032 if (!RC) {
7033 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007034 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
Douglas Gregor882211c2010-04-28 22:16:22 +00007035 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007036 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007037
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007038 // Get the decl corresponding to this.
7039 RecordDecl *RD = RC->getDecl();
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00007040 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007041 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
7042 DiagRuntimeBehavior(BuiltinLoc,
7043 PDiag(diag::warn_offsetof_non_pod_type)
Douglas Gregor882211c2010-04-28 22:16:22 +00007044 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
7045 << Res->getType()))
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007046 DidWarnAboutNonPOD = true;
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00007047 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007048
John McCall27b18f82009-11-17 02:14:36 +00007049 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
7050 LookupQualifiedName(R, RD);
Douglas Gregor882211c2010-04-28 22:16:22 +00007051
John McCall67c00872009-12-02 08:25:40 +00007052 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007053 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007054 if (!MemberDecl)
Douglas Gregore40876a2009-10-13 21:16:44 +00007055 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
Douglas Gregor882211c2010-04-28 22:16:22 +00007056 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
7057
Douglas Gregor10982ea2010-04-28 22:36:06 +00007058 // C99 7.17p3:
7059 // (If the specified member is a bit-field, the behavior is undefined.)
7060 //
7061 // We diagnose this as an error.
7062 if (MemberDecl->getBitWidth()) {
7063 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
7064 << MemberDecl->getDeclName()
7065 << SourceRange(BuiltinLoc, RPLoc);
7066 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
7067 return ExprError();
7068 }
7069
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007070 // FIXME: C++: Verify that MemberDecl isn't a static field.
7071 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman64fc3c62009-04-26 20:50:44 +00007072 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +00007073 Res = BuildAnonymousStructUnionMemberReference(
Douglas Gregor882211c2010-04-28 22:16:22 +00007074 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedman64fc3c62009-04-26 20:50:44 +00007075 } else {
John McCall16df1e52010-03-30 21:47:33 +00007076 PerformObjectMemberConversion(Res, /*Qualifier=*/0,
7077 *R.begin(), MemberDecl);
Eli Friedman64fc3c62009-04-26 20:50:44 +00007078 // MemberDecl->getType() doesn't get the right qualifiers, but it
7079 // doesn't matter here.
7080 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
Douglas Gregor882211c2010-04-28 22:16:22 +00007081 MemberDecl->getType().getNonReferenceType());
Eli Friedman64fc3c62009-04-26 20:50:44 +00007082 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007083 }
Chris Lattnerf17bd422007-08-30 17:45:32 +00007084 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007085
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007086 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
7087 Context.getSizeType(), BuiltinLoc));
Chris Lattnerf17bd422007-08-30 17:45:32 +00007088}
7089
7090
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007091Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
7092 TypeTy *arg1,TypeTy *arg2,
7093 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00007094 // FIXME: Preserve type source info.
7095 QualType argT1 = GetTypeFromParser(arg1);
7096 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007097
Steve Naroff78864672007-08-01 22:05:33 +00007098 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump4e1f26a2009-02-19 03:04:26 +00007099
Douglas Gregorf907cbf2009-05-19 22:28:02 +00007100 if (getLangOptions().CPlusPlus) {
7101 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
7102 << SourceRange(BuiltinLoc, RPLoc);
7103 return ExprError();
7104 }
7105
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007106 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
7107 argT1, argT2, RPLoc));
Steve Naroff78864672007-08-01 22:05:33 +00007108}
7109
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007110Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
7111 ExprArg cond,
7112 ExprArg expr1, ExprArg expr2,
7113 SourceLocation RPLoc) {
7114 Expr *CondExpr = static_cast<Expr*>(cond.get());
7115 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
7116 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00007117
Steve Naroff9efdabc2007-08-03 21:21:27 +00007118 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
7119
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007120 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00007121 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00007122 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007123 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00007124 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007125 } else {
7126 // The conditional expression is required to be a constant expression.
7127 llvm::APSInt condEval(32);
7128 SourceLocation ExpLoc;
7129 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007130 return ExprError(Diag(ExpLoc,
7131 diag::err_typecheck_choose_expr_requires_constant)
7132 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00007133
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007134 // If the condition is > zero, then the AST type is the same as the LSHExpr.
7135 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregor56751b52009-09-25 04:25:58 +00007136 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
7137 : RHSExpr->isValueDependent();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007138 }
7139
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007140 cond.release(); expr1.release(); expr2.release();
7141 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregor56751b52009-09-25 04:25:58 +00007142 resType, RPLoc,
7143 resType->isDependentType(),
7144 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00007145}
7146
Steve Naroffc540d662008-09-03 18:15:37 +00007147//===----------------------------------------------------------------------===//
7148// Clang Extensions.
7149//===----------------------------------------------------------------------===//
7150
7151/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00007152void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00007153 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
7154 PushBlockScope(BlockScope, Block);
7155 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00007156 if (BlockScope)
7157 PushDeclContext(BlockScope, Block);
7158 else
7159 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00007160}
7161
Mike Stump82f071f2009-02-04 22:31:32 +00007162void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00007163 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Douglas Gregor9a28e842010-03-01 23:15:13 +00007164 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007165
John McCall8cb7bdf2010-06-04 23:28:52 +00007166 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCalla3ccba02010-06-04 11:21:44 +00007167 CurBlock->TheDecl->setSignatureAsWritten(Sig);
John McCall8cb7bdf2010-06-04 23:28:52 +00007168 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00007169
John McCall8e346702010-06-04 19:02:56 +00007170 bool isVariadic;
John McCalla3ccba02010-06-04 11:21:44 +00007171 QualType RetTy;
7172 if (const FunctionType *Fn = T->getAs<FunctionType>()) {
John McCall8e346702010-06-04 19:02:56 +00007173 CurBlock->FunctionType = T;
John McCalla3ccba02010-06-04 11:21:44 +00007174 RetTy = Fn->getResultType();
John McCall8e346702010-06-04 19:02:56 +00007175 isVariadic =
John McCalla3ccba02010-06-04 11:21:44 +00007176 !isa<FunctionProtoType>(Fn) || cast<FunctionProtoType>(Fn)->isVariadic();
7177 } else {
7178 RetTy = T;
John McCall8e346702010-06-04 19:02:56 +00007179 isVariadic = false;
John McCalla3ccba02010-06-04 11:21:44 +00007180 }
Mike Stump11289f42009-09-09 15:08:12 +00007181
John McCall8e346702010-06-04 19:02:56 +00007182 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00007183
John McCalla3ccba02010-06-04 11:21:44 +00007184 // Don't allow returning an array by value.
7185 if (RetTy->isArrayType()) {
7186 Diag(ParamInfo.getSourceRange().getBegin(), diag::err_block_returns_array);
Mike Stump82f071f2009-02-04 22:31:32 +00007187 return;
7188 }
7189
John McCalla3ccba02010-06-04 11:21:44 +00007190 // Don't allow returning a objc interface by value.
7191 if (RetTy->isObjCObjectType()) {
7192 Diag(ParamInfo.getSourceRange().getBegin(),
7193 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
7194 return;
7195 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007196
John McCalla3ccba02010-06-04 11:21:44 +00007197 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00007198 // return type. TODO: what should we do with declarators like:
7199 // ^ * { ... }
7200 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00007201 if (RetTy != Context.DependentTy)
7202 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007203
John McCalla3ccba02010-06-04 11:21:44 +00007204 // Push block parameters from the declarator if we had them.
John McCall8e346702010-06-04 19:02:56 +00007205 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCalla3ccba02010-06-04 11:21:44 +00007206 if (isa<FunctionProtoType>(T)) {
7207 FunctionProtoTypeLoc TL = cast<FunctionProtoTypeLoc>(Sig->getTypeLoc());
7208 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
7209 ParmVarDecl *Param = TL.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00007210 if (Param->getIdentifier() == 0 &&
7211 !Param->isImplicit() &&
7212 !Param->isInvalidDecl() &&
7213 !getLangOptions().CPlusPlus)
7214 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00007215 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00007216 }
John McCalla3ccba02010-06-04 11:21:44 +00007217
7218 // Fake up parameter variables if we have a typedef, like
7219 // ^ fntype { ... }
7220 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
7221 for (FunctionProtoType::arg_type_iterator
7222 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
7223 ParmVarDecl *Param =
7224 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
7225 ParamInfo.getSourceRange().getBegin(),
7226 *I);
John McCall8e346702010-06-04 19:02:56 +00007227 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00007228 }
Steve Naroffc540d662008-09-03 18:15:37 +00007229 }
John McCalla3ccba02010-06-04 11:21:44 +00007230
John McCall8e346702010-06-04 19:02:56 +00007231 // Set the parameters on the block decl.
7232 if (!Params.empty())
7233 CurBlock->TheDecl->setParams(Params.data(), Params.size());
John McCalla3ccba02010-06-04 11:21:44 +00007234
7235 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00007236 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00007237
John McCall8e346702010-06-04 19:02:56 +00007238 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00007239 Diag(ParamInfo.getAttributes()->getLoc(),
7240 diag::warn_attribute_sentinel_not_variadic) << 1;
7241 // FIXME: remove the attribute.
7242 }
7243
7244 // Put the parameter variables in scope. We can bail out immediately
7245 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00007246 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00007247 return;
7248
John McCalldf8b37c2010-03-22 09:20:08 +00007249 bool ShouldCheckShadow =
7250 Diags.getDiagnosticLevel(diag::warn_decl_shadow) != Diagnostic::Ignored;
7251
Steve Naroff1d95e5a2008-10-10 01:28:17 +00007252 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00007253 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
7254 (*AI)->setOwningFunction(CurBlock->TheDecl);
7255
Steve Naroff1d95e5a2008-10-10 01:28:17 +00007256 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00007257 if ((*AI)->getIdentifier()) {
7258 if (ShouldCheckShadow)
7259 CheckShadow(CurBlock->TheScope, *AI);
7260
Steve Naroff1d95e5a2008-10-10 01:28:17 +00007261 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00007262 }
John McCallf7b2fb52010-01-22 00:28:27 +00007263 }
Steve Naroffc540d662008-09-03 18:15:37 +00007264}
7265
7266/// ActOnBlockError - If there is an error parsing a block, this callback
7267/// is invoked to pop the information about the block from the action impl.
7268void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00007269 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00007270 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00007271 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00007272 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroffc540d662008-09-03 18:15:37 +00007273}
7274
7275/// ActOnBlockStmtExpr - This is called when the body of a block statement
7276/// literal was successfully completed. ^(int x){...}
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007277Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
7278 StmtArg body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00007279 // If blocks are disabled, emit an error.
7280 if (!LangOpts.Blocks)
7281 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00007282
Douglas Gregor9a28e842010-03-01 23:15:13 +00007283 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00007284
Steve Naroff1d95e5a2008-10-10 01:28:17 +00007285 PopDeclContext();
7286
Steve Naroffc540d662008-09-03 18:15:37 +00007287 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00007288 if (!BSI->ReturnType.isNull())
7289 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007290
Mike Stump3bf1ab42009-07-28 22:04:01 +00007291 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00007292 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00007293
7294 // If the user wrote a function type in some form, try to use that.
7295 if (!BSI->FunctionType.isNull()) {
7296 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
7297
7298 FunctionType::ExtInfo Ext = FTy->getExtInfo();
7299 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
7300
7301 // Turn protoless block types into nullary block types.
7302 if (isa<FunctionNoProtoType>(FTy)) {
7303 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0,
7304 false, false, 0, 0, Ext);
7305
7306 // Otherwise, if we don't need to change anything about the function type,
7307 // preserve its sugar structure.
7308 } else if (FTy->getResultType() == RetTy &&
7309 (!NoReturn || FTy->getNoReturnAttr())) {
7310 BlockTy = BSI->FunctionType;
7311
7312 // Otherwise, make the minimal modifications to the function type.
7313 } else {
7314 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
7315 BlockTy = Context.getFunctionType(RetTy,
7316 FPT->arg_type_begin(),
7317 FPT->getNumArgs(),
7318 FPT->isVariadic(),
7319 /*quals*/ 0,
7320 FPT->hasExceptionSpec(),
7321 FPT->hasAnyExceptionSpec(),
7322 FPT->getNumExceptions(),
7323 FPT->exception_begin(),
7324 Ext);
7325 }
7326
7327 // If we don't have a function type, just build one from nothing.
7328 } else {
7329 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0,
7330 false, false, 0, 0,
7331 FunctionType::ExtInfo(NoReturn, 0, CC_Default));
7332 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007333
Eli Friedmanba961a92009-03-23 00:24:07 +00007334 // FIXME: Check that return/parameter types are complete/non-abstract
John McCall8e346702010-06-04 19:02:56 +00007335 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
7336 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00007337 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007338
Chris Lattner45542ea2009-04-19 05:28:12 +00007339 // If needed, diagnose invalid gotos and switches in the block.
Douglas Gregor9a28e842010-03-01 23:15:13 +00007340 if (FunctionNeedsScopeChecking() && !hasAnyErrorsInThisFunction())
Chris Lattner45542ea2009-04-19 05:28:12 +00007341 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
Mike Stump11289f42009-09-09 15:08:12 +00007342
Anders Carlssonb781bcd2009-05-01 19:49:17 +00007343 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump314825b2010-01-19 23:08:01 +00007344
7345 bool Good = true;
7346 // Check goto/label use.
7347 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
7348 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
7349 LabelStmt *L = I->second;
7350
7351 // Verify that we have no forward references left. If so, there was a goto
7352 // or address of a label taken, but no definition of it.
7353 if (L->getSubStmt() != 0)
7354 continue;
7355
7356 // Emit error.
7357 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
7358 Good = false;
7359 }
Douglas Gregor9a28e842010-03-01 23:15:13 +00007360 if (!Good) {
7361 PopFunctionOrBlockScope();
Mike Stump314825b2010-01-19 23:08:01 +00007362 return ExprError();
Douglas Gregor9a28e842010-03-01 23:15:13 +00007363 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007364
Ted Kremenek918fe842010-03-20 21:06:02 +00007365 // Issue any analysis-based warnings.
Ted Kremenek0b405322010-03-23 00:13:23 +00007366 const sema::AnalysisBasedWarnings::Policy &WP =
7367 AnalysisWarnings.getDefaultPolicy();
7368 AnalysisWarnings.IssueWarnings(WP, BSI->TheDecl, BlockTy);
Ted Kremenek918fe842010-03-20 21:06:02 +00007369
Douglas Gregor9a28e842010-03-01 23:15:13 +00007370 Expr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy,
7371 BSI->hasBlockDeclRefExprs);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007372 PopFunctionOrBlockScope();
Douglas Gregor9a28e842010-03-01 23:15:13 +00007373 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00007374}
7375
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007376Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
7377 ExprArg expr, TypeTy *type,
7378 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00007379 QualType T = GetTypeFromParser(type);
Chris Lattner56382aa2009-04-05 15:49:53 +00007380 Expr *E = static_cast<Expr*>(expr.get());
7381 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00007382
Anders Carlsson7e13ab82007-10-15 20:28:48 +00007383 InitBuiltinVaListType();
Eli Friedman121ba0c2008-08-09 23:32:40 +00007384
7385 // Get the va_list type
7386 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00007387 if (VaListType->isArrayType()) {
7388 // Deal with implicit array decay; for example, on x86-64,
7389 // va_list is an array, but it's supposed to decay to
7390 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00007391 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00007392 // Make sure the input expression also decays appropriately.
7393 UsualUnaryConversions(E);
7394 } else {
7395 // Otherwise, the va_list argument must be an l-value because
7396 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00007397 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00007398 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00007399 return ExprError();
7400 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00007401
Douglas Gregorad3150c2009-05-19 23:10:31 +00007402 if (!E->isTypeDependent() &&
7403 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007404 return ExprError(Diag(E->getLocStart(),
7405 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00007406 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00007407 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007408
Eli Friedmanba961a92009-03-23 00:24:07 +00007409 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00007410 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007411
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007412 expr.release();
Douglas Gregora8a089b2010-07-13 18:40:04 +00007413 return Owned(new (Context) VAArgExpr(BuiltinLoc, E,
7414 T.getNonLValueExprType(Context),
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007415 RPLoc));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00007416}
7417
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007418Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00007419 // The type of __null will be int or long, depending on the size of
7420 // pointers on the target.
7421 QualType Ty;
7422 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
7423 Ty = Context.IntTy;
7424 else
7425 Ty = Context.LongTy;
7426
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007427 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00007428}
7429
Alexis Huntc46382e2010-04-28 23:02:27 +00007430static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00007431 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00007432 if (!SemaRef.getLangOptions().ObjC1)
7433 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007434
Anders Carlssonace5d072009-11-10 04:46:30 +00007435 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
7436 if (!PT)
7437 return;
7438
7439 // Check if the destination is of type 'id'.
7440 if (!PT->isObjCIdType()) {
7441 // Check if the destination is the 'NSString' interface.
7442 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
7443 if (!ID || !ID->getIdentifier()->isStr("NSString"))
7444 return;
7445 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007446
Anders Carlssonace5d072009-11-10 04:46:30 +00007447 // Strip off any parens and casts.
7448 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
7449 if (!SL || SL->isWide())
7450 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007451
Douglas Gregora771f462010-03-31 17:46:05 +00007452 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00007453}
7454
Chris Lattner9bad62c2008-01-04 18:04:52 +00007455bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
7456 SourceLocation Loc,
7457 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007458 Expr *SrcExpr, AssignmentAction Action,
7459 bool *Complained) {
7460 if (Complained)
7461 *Complained = false;
7462
Chris Lattner9bad62c2008-01-04 18:04:52 +00007463 // Decode the result (notice that AST's are still created for extensions).
7464 bool isInvalid = false;
7465 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00007466 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007467
Chris Lattner9bad62c2008-01-04 18:04:52 +00007468 switch (ConvTy) {
7469 default: assert(0 && "Unknown conversion type");
7470 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00007471 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00007472 DiagKind = diag::ext_typecheck_convert_pointer_int;
7473 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00007474 case IntToPointer:
7475 DiagKind = diag::ext_typecheck_convert_int_pointer;
7476 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007477 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00007478 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00007479 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
7480 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00007481 case IncompatiblePointerSign:
7482 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
7483 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007484 case FunctionVoidPointer:
7485 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
7486 break;
7487 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00007488 // If the qualifiers lost were because we were applying the
7489 // (deprecated) C++ conversion from a string literal to a char*
7490 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
7491 // Ideally, this check would be performed in
7492 // CheckPointerTypesForAssignment. However, that would require a
7493 // bit of refactoring (so that the second argument is an
7494 // expression, rather than a type), which should be done as part
7495 // of a larger effort to fix CheckPointerTypesForAssignment for
7496 // C++ semantics.
7497 if (getLangOptions().CPlusPlus &&
7498 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
7499 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007500 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
7501 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00007502 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00007503 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00007504 break;
Steve Naroff081c7422008-09-04 15:10:53 +00007505 case IntToBlockPointer:
7506 DiagKind = diag::err_int_to_block_pointer;
7507 break;
7508 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00007509 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00007510 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00007511 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00007512 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00007513 // it can give a more specific diagnostic.
7514 DiagKind = diag::warn_incompatible_qualified_id;
7515 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00007516 case IncompatibleVectors:
7517 DiagKind = diag::warn_incompatible_vectors;
7518 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007519 case Incompatible:
7520 DiagKind = diag::err_typecheck_convert_incompatible;
7521 isInvalid = true;
7522 break;
7523 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007524
Douglas Gregorc68e1402010-04-09 00:35:39 +00007525 QualType FirstType, SecondType;
7526 switch (Action) {
7527 case AA_Assigning:
7528 case AA_Initializing:
7529 // The destination type comes first.
7530 FirstType = DstType;
7531 SecondType = SrcType;
7532 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00007533
Douglas Gregorc68e1402010-04-09 00:35:39 +00007534 case AA_Returning:
7535 case AA_Passing:
7536 case AA_Converting:
7537 case AA_Sending:
7538 case AA_Casting:
7539 // The source type comes first.
7540 FirstType = SrcType;
7541 SecondType = DstType;
7542 break;
7543 }
Alexis Huntc46382e2010-04-28 23:02:27 +00007544
Douglas Gregorc68e1402010-04-09 00:35:39 +00007545 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00007546 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor4f4946a2010-04-22 00:20:18 +00007547 if (Complained)
7548 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007549 return isInvalid;
7550}
Anders Carlssone54e8a12008-11-30 19:50:32 +00007551
Chris Lattnerc71d08b2009-04-25 21:59:05 +00007552bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00007553 llvm::APSInt ICEResult;
7554 if (E->isIntegerConstantExpr(ICEResult, Context)) {
7555 if (Result)
7556 *Result = ICEResult;
7557 return false;
7558 }
7559
Anders Carlssone54e8a12008-11-30 19:50:32 +00007560 Expr::EvalResult EvalResult;
7561
Mike Stump4e1f26a2009-02-19 03:04:26 +00007562 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00007563 EvalResult.HasSideEffects) {
7564 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
7565
7566 if (EvalResult.Diag) {
7567 // We only show the note if it's not the usual "invalid subexpression"
7568 // or if it's actually in a subexpression.
7569 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
7570 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
7571 Diag(EvalResult.DiagLoc, EvalResult.Diag);
7572 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007573
Anders Carlssone54e8a12008-11-30 19:50:32 +00007574 return true;
7575 }
7576
Eli Friedmanbb967cc2009-04-25 22:26:58 +00007577 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
7578 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00007579
Eli Friedmanbb967cc2009-04-25 22:26:58 +00007580 if (EvalResult.Diag &&
7581 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
7582 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007583
Anders Carlssone54e8a12008-11-30 19:50:32 +00007584 if (Result)
7585 *Result = EvalResult.Val.getInt();
7586 return false;
7587}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007588
Douglas Gregorff790f12009-11-26 00:44:06 +00007589void
Mike Stump11289f42009-09-09 15:08:12 +00007590Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00007591 ExprEvalContexts.push_back(
7592 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007593}
7594
Mike Stump11289f42009-09-09 15:08:12 +00007595void
Douglas Gregorff790f12009-11-26 00:44:06 +00007596Sema::PopExpressionEvaluationContext() {
7597 // Pop the current expression evaluation context off the stack.
7598 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
7599 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007600
Douglas Gregorfab31f42009-12-12 07:57:52 +00007601 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
7602 if (Rec.PotentiallyReferenced) {
7603 // Mark any remaining declarations in the current position of the stack
7604 // as "referenced". If they were not meant to be referenced, semantic
7605 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007606 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00007607 I = Rec.PotentiallyReferenced->begin(),
7608 IEnd = Rec.PotentiallyReferenced->end();
7609 I != IEnd; ++I)
7610 MarkDeclarationReferenced(I->first, I->second);
7611 }
7612
7613 if (Rec.PotentiallyDiagnosed) {
7614 // Emit any pending diagnostics.
7615 for (PotentiallyEmittedDiagnostics::iterator
7616 I = Rec.PotentiallyDiagnosed->begin(),
7617 IEnd = Rec.PotentiallyDiagnosed->end();
7618 I != IEnd; ++I)
7619 Diag(I->first, I->second);
7620 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007621 }
Douglas Gregorff790f12009-11-26 00:44:06 +00007622
7623 // When are coming out of an unevaluated context, clear out any
7624 // temporaries that we may have created as part of the evaluation of
7625 // the expression in that context: they aren't relevant because they
7626 // will never be constructed.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007627 if (Rec.Context == Unevaluated &&
Douglas Gregorff790f12009-11-26 00:44:06 +00007628 ExprTemporaries.size() > Rec.NumTemporaries)
7629 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
7630 ExprTemporaries.end());
7631
7632 // Destroy the popped expression evaluation record.
7633 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007634}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007635
7636/// \brief Note that the given declaration was referenced in the source code.
7637///
7638/// This routine should be invoke whenever a given declaration is referenced
7639/// in the source code, and where that reference occurred. If this declaration
7640/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
7641/// C99 6.9p3), then the declaration will be marked as used.
7642///
7643/// \param Loc the location where the declaration was referenced.
7644///
7645/// \param D the declaration that has been referenced by the source code.
7646void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
7647 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00007648
Douglas Gregorebada0772010-06-17 23:14:26 +00007649 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00007650 return;
Mike Stump11289f42009-09-09 15:08:12 +00007651
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00007652 // Mark a parameter or variable declaration "used", regardless of whether we're in a
7653 // template or not. The reason for this is that unevaluated expressions
7654 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
7655 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007656 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00007657 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007658 D->setUsed(true);
Douglas Gregorfd27fed2010-04-07 20:29:57 +00007659 return;
7660 }
Alexis Huntc46382e2010-04-28 23:02:27 +00007661
Douglas Gregorfd27fed2010-04-07 20:29:57 +00007662 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
7663 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00007664
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007665 // Do not mark anything as "used" within a dependent context; wait for
7666 // an instantiation.
7667 if (CurContext->isDependentContext())
7668 return;
Mike Stump11289f42009-09-09 15:08:12 +00007669
Douglas Gregorff790f12009-11-26 00:44:06 +00007670 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007671 case Unevaluated:
7672 // We are in an expression that is not potentially evaluated; do nothing.
7673 return;
Mike Stump11289f42009-09-09 15:08:12 +00007674
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007675 case PotentiallyEvaluated:
7676 // We are in a potentially-evaluated expression, so this declaration is
7677 // "used"; handle this below.
7678 break;
Mike Stump11289f42009-09-09 15:08:12 +00007679
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007680 case PotentiallyPotentiallyEvaluated:
7681 // We are in an expression that may be potentially evaluated; queue this
7682 // declaration reference until we know whether the expression is
7683 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00007684 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00007685 return;
7686 }
Mike Stump11289f42009-09-09 15:08:12 +00007687
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007688 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00007689 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007690 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00007691 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Douglas Gregorebada0772010-06-17 23:14:26 +00007692 if (!Constructor->isUsed(false))
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00007693 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00007694 } else if (Constructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00007695 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00007696 if (!Constructor->isUsed(false))
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007697 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7698 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007699
Douglas Gregor88d292c2010-05-13 16:44:06 +00007700 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007701 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorebada0772010-06-17 23:14:26 +00007702 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007703 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00007704 if (Destructor->isVirtual())
7705 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007706 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7707 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7708 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00007709 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00007710 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00007711 } else if (MethodDecl->isVirtual())
7712 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007713 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00007714 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00007715 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00007716 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00007717 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00007718 bool AlreadyInstantiated = false;
7719 if (FunctionTemplateSpecializationInfo *SpecInfo
7720 = Function->getTemplateSpecializationInfo()) {
7721 if (SpecInfo->getPointOfInstantiation().isInvalid())
7722 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007723 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00007724 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00007725 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007726 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00007727 = Function->getMemberSpecializationInfo()) {
7728 if (MSInfo->getPointOfInstantiation().isInvalid())
7729 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007730 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00007731 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00007732 AlreadyInstantiated = true;
7733 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007734
Douglas Gregor7f792cf2010-01-16 22:29:39 +00007735 if (!AlreadyInstantiated) {
7736 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
7737 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
7738 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
7739 Loc));
7740 else
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007741 PendingImplicitInstantiations.push_back(std::make_pair(Function,
Douglas Gregor7f792cf2010-01-16 22:29:39 +00007742 Loc));
7743 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00007744 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007745
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007746 // FIXME: keep track of references to static functions
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007747 Function->setUsed(true);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007748
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007749 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00007750 }
Mike Stump11289f42009-09-09 15:08:12 +00007751
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007752 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007753 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00007754 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00007755 Var->getInstantiatedFromStaticDataMember()) {
7756 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7757 assert(MSInfo && "Missing member specialization information?");
7758 if (MSInfo->getPointOfInstantiation().isInvalid() &&
7759 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7760 MSInfo->setPointOfInstantiation(Loc);
7761 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7762 }
7763 }
Mike Stump11289f42009-09-09 15:08:12 +00007764
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007765 // FIXME: keep track of references to static data?
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007766
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007767 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00007768 return;
Sam Weinigbae69142009-09-11 03:29:30 +00007769 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007770}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007771
Douglas Gregor5597ab42010-05-07 23:12:07 +00007772namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00007773 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00007774 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00007775 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00007776 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
7777 Sema &S;
7778 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00007779
Douglas Gregor5597ab42010-05-07 23:12:07 +00007780 public:
7781 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00007782
Douglas Gregor5597ab42010-05-07 23:12:07 +00007783 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00007784
7785 bool TraverseTemplateArgument(const TemplateArgument &Arg);
7786 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00007787 };
7788}
7789
Chandler Carruthaf80f662010-06-09 08:17:30 +00007790bool MarkReferencedDecls::TraverseTemplateArgument(
7791 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00007792 if (Arg.getKind() == TemplateArgument::Declaration) {
7793 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
7794 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00007795
7796 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00007797}
7798
Chandler Carruthaf80f662010-06-09 08:17:30 +00007799bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00007800 if (ClassTemplateSpecializationDecl *Spec
7801 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
7802 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Chandler Carruthaf80f662010-06-09 08:17:30 +00007803 return TraverseTemplateArguments(Args.getFlatArgumentList(),
7804 Args.flat_size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00007805 }
7806
Chandler Carruthc65667c2010-06-10 10:31:57 +00007807 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00007808}
7809
7810void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
7811 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00007812 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00007813}
7814
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007815/// \brief Emit a diagnostic that describes an effect on the run-time behavior
7816/// of the program being compiled.
7817///
7818/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007819/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007820/// possibility that the code will actually be executable. Code in sizeof()
7821/// expressions, code used only during overload resolution, etc., are not
7822/// potentially evaluated. This routine will suppress such diagnostics or,
7823/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007824/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007825/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007826///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007827/// This routine should be used for all diagnostics that describe the run-time
7828/// behavior of a program, such as passing a non-POD value through an ellipsis.
7829/// Failure to do so will likely result in spurious diagnostics or failures
7830/// during overload resolution or within sizeof/alignof/typeof/typeid.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007831bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007832 const PartialDiagnostic &PD) {
7833 switch (ExprEvalContexts.back().Context ) {
7834 case Unevaluated:
7835 // The argument will never be evaluated, so don't complain.
7836 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007837
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007838 case PotentiallyEvaluated:
7839 Diag(Loc, PD);
7840 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007841
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00007842 case PotentiallyPotentiallyEvaluated:
7843 ExprEvalContexts.back().addDiagnostic(Loc, PD);
7844 break;
7845 }
7846
7847 return false;
7848}
7849
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007850bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7851 CallExpr *CE, FunctionDecl *FD) {
7852 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7853 return false;
7854
7855 PartialDiagnostic Note =
7856 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7857 << FD->getDeclName() : PDiag();
7858 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007859
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007860 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007861 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007862 PDiag(diag::err_call_function_incomplete_return)
7863 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007864 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007865 << CE->getSourceRange(),
7866 std::make_pair(NoteLoc, Note)))
7867 return true;
7868
7869 return false;
7870}
7871
John McCalld5707ab2009-10-12 21:59:07 +00007872// Diagnose the common s/=/==/ typo. Note that adding parentheses
7873// will prevent this condition from triggering, which is what we want.
7874void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7875 SourceLocation Loc;
7876
John McCall0506e4a2009-11-11 02:41:58 +00007877 unsigned diagnostic = diag::warn_condition_is_assignment;
7878
John McCalld5707ab2009-10-12 21:59:07 +00007879 if (isa<BinaryOperator>(E)) {
7880 BinaryOperator *Op = cast<BinaryOperator>(E);
7881 if (Op->getOpcode() != BinaryOperator::Assign)
7882 return;
7883
John McCallb0e419e2009-11-12 00:06:05 +00007884 // Greylist some idioms by putting them into a warning subcategory.
7885 if (ObjCMessageExpr *ME
7886 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7887 Selector Sel = ME->getSelector();
7888
John McCallb0e419e2009-11-12 00:06:05 +00007889 // self = [<foo> init...]
7890 if (isSelfExpr(Op->getLHS())
7891 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7892 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7893
7894 // <foo> = [<bar> nextObject]
7895 else if (Sel.isUnarySelector() &&
7896 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7897 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7898 }
John McCall0506e4a2009-11-11 02:41:58 +00007899
John McCalld5707ab2009-10-12 21:59:07 +00007900 Loc = Op->getOperatorLoc();
7901 } else if (isa<CXXOperatorCallExpr>(E)) {
7902 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7903 if (Op->getOperator() != OO_Equal)
7904 return;
7905
7906 Loc = Op->getOperatorLoc();
7907 } else {
7908 // Not an assignment.
7909 return;
7910 }
7911
John McCalld5707ab2009-10-12 21:59:07 +00007912 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00007913 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007914
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007915 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007916 Diag(Loc, diag::note_condition_assign_to_comparison)
Douglas Gregora771f462010-03-31 17:46:05 +00007917 << FixItHint::CreateReplacement(Loc, "==");
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007918 Diag(Loc, diag::note_condition_assign_silence)
7919 << FixItHint::CreateInsertion(Open, "(")
7920 << FixItHint::CreateInsertion(Close, ")");
John McCalld5707ab2009-10-12 21:59:07 +00007921}
7922
7923bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7924 DiagnoseAssignmentAsCondition(E);
7925
7926 if (!E->isTypeDependent()) {
Douglas Gregorb92a1562010-02-03 00:27:59 +00007927 DefaultFunctionArrayLvalueConversion(E);
John McCalld5707ab2009-10-12 21:59:07 +00007928
7929 QualType T = E->getType();
7930
7931 if (getLangOptions().CPlusPlus) {
7932 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7933 return true;
7934 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7935 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7936 << T << E->getSourceRange();
7937 return true;
7938 }
7939 }
7940
7941 return false;
7942}
Douglas Gregore60e41a2010-05-06 17:25:47 +00007943
7944Sema::OwningExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
7945 ExprArg SubExpr) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00007946 Expr *Sub = SubExpr.takeAs<Expr>();
7947 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00007948 return ExprError();
7949
Douglas Gregore60e41a2010-05-06 17:25:47 +00007950 if (CheckBooleanCondition(Sub, Loc)) {
7951 Sub->Destroy(Context);
7952 return ExprError();
7953 }
7954
7955 return Owned(Sub);
7956}