blob: 8def7d4efc51b1257f07272837e6616475bca858 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000015#include "Lookup.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000017#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000018#include "clang/AST/DeclTemplate.h"
Chris Lattner04421082008-04-08 04:40:51 +000019#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000020#include "clang/AST/ExprObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000021#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000024#include "clang/Lex/LiteralSupport.h"
25#include "clang/Lex/Preprocessor.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000026#include "clang/Parse/DeclSpec.h"
Chris Lattner418f6c72008-10-26 23:43:26 +000027#include "clang/Parse/Designator.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000028#include "clang/Parse/Scope.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000029#include "clang/Parse/Template.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030using namespace clang;
31
David Chisnall0f436562009-08-17 16:35:33 +000032
Douglas Gregor48f3bb92009-02-18 21:56:37 +000033/// \brief Determine whether the use of this declaration is valid, and
34/// emit any corresponding diagnostics.
35///
36/// This routine diagnoses various problems with referencing
37/// declarations that can occur when using a declaration. For example,
38/// it might warn if a deprecated or unavailable declaration is being
39/// used, or produce an error (and return true) if a C++0x deleted
40/// function is being used.
41///
Chris Lattner52338262009-10-25 22:31:57 +000042/// If IgnoreDeprecated is set to true, this should not want about deprecated
43/// decls.
44///
Douglas Gregor48f3bb92009-02-18 21:56:37 +000045/// \returns true if there was an error (this declaration cannot be
46/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +000047///
John McCall54abf7d2009-11-04 02:18:39 +000048bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner76a642f2009-02-15 22:43:40 +000049 // See if the decl is deprecated.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000050 if (D->getAttr<DeprecatedAttr>()) {
John McCall54abf7d2009-11-04 02:18:39 +000051 EmitDeprecationWarning(D, Loc);
Chris Lattner76a642f2009-02-15 22:43:40 +000052 }
53
Chris Lattnerffb93682009-10-25 17:21:40 +000054 // See if the decl is unavailable
55 if (D->getAttr<UnavailableAttr>()) {
56 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
57 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
58 }
59
Douglas Gregor48f3bb92009-02-18 21:56:37 +000060 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +000061 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000062 if (FD->isDeleted()) {
63 Diag(Loc, diag::err_deleted_function_use);
64 Diag(D->getLocation(), diag::note_unavailable_here) << true;
65 return true;
66 }
Douglas Gregor25d944a2009-02-24 04:26:15 +000067 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +000068
Douglas Gregor48f3bb92009-02-18 21:56:37 +000069 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +000070}
71
Fariborz Jahanian5b530052009-05-13 18:09:35 +000072/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +000073/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-05-13 18:09:35 +000074/// attribute. It warns if call does not have the sentinel argument.
75///
76void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +000077 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000078 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +000079 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000080 return;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000081 int sentinelPos = attr->getSentinel();
82 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +000083
Mike Stump390b4cc2009-05-16 07:39:55 +000084 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
85 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000086 unsigned int i = 0;
Fariborz Jahanian236673e2009-05-14 18:00:00 +000087 bool warnNotEnoughArgs = false;
88 int isMethod = 0;
89 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
90 // skip over named parameters.
91 ObjCMethodDecl::param_iterator P, E = MD->param_end();
92 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
93 if (nullPos)
94 --nullPos;
95 else
96 ++i;
97 }
98 warnNotEnoughArgs = (P != E || i >= NumArgs);
99 isMethod = 1;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000100 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000101 // skip over named parameters.
102 ObjCMethodDecl::param_iterator P, E = FD->param_end();
103 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
104 if (nullPos)
105 --nullPos;
106 else
107 ++i;
108 }
109 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000110 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000111 // block or function pointer call.
112 QualType Ty = V->getType();
113 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000114 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000115 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
116 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000117 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
118 unsigned NumArgsInProto = Proto->getNumArgs();
119 unsigned k;
120 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
121 if (nullPos)
122 --nullPos;
123 else
124 ++i;
125 }
126 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
127 }
128 if (Ty->isBlockPointerType())
129 isMethod = 2;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000130 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000131 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000132 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000133 return;
134
135 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000136 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000137 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000138 return;
139 }
140 int sentinel = i;
141 while (sentinelPos > 0 && i < NumArgs-1) {
142 --sentinelPos;
143 ++i;
144 }
145 if (sentinelPos > 0) {
146 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000147 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000148 return;
149 }
150 while (i < NumArgs-1) {
151 ++i;
152 ++sentinel;
153 }
154 Expr *sentinelExpr = Args[sentinel];
Anders Carlssone4d2bdd2009-11-24 17:24:21 +0000155 if (sentinelExpr && (!isa<GNUNullExpr>(sentinelExpr) &&
156 (!sentinelExpr->getType()->isPointerType() ||
157 !sentinelExpr->isNullPointerConstant(Context,
158 Expr::NPC_ValueDependentIsNull)))) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000159 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000160 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000161 }
162 return;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000163}
164
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000165SourceRange Sema::getExprRange(ExprTy *E) const {
166 Expr *Ex = (Expr *)E;
167 return Ex? Ex->getSourceRange() : SourceRange();
168}
169
Chris Lattnere7a2e912008-07-25 21:10:04 +0000170//===----------------------------------------------------------------------===//
171// Standard Promotions and Conversions
172//===----------------------------------------------------------------------===//
173
Chris Lattnere7a2e912008-07-25 21:10:04 +0000174/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
175void Sema::DefaultFunctionArrayConversion(Expr *&E) {
176 QualType Ty = E->getType();
177 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
178
Chris Lattnere7a2e912008-07-25 21:10:04 +0000179 if (Ty->isFunctionType())
Mike Stump1eb44332009-09-09 15:08:12 +0000180 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlssonb633c4e2009-09-01 20:37:18 +0000181 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000182 else if (Ty->isArrayType()) {
183 // In C90 mode, arrays only promote to pointers if the array expression is
184 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
185 // type 'array of type' is converted to an expression that has type 'pointer
186 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
187 // that has type 'array of type' ...". The relevant change is "an lvalue"
188 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000189 //
190 // C++ 4.2p1:
191 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
192 // T" can be converted to an rvalue of type "pointer to T".
193 //
194 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
195 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson112a0a82009-08-07 23:48:20 +0000196 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
197 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000198 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000199}
200
201/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000202/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnere7a2e912008-07-25 21:10:04 +0000203/// sometimes surpressed. For example, the array->pointer conversion doesn't
204/// apply if the array is an argument to the sizeof or address (&) operators.
205/// In these instances, this routine should *not* be called.
206Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
207 QualType Ty = Expr->getType();
208 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000209
Douglas Gregorfc24e442009-05-01 20:41:21 +0000210 // C99 6.3.1.1p2:
211 //
212 // The following may be used in an expression wherever an int or
213 // unsigned int may be used:
214 // - an object or expression with an integer type whose integer
215 // conversion rank is less than or equal to the rank of int
216 // and unsigned int.
217 // - A bit-field of type _Bool, int, signed int, or unsigned int.
218 //
219 // If an int can represent all values of the original type, the
220 // value is converted to an int; otherwise, it is converted to an
221 // unsigned int. These are called the integer promotions. All
222 // other types are unchanged by the integer promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000223 QualType PTy = Context.isPromotableBitField(Expr);
224 if (!PTy.isNull()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +0000225 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman04e83572009-08-20 04:21:42 +0000226 return Expr;
227 }
Douglas Gregorfc24e442009-05-01 20:41:21 +0000228 if (Ty->isPromotableIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +0000229 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman73c39ab2009-10-20 08:27:19 +0000230 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregorfc24e442009-05-01 20:41:21 +0000231 return Expr;
Eli Friedman04e83572009-08-20 04:21:42 +0000232 }
233
Douglas Gregorfc24e442009-05-01 20:41:21 +0000234 DefaultFunctionArrayConversion(Expr);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000235 return Expr;
236}
237
Chris Lattner05faf172008-07-25 22:25:12 +0000238/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000239/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000240/// double. All other argument types are converted by UsualUnaryConversions().
241void Sema::DefaultArgumentPromotion(Expr *&Expr) {
242 QualType Ty = Expr->getType();
243 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Chris Lattner05faf172008-07-25 22:25:12 +0000245 // If this is a 'float' (CVR qualified or typedef) promote to double.
John McCall183700f2009-09-21 23:43:11 +0000246 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
Chris Lattner05faf172008-07-25 22:25:12 +0000247 if (BT->getKind() == BuiltinType::Float)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000248 return ImpCastExprToType(Expr, Context.DoubleTy,
249 CastExpr::CK_FloatingCast);
Mike Stump1eb44332009-09-09 15:08:12 +0000250
Chris Lattner05faf172008-07-25 22:25:12 +0000251 UsualUnaryConversions(Expr);
252}
253
Chris Lattner312531a2009-04-12 08:11:20 +0000254/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
255/// will warn if the resulting type is not a POD type, and rejects ObjC
256/// interfaces passed by value. This returns true if the argument type is
257/// completely illegal.
258bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000259 DefaultArgumentPromotion(Expr);
Mike Stump1eb44332009-09-09 15:08:12 +0000260
Chris Lattner312531a2009-04-12 08:11:20 +0000261 if (Expr->getType()->isObjCInterfaceType()) {
262 Diag(Expr->getLocStart(),
263 diag::err_cannot_pass_objc_interface_to_vararg)
264 << Expr->getType() << CT;
265 return true;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000266 }
Mike Stump1eb44332009-09-09 15:08:12 +0000267
Chris Lattner312531a2009-04-12 08:11:20 +0000268 if (!Expr->getType()->isPODType())
269 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
270 << Expr->getType() << CT;
271
272 return false;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000273}
274
275
Chris Lattnere7a2e912008-07-25 21:10:04 +0000276/// UsualArithmeticConversions - Performs various conversions that are common to
277/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000278/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000279/// responsible for emitting appropriate error diagnostics.
280/// FIXME: verify the conversion rules for "complex int" are consistent with
281/// GCC.
282QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
283 bool isCompAssign) {
Eli Friedmanab3a8522009-03-28 01:22:36 +0000284 if (!isCompAssign)
Chris Lattnere7a2e912008-07-25 21:10:04 +0000285 UsualUnaryConversions(lhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000286
287 UsualUnaryConversions(rhsExpr);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000288
Mike Stump1eb44332009-09-09 15:08:12 +0000289 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000290 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000291 QualType lhs =
292 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000293 QualType rhs =
Chris Lattnerb77792e2008-07-26 22:17:49 +0000294 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000295
296 // If both types are identical, no conversion is needed.
297 if (lhs == rhs)
298 return lhs;
299
300 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
301 // The caller can deal with this (e.g. pointer + int).
302 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
303 return lhs;
304
Douglas Gregor2d833e32009-05-02 00:36:19 +0000305 // Perform bitfield promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000306 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000307 if (!LHSBitfieldPromoteTy.isNull())
308 lhs = LHSBitfieldPromoteTy;
Eli Friedman04e83572009-08-20 04:21:42 +0000309 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000310 if (!RHSBitfieldPromoteTy.isNull())
311 rhs = RHSBitfieldPromoteTy;
312
Eli Friedmana95d7572009-08-19 07:44:53 +0000313 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000314 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000315 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
316 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000317 return destType;
318}
319
Chris Lattnere7a2e912008-07-25 21:10:04 +0000320//===----------------------------------------------------------------------===//
321// Semantic Analysis for various Expression Types
322//===----------------------------------------------------------------------===//
323
324
Steve Narofff69936d2007-09-16 03:34:24 +0000325/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000326/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
327/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
328/// multiple tokens. However, the common case is that StringToks points to one
329/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000330///
331Action::OwningExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000332Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000333 assert(NumStringToks && "Must have at least one string!");
334
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000335 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000336 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000337 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000338
339 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
340 for (unsigned i = 0; i != NumStringToks; ++i)
341 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000342
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000343 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000344 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000345 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000346
347 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
348 if (getLangOptions().CPlusPlus)
349 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000350
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000351 // Get an array type for the string, according to C99 6.4.5. This includes
352 // the nul terminator character as well as the string length for pascal
353 // strings.
354 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000355 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000356 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Reid Spencer5f016e22007-07-11 17:01:13 +0000358 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump1eb44332009-09-09 15:08:12 +0000359 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattner2085fd62009-02-18 06:40:38 +0000360 Literal.GetStringLength(),
361 Literal.AnyWide, StrTy,
362 &StringTokLocs[0],
363 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000364}
365
Chris Lattner639e2d32008-10-20 05:16:36 +0000366/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
367/// CurBlock to VD should cause it to be snapshotted (as we do for auto
368/// variables defined outside the block) or false if this is not needed (e.g.
369/// for values inside the block or for globals).
370///
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000371/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
372/// up-to-date.
373///
Chris Lattner639e2d32008-10-20 05:16:36 +0000374static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
375 ValueDecl *VD) {
376 // If the value is defined inside the block, we couldn't snapshot it even if
377 // we wanted to.
378 if (CurBlock->TheDecl == VD->getDeclContext())
379 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000380
Chris Lattner639e2d32008-10-20 05:16:36 +0000381 // If this is an enum constant or function, it is constant, don't snapshot.
382 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
383 return false;
384
385 // If this is a reference to an extern, static, or global variable, no need to
386 // snapshot it.
387 // FIXME: What about 'const' variables in C++?
388 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000389 if (!Var->hasLocalStorage())
390 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000392 // Blocks that have these can't be constant.
393 CurBlock->hasBlockDeclRefExprs = true;
394
395 // If we have nested blocks, the decl may be declared in an outer block (in
396 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
397 // be defined outside all of the current blocks (in which case the blocks do
398 // all get the bit). Walk the nesting chain.
399 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
400 NextBlock = NextBlock->PrevBlockInfo) {
401 // If we found the defining block for the variable, don't mark the block as
402 // having a reference outside it.
403 if (NextBlock->TheDecl == VD->getDeclContext())
404 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000405
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000406 // Otherwise, the DeclRef from the inner block causes the outer one to need
407 // a snapshot as well.
408 NextBlock->hasBlockDeclRefExprs = true;
409 }
Mike Stump1eb44332009-09-09 15:08:12 +0000410
Chris Lattner639e2d32008-10-20 05:16:36 +0000411 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000412}
413
Chris Lattner639e2d32008-10-20 05:16:36 +0000414
415
Douglas Gregora2813ce2009-10-23 18:54:35 +0000416/// BuildDeclRefExpr - Build a DeclRefExpr.
Anders Carlssone41590d2009-06-24 00:10:43 +0000417Sema::OwningExprResult
Sebastian Redlebc07d52009-02-03 20:19:35 +0000418Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000419 const CXXScopeSpec *SS) {
John McCallba135432009-11-21 08:51:07 +0000420 assert(!isa<OverloadedFunctionDecl>(D));
421
Anders Carlssone2bb2242009-06-26 19:16:07 +0000422 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
423 Diag(Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000424 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlssone2bb2242009-06-26 19:16:07 +0000425 << D->getDeclName();
426 return ExprError();
427 }
Mike Stump1eb44332009-09-09 15:08:12 +0000428
Anders Carlssone41590d2009-06-24 00:10:43 +0000429 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
430 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
431 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
432 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Mike Stump1eb44332009-09-09 15:08:12 +0000433 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlssone41590d2009-06-24 00:10:43 +0000434 << D->getIdentifier() << FD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +0000435 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlssone41590d2009-06-24 00:10:43 +0000436 << D->getIdentifier();
437 return ExprError();
438 }
439 }
440 }
441 }
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Douglas Gregore0762c92009-06-19 23:52:42 +0000443 MarkDeclarationReferenced(Loc, D);
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Douglas Gregora2813ce2009-10-23 18:54:35 +0000445 return Owned(DeclRefExpr::Create(Context,
446 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
447 SS? SS->getRange() : SourceRange(),
Douglas Gregor0da76df2009-11-23 11:41:28 +0000448 D, Loc, Ty));
Douglas Gregor1a49af92009-01-06 05:10:23 +0000449}
450
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000451/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
452/// variable corresponding to the anonymous union or struct whose type
453/// is Record.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000454static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
455 RecordDecl *Record) {
Mike Stump1eb44332009-09-09 15:08:12 +0000456 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000457 "Record must be an anonymous struct or union!");
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Mike Stump390b4cc2009-05-16 07:39:55 +0000459 // FIXME: Once Decls are directly linked together, this will be an O(1)
460 // operation rather than a slow walk through DeclContext's vector (which
461 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000462 DeclContext *Ctx = Record->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +0000463 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000464 DEnd = Ctx->decls_end();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000465 D != DEnd; ++D) {
466 if (*D == Record) {
467 // The object for the anonymous struct/union directly
468 // follows its type in the list of declarations.
469 ++D;
470 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000471 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000472 return *D;
473 }
474 }
475
476 assert(false && "Missing object for anonymous record");
477 return 0;
478}
479
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000480/// \brief Given a field that represents a member of an anonymous
481/// struct/union, build the path from that field's context to the
482/// actual member.
483///
484/// Construct the sequence of field member references we'll have to
485/// perform to get to the field in the anonymous union/struct. The
486/// list of members is built from the field outward, so traverse it
487/// backwards to go from an object in the current context to the field
488/// we found.
489///
490/// \returns The variable from which the field access should begin,
491/// for an anonymous struct/union that is not a member of another
492/// class. Otherwise, returns NULL.
493VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
494 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000495 assert(Field->getDeclContext()->isRecord() &&
496 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
497 && "Field must be stored inside an anonymous struct or union");
498
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000499 Path.push_back(Field);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000500 VarDecl *BaseObject = 0;
501 DeclContext *Ctx = Field->getDeclContext();
502 do {
503 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000504 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000505 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000506 Path.push_back(AnonField);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000507 else {
508 BaseObject = cast<VarDecl>(AnonObject);
509 break;
510 }
511 Ctx = Ctx->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +0000512 } while (Ctx->isRecord() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000513 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000514
515 return BaseObject;
516}
517
518Sema::OwningExprResult
519Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
520 FieldDecl *Field,
521 Expr *BaseObjectExpr,
522 SourceLocation OpLoc) {
523 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump1eb44332009-09-09 15:08:12 +0000524 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000525 AnonFields);
526
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000527 // Build the expression that refers to the base object, from
528 // which we will build a sequence of member references to each
529 // of the anonymous union objects and, eventually, the field we
530 // found via name lookup.
531 bool BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000532 Qualifiers BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000533 if (BaseObject) {
534 // BaseObject is an anonymous struct/union variable (and is,
535 // therefore, not part of another non-anonymous record).
Ted Kremenek8189cde2009-02-07 01:47:29 +0000536 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregore0762c92009-06-19 23:52:42 +0000537 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000538 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000539 SourceLocation());
John McCall0953e762009-09-24 19:53:00 +0000540 BaseQuals
541 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000542 } else if (BaseObjectExpr) {
543 // The caller provided the base object expression. Determine
544 // whether its a pointer and whether it adds any qualifiers to the
545 // anonymous struct/union fields we're looking into.
546 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000547 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000548 BaseObjectIsPointer = true;
549 ObjectType = ObjectPtr->getPointeeType();
550 }
John McCall0953e762009-09-24 19:53:00 +0000551 BaseQuals
552 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000553 } else {
554 // We've found a member of an anonymous struct/union that is
555 // inside a non-anonymous struct/union, so in a well-formed
556 // program our base object expression is "this".
557 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
558 if (!MD->isStatic()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000559 QualType AnonFieldType
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000560 = Context.getTagDeclType(
561 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
562 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +0000563 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000564 == Context.getCanonicalType(ThisType)) ||
565 IsDerivedFrom(ThisType, AnonFieldType)) {
566 // Our base object expression is "this".
Steve Naroff6ece14c2009-01-21 00:14:39 +0000567 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000568 MD->getThisType(Context));
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000569 BaseObjectIsPointer = true;
570 }
571 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000572 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
573 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000574 }
John McCall0953e762009-09-24 19:53:00 +0000575 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000576 }
577
Mike Stump1eb44332009-09-09 15:08:12 +0000578 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000579 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
580 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000581 }
582
583 // Build the implicit member references to the field of the
584 // anonymous struct/union.
585 Expr *Result = BaseObjectExpr;
John McCall0953e762009-09-24 19:53:00 +0000586 Qualifiers ResultQuals = BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000587 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
588 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
589 FI != FIEnd; ++FI) {
590 QualType MemberType = (*FI)->getType();
John McCall0953e762009-09-24 19:53:00 +0000591 Qualifiers MemberTypeQuals =
592 Context.getCanonicalType(MemberType).getQualifiers();
593
594 // CVR attributes from the base are picked up by members,
595 // except that 'mutable' members don't pick up 'const'.
596 if ((*FI)->isMutable())
597 ResultQuals.removeConst();
598
599 // GC attributes are never picked up by members.
600 ResultQuals.removeObjCGCAttr();
601
602 // TR 18037 does not allow fields to be declared with address spaces.
603 assert(!MemberTypeQuals.hasAddressSpace());
604
605 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
606 if (NewQuals != MemberTypeQuals)
607 MemberType = Context.getQualifiedType(MemberType, NewQuals);
608
Douglas Gregore0762c92009-06-19 23:52:42 +0000609 MarkDeclarationReferenced(Loc, *FI);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000610 // FIXME: Might this end up being a qualified name?
Steve Naroff6ece14c2009-01-21 00:14:39 +0000611 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
612 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000613 BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000614 ResultQuals = NewQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000615 }
616
Sebastian Redlcd965b92009-01-18 18:53:16 +0000617 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000618}
619
John McCallf7a1a742009-11-24 19:00:30 +0000620static void DecomposeTemplateName(LookupResult &R, TemplateName TName) {
621 if (TemplateDecl *TD = TName.getAsTemplateDecl())
622 R.addDecl(TD);
623 else if (OverloadedFunctionDecl *OD
624 = TName.getAsOverloadedFunctionDecl())
625 for (OverloadIterator I(OD), E; I != E; ++I)
626 R.addDecl(*I);
John McCallb681b612009-11-22 02:49:43 +0000627
John McCallf7a1a742009-11-24 19:00:30 +0000628 R.resolveKind();
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000629}
630
John McCallf7a1a742009-11-24 19:00:30 +0000631Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
632 const CXXScopeSpec &SS,
633 UnqualifiedId &Id,
634 bool HasTrailingLParen,
635 bool isAddressOfOperand) {
636 assert(!(isAddressOfOperand && HasTrailingLParen) &&
637 "cannot be direct & operand and have a trailing lparen");
638
639 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000640 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000641
John McCallf7a1a742009-11-24 19:00:30 +0000642 TemplateArgumentListInfo ExplicitTemplateArgs;
643
644 // Decompose the UnqualifiedId into the following data.
645 DeclarationName Name;
646 SourceLocation NameLoc;
647 const TemplateArgumentListInfo *TemplateArgs;
648 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
649 ExplicitTemplateArgs.setLAngleLoc(Id.TemplateId->LAngleLoc);
650 ExplicitTemplateArgs.setRAngleLoc(Id.TemplateId->RAngleLoc);
651
652 ASTTemplateArgsPtr TemplateArgsPtr(*this,
653 Id.TemplateId->getTemplateArgs(),
654 Id.TemplateId->NumArgs);
655 translateTemplateArguments(TemplateArgsPtr, ExplicitTemplateArgs);
656 TemplateArgsPtr.release();
657
658 TemplateName TName =
659 TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
660
661 Name = Context.getNameForTemplate(TName);
662 NameLoc = Id.TemplateId->TemplateNameLoc;
663 TemplateArgs = &ExplicitTemplateArgs;
664 } else {
665 Name = GetNameFromUnqualifiedId(Id);
666 NameLoc = Id.StartLocation;
667 TemplateArgs = 0;
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000668 }
669
Douglas Gregor10c42622008-11-18 15:03:34 +0000670 IdentifierInfo *II = Name.getAsIdentifierInfo();
John McCallba135432009-11-21 08:51:07 +0000671
John McCallf7a1a742009-11-24 19:00:30 +0000672 // C++ [temp.dep.expr]p3:
673 // An id-expression is type-dependent if it contains:
674 // -- a nested-name-specifier that contains a class-name that
675 // names a dependent type.
676 // Determine whether this is a member of an unknown specialization;
677 // we need to handle these differently.
678 if (SS.isSet() && !computeDeclContext(SS, false)) {
679 bool CheckForImplicitMember = !isAddressOfOperand;
John McCallba135432009-11-21 08:51:07 +0000680
John McCallf7a1a742009-11-24 19:00:30 +0000681 return ActOnDependentIdExpression(SS, Name, NameLoc,
682 CheckForImplicitMember,
683 TemplateArgs);
684 }
John McCallba135432009-11-21 08:51:07 +0000685
John McCallf7a1a742009-11-24 19:00:30 +0000686 // Perform the required lookup.
687 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
688 if (TemplateArgs) {
689 TemplateName TName =
690 TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
John McCallba135432009-11-21 08:51:07 +0000691
John McCallf7a1a742009-11-24 19:00:30 +0000692 // Just re-use the lookup done by isTemplateName.
693 DecomposeTemplateName(R, TName);
694 } else {
695 LookupParsedName(R, S, &SS, true);
Mike Stump1eb44332009-09-09 15:08:12 +0000696
John McCallf7a1a742009-11-24 19:00:30 +0000697 // If this reference is in an Objective-C method, then we need to do
698 // some special Objective-C lookup, too.
699 if (!SS.isSet() && II && getCurMethodDecl()) {
700 OwningExprResult E(LookupInObjCMethod(R, S, II));
701 if (E.isInvalid())
702 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000703
John McCallf7a1a742009-11-24 19:00:30 +0000704 Expr *Ex = E.takeAs<Expr>();
705 if (Ex) return Owned(Ex);
Steve Naroffe3e9add2008-06-02 23:03:37 +0000706 }
Chris Lattner8a934232008-03-31 00:36:02 +0000707 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +0000708
John McCallf7a1a742009-11-24 19:00:30 +0000709 if (R.isAmbiguous())
710 return ExprError();
711
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000712 // Determine whether this name might be a candidate for
713 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +0000714 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000715
John McCallf7a1a742009-11-24 19:00:30 +0000716 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000717 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +0000718 // in C90, extension in C99, forbidden in C++).
719 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
720 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
721 if (D) R.addDecl(D);
722 }
723
724 // If this name wasn't predeclared and if this is not a function
725 // call, diagnose the problem.
726 if (R.empty()) {
727 if (!SS.isEmpty())
728 return ExprError(Diag(NameLoc, diag::err_no_member)
729 << Name << computeDeclContext(SS, false)
730 << SS.getRange());
Douglas Gregor3f093272009-10-13 21:16:44 +0000731 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
Sean Hunt3e518bd2009-11-29 07:34:05 +0000732 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor10c42622008-11-18 15:03:34 +0000733 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
John McCallf7a1a742009-11-24 19:00:30 +0000734 return ExprError(Diag(NameLoc, diag::err_undeclared_use)
735 << Name);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000736 else
John McCallf7a1a742009-11-24 19:00:30 +0000737 return ExprError(Diag(NameLoc, diag::err_undeclared_var_use) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000738 }
739 }
Mike Stump1eb44332009-09-09 15:08:12 +0000740
John McCallf7a1a742009-11-24 19:00:30 +0000741 // This is guaranteed from this point on.
742 assert(!R.empty() || ADL);
743
744 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +0000745 // Warn about constructs like:
746 // if (void *X = foo()) { ... } else { X }.
747 // In the else block, the pointer is always false.
Mike Stump1eb44332009-09-09 15:08:12 +0000748
Douglas Gregor751f9a42009-06-30 15:47:41 +0000749 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
750 Scope *CheckS = S;
Douglas Gregor9c4b8382009-11-05 17:49:26 +0000751 while (CheckS && CheckS->getControlParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000752 if (CheckS->isWithinElse() &&
Douglas Gregor751f9a42009-06-30 15:47:41 +0000753 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
John McCallf7a1a742009-11-24 19:00:30 +0000754 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
Douglas Gregor9c4b8382009-11-05 17:49:26 +0000755 << Var->getDeclName()
756 << (Var->getType()->isPointerType()? 2 :
757 Var->getType()->isBooleanType()? 1 : 0));
Douglas Gregor751f9a42009-06-30 15:47:41 +0000758 break;
759 }
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Douglas Gregor9c4b8382009-11-05 17:49:26 +0000761 // Move to the parent of this scope.
762 CheckS = CheckS->getParent();
Douglas Gregor751f9a42009-06-30 15:47:41 +0000763 }
764 }
John McCallf7a1a742009-11-24 19:00:30 +0000765 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +0000766 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
767 // C99 DR 316 says that, if a function type comes from a
768 // function definition (without a prototype), that type is only
769 // used for checking compatibility. Therefore, when referencing
770 // the function, we pretend that we don't have the full function
771 // type.
John McCallf7a1a742009-11-24 19:00:30 +0000772 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor751f9a42009-06-30 15:47:41 +0000773 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000774
Douglas Gregor751f9a42009-06-30 15:47:41 +0000775 QualType T = Func->getType();
776 QualType NoProtoType = T;
John McCall183700f2009-09-21 23:43:11 +0000777 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor751f9a42009-06-30 15:47:41 +0000778 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
John McCallf7a1a742009-11-24 19:00:30 +0000779 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor751f9a42009-06-30 15:47:41 +0000780 }
781 }
Mike Stump1eb44332009-09-09 15:08:12 +0000782
John McCall5b3f9132009-11-22 01:44:31 +0000783 // &SomeClass::foo is an abstract member reference, regardless of
784 // the nature of foo, but &SomeClass::foo(...) is not. If this is
785 // *not* an abstract member reference, and any of the results is a
786 // class member (which necessarily means they're all class members),
787 // then we make an implicit member reference instead.
788 //
789 // This check considers all the same information as the "needs ADL"
790 // check, but there's no simple logical relationship other than the
791 // fact that they can never be simultaneously true. We could
792 // calculate them both in one pass if that proves important for
793 // performance.
794 if (!ADL) {
John McCallf7a1a742009-11-24 19:00:30 +0000795 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCall5b3f9132009-11-22 01:44:31 +0000796
John McCallf7a1a742009-11-24 19:00:30 +0000797 if (!isAbstractMemberPointer && !R.empty() &&
798 isa<CXXRecordDecl>((*R.begin())->getDeclContext())) {
799 return BuildImplicitMemberReferenceExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +0000800 }
801 }
802
John McCallf7a1a742009-11-24 19:00:30 +0000803 if (TemplateArgs)
804 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +0000805
John McCallf7a1a742009-11-24 19:00:30 +0000806 return BuildDeclarationNameExpr(SS, R, ADL);
807}
808
809/// ActOnDeclarationNameExpr - Build a C++ qualified declaration name,
810/// generally during template instantiation. There's a large number
811/// of things which don't need to be done along this path.
812Sema::OwningExprResult
813Sema::BuildQualifiedDeclarationNameExpr(const CXXScopeSpec &SS,
814 DeclarationName Name,
815 SourceLocation NameLoc) {
816 DeclContext *DC;
817 if (!(DC = computeDeclContext(SS, false)) ||
818 DC->isDependentContext() ||
819 RequireCompleteDeclContext(SS))
820 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
821
822 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
823 LookupQualifiedName(R, DC);
824
825 if (R.isAmbiguous())
826 return ExprError();
827
828 if (R.empty()) {
829 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
830 return ExprError();
831 }
832
833 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
834}
835
836/// LookupInObjCMethod - The parser has read a name in, and Sema has
837/// detected that we're currently inside an ObjC method. Perform some
838/// additional lookup.
839///
840/// Ideally, most of this would be done by lookup, but there's
841/// actually quite a lot of extra work involved.
842///
843/// Returns a null sentinel to indicate trivial success.
844Sema::OwningExprResult
845Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
846 IdentifierInfo *II) {
847 SourceLocation Loc = Lookup.getNameLoc();
848
849 // There are two cases to handle here. 1) scoped lookup could have failed,
850 // in which case we should look for an ivar. 2) scoped lookup could have
851 // found a decl, but that decl is outside the current instance method (i.e.
852 // a global variable). In these two cases, we do a lookup for an ivar with
853 // this name, if the lookup sucedes, we replace it our current decl.
854
855 // If we're in a class method, we don't normally want to look for
856 // ivars. But if we don't find anything else, and there's an
857 // ivar, that's an error.
858 bool IsClassMethod = getCurMethodDecl()->isClassMethod();
859
860 bool LookForIvars;
861 if (Lookup.empty())
862 LookForIvars = true;
863 else if (IsClassMethod)
864 LookForIvars = false;
865 else
866 LookForIvars = (Lookup.isSingleResult() &&
867 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
868
869 if (LookForIvars) {
870 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
871 ObjCInterfaceDecl *ClassDeclared;
872 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
873 // Diagnose using an ivar in a class method.
874 if (IsClassMethod)
875 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
876 << IV->getDeclName());
877
878 // If we're referencing an invalid decl, just return this as a silent
879 // error node. The error diagnostic was already emitted on the decl.
880 if (IV->isInvalidDecl())
881 return ExprError();
882
883 // Check if referencing a field with __attribute__((deprecated)).
884 if (DiagnoseUseOfDecl(IV, Loc))
885 return ExprError();
886
887 // Diagnose the use of an ivar outside of the declaring class.
888 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
889 ClassDeclared != IFace)
890 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
891
892 // FIXME: This should use a new expr for a direct reference, don't
893 // turn this into Self->ivar, just return a BareIVarExpr or something.
894 IdentifierInfo &II = Context.Idents.get("self");
895 UnqualifiedId SelfName;
896 SelfName.setIdentifier(&II, SourceLocation());
897 CXXScopeSpec SelfScopeSpec;
898 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
899 SelfName, false, false);
900 MarkDeclarationReferenced(Loc, IV);
901 return Owned(new (Context)
902 ObjCIvarRefExpr(IV, IV->getType(), Loc,
903 SelfExpr.takeAs<Expr>(), true, true));
904 }
905 } else if (getCurMethodDecl()->isInstanceMethod()) {
906 // We should warn if a local variable hides an ivar.
907 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
908 ObjCInterfaceDecl *ClassDeclared;
909 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
910 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
911 IFace == ClassDeclared)
912 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
913 }
914 }
915
916 // Needed to implement property "super.method" notation.
917 if (Lookup.empty() && II->isStr("super")) {
918 QualType T;
919
920 if (getCurMethodDecl()->isInstanceMethod())
921 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
922 getCurMethodDecl()->getClassInterface()));
923 else
924 T = Context.getObjCClassType();
925 return Owned(new (Context) ObjCSuperExpr(Loc, T));
926 }
927
928 // Sentinel value saying that we didn't do anything special.
929 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +0000930}
John McCallba135432009-11-21 08:51:07 +0000931
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000932/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +0000933bool
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000934Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
935 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump1eb44332009-09-09 15:08:12 +0000936 if (CXXRecordDecl *RD =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000937 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000938 QualType DestType =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000939 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +0000940 if (DestType->isDependentType() || From->getType()->isDependentType())
941 return false;
942 QualType FromRecordType = From->getType();
943 QualType DestRecordType = DestType;
Ted Kremenek6217b802009-07-29 21:53:49 +0000944 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +0000945 DestType = Context.getPointerType(DestType);
946 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000947 }
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +0000948 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
949 CheckDerivedToBaseConversion(FromRecordType,
950 DestRecordType,
951 From->getSourceRange().getBegin(),
952 From->getSourceRange()))
953 return true;
Anders Carlsson3503d042009-07-31 01:23:52 +0000954 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
955 /*isLvalue=*/true);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000956 }
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +0000957 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000958}
Douglas Gregor751f9a42009-06-30 15:47:41 +0000959
Douglas Gregor83f6faf2009-08-31 23:41:50 +0000960/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +0000961static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
962 const CXXScopeSpec *SS, NamedDecl *Member,
John McCallf7a1a742009-11-24 19:00:30 +0000963 SourceLocation Loc, QualType Ty,
964 const TemplateArgumentListInfo *TemplateArgs = 0) {
965 NestedNameSpecifier *Qualifier = 0;
966 SourceRange QualifierRange;
967 if (SS && SS->isSet()) {
968 Qualifier = (NestedNameSpecifier *) SS->getScopeRep();
969 QualifierRange = SS->getRange();
970 }
Mike Stump1eb44332009-09-09 15:08:12 +0000971
John McCallf7a1a742009-11-24 19:00:30 +0000972 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
973 Member, Loc, TemplateArgs, Ty);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000974}
975
John McCallba135432009-11-21 08:51:07 +0000976/// Builds an implicit member access expression from the given
977/// unqualified lookup set, which is known to contain only class
978/// members.
John McCall5b3f9132009-11-22 01:44:31 +0000979Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +0000980Sema::BuildImplicitMemberReferenceExpr(const CXXScopeSpec &SS,
981 LookupResult &R,
982 const TemplateArgumentListInfo *TemplateArgs) {
983 assert(!R.empty() && !R.isAmbiguous());
984
John McCall5b3f9132009-11-22 01:44:31 +0000985 NamedDecl *D = R.getAsSingleDecl(Context);
John McCallba135432009-11-21 08:51:07 +0000986 SourceLocation Loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +0000987
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000988 // We may have found a field within an anonymous union or struct
989 // (C++ [class.union]).
Douglas Gregore961afb2009-10-22 07:08:30 +0000990 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCallf7a1a742009-11-24 19:00:30 +0000991 // FIXME: template-ids inside anonymous structs?
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000992 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
993 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCall5b3f9132009-11-22 01:44:31 +0000994 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000995
John McCallba135432009-11-21 08:51:07 +0000996 QualType ThisType;
997 QualType MemberType;
John McCall5b3f9132009-11-22 01:44:31 +0000998 if (isImplicitMemberReference(SS, D, Loc, ThisType, MemberType)) {
999 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
1000 MarkDeclarationReferenced(Loc, D);
1001 if (PerformObjectMemberConversion(This, D))
1002 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00001003
Douglas Gregore961afb2009-10-22 07:08:30 +00001004 bool ShouldCheckUse = true;
1005 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
1006 // Don't diagnose the use of a virtual member function unless it's
1007 // explicitly qualified.
John McCallf7a1a742009-11-24 19:00:30 +00001008 if (MD->isVirtual() && !SS.isSet())
Douglas Gregore961afb2009-10-22 07:08:30 +00001009 ShouldCheckUse = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00001010 }
Douglas Gregore961afb2009-10-22 07:08:30 +00001011
John McCall5b3f9132009-11-22 01:44:31 +00001012 if (ShouldCheckUse && DiagnoseUseOfDecl(D, Loc))
1013 return ExprError();
John McCallf7a1a742009-11-24 19:00:30 +00001014 return Owned(BuildMemberExpr(Context, This, true, &SS, D, Loc, MemberType,
1015 TemplateArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +00001016 }
1017
John McCallba135432009-11-21 08:51:07 +00001018 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
John McCall5b3f9132009-11-22 01:44:31 +00001019 if (!Method->isStatic())
1020 return ExprError(Diag(Loc, diag::err_member_call_without_object));
John McCallba135432009-11-21 08:51:07 +00001021 }
1022
1023 if (isa<FieldDecl>(D)) {
John McCall5b3f9132009-11-22 01:44:31 +00001024 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
John McCallba135432009-11-21 08:51:07 +00001025 if (MD->isStatic()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001026 // "invalid use of member 'x' in static member function"
John McCall5b3f9132009-11-22 01:44:31 +00001027 Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCallba135432009-11-21 08:51:07 +00001028 << D->getDeclName();
John McCall5b3f9132009-11-22 01:44:31 +00001029 return ExprError();
John McCallba135432009-11-21 08:51:07 +00001030 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001031 }
1032
Douglas Gregor88a35142008-12-22 05:46:06 +00001033 // Any other ways we could have found the field in a well-formed
1034 // program would have been turned into implicit member expressions
1035 // above.
John McCall5b3f9132009-11-22 01:44:31 +00001036 Diag(Loc, diag::err_invalid_non_static_member_use)
John McCallba135432009-11-21 08:51:07 +00001037 << D->getDeclName();
John McCall5b3f9132009-11-22 01:44:31 +00001038 return ExprError();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001039 }
Douglas Gregor88a35142008-12-22 05:46:06 +00001040
John McCall5b3f9132009-11-22 01:44:31 +00001041 // We're not in an implicit member-reference context, but the lookup
1042 // results might not require an instance. Try to build a non-member
1043 // decl reference.
John McCallf7a1a742009-11-24 19:00:30 +00001044 if (TemplateArgs)
1045 return BuildTemplateIdExpr(SS, R, /* ADL */ false, *TemplateArgs);
1046
John McCall5b3f9132009-11-22 01:44:31 +00001047 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
John McCallba135432009-11-21 08:51:07 +00001048}
1049
John McCallf7a1a742009-11-24 19:00:30 +00001050bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001051 const LookupResult &R,
1052 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00001053 // Only when used directly as the postfix-expression of a call.
1054 if (!HasTrailingLParen)
1055 return false;
1056
1057 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00001058 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00001059 return false;
1060
1061 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00001062 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00001063 return false;
1064
1065 // Turn off ADL when we find certain kinds of declarations during
1066 // normal lookup:
1067 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1068 NamedDecl *D = *I;
1069
1070 // C++0x [basic.lookup.argdep]p3:
1071 // -- a declaration of a class member
1072 // Since using decls preserve this property, we check this on the
1073 // original decl.
1074 if (D->getDeclContext()->isRecord())
1075 return false;
1076
1077 // C++0x [basic.lookup.argdep]p3:
1078 // -- a block-scope function declaration that is not a
1079 // using-declaration
1080 // NOTE: we also trigger this for function templates (in fact, we
1081 // don't check the decl type at all, since all other decl types
1082 // turn off ADL anyway).
1083 if (isa<UsingShadowDecl>(D))
1084 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1085 else if (D->getDeclContext()->isFunctionOrMethod())
1086 return false;
1087
1088 // C++0x [basic.lookup.argdep]p3:
1089 // -- a declaration that is neither a function or a function
1090 // template
1091 // And also for builtin functions.
1092 if (isa<FunctionDecl>(D)) {
1093 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1094
1095 // But also builtin functions.
1096 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1097 return false;
1098 } else if (!isa<FunctionTemplateDecl>(D))
1099 return false;
1100 }
1101
1102 return true;
1103}
1104
1105
John McCallba135432009-11-21 08:51:07 +00001106/// Diagnoses obvious problems with the use of the given declaration
1107/// as an expression. This is only actually called for lookups that
1108/// were not overloaded, and it doesn't promise that the declaration
1109/// will in fact be used.
1110static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1111 if (isa<TypedefDecl>(D)) {
1112 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1113 return true;
1114 }
1115
1116 if (isa<ObjCInterfaceDecl>(D)) {
1117 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1118 return true;
1119 }
1120
1121 if (isa<NamespaceDecl>(D)) {
1122 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1123 return true;
1124 }
1125
1126 return false;
1127}
1128
1129Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001130Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001131 LookupResult &R,
1132 bool NeedsADL) {
1133 assert(R.getResultKind() != LookupResult::FoundUnresolvedValue);
1134
John McCallf7a1a742009-11-24 19:00:30 +00001135 // If this isn't an overloaded result and we don't need ADL, just
1136 // build an ordinary singleton decl ref.
John McCall5b3f9132009-11-22 01:44:31 +00001137 if (!NeedsADL && !R.isOverloadedResult())
1138 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00001139
1140 // We only need to check the declaration if there's exactly one
1141 // result, because in the overloaded case the results can only be
1142 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00001143 if (R.isSingleResult() &&
1144 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00001145 return ExprError();
1146
John McCallf7a1a742009-11-24 19:00:30 +00001147 bool Dependent
1148 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCallba135432009-11-21 08:51:07 +00001149 UnresolvedLookupExpr *ULE
John McCallf7a1a742009-11-24 19:00:30 +00001150 = UnresolvedLookupExpr::Create(Context, Dependent,
1151 (NestedNameSpecifier*) SS.getScopeRep(),
1152 SS.getRange(),
John McCall5b3f9132009-11-22 01:44:31 +00001153 R.getLookupName(), R.getNameLoc(),
1154 NeedsADL, R.isOverloadedResult());
1155 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1156 ULE->addDecl(*I);
John McCallba135432009-11-21 08:51:07 +00001157
1158 return Owned(ULE);
1159}
1160
1161
1162/// \brief Complete semantic analysis for a reference to the given declaration.
1163Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001164Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallba135432009-11-21 08:51:07 +00001165 SourceLocation Loc, NamedDecl *D) {
1166 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00001167 assert(!isa<FunctionTemplateDecl>(D) &&
1168 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00001169 DeclarationName Name = D->getDeclName();
1170
1171 if (CheckDeclInExpr(*this, Loc, D))
1172 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001173
Steve Naroffdd972f22008-09-05 22:11:13 +00001174 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001175
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001176 // Check whether this declaration can be used. Note that we suppress
1177 // this check when we're going to perform argument-dependent lookup
1178 // on this function name, because this might not be the function
1179 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00001180 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001181 return ExprError();
1182
Steve Naroffdd972f22008-09-05 22:11:13 +00001183 // Only create DeclRefExpr's for valid Decl's.
1184 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001185 return ExprError();
1186
Chris Lattner639e2d32008-10-20 05:16:36 +00001187 // If the identifier reference is inside a block, and it refers to a value
1188 // that is outside the block, create a BlockDeclRefExpr instead of a
1189 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1190 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00001191 //
Chris Lattner639e2d32008-10-20 05:16:36 +00001192 // We do not do this for things like enum constants, global variables, etc,
1193 // as they do not get snapshotted.
1194 //
1195 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregore0762c92009-06-19 23:52:42 +00001196 MarkDeclarationReferenced(Loc, VD);
Eli Friedman5fdeae12009-03-22 23:00:19 +00001197 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff090276f2008-10-10 01:28:17 +00001198 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001199 if (VD->getAttr<BlocksAttr>())
Eli Friedman5fdeae12009-03-22 23:00:19 +00001200 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001201 // This is to record that a 'const' was actually synthesize and added.
1202 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff090276f2008-10-10 01:28:17 +00001203 // Variable will be bound by-copy, make it const within the closure.
Mike Stump1eb44332009-09-09 15:08:12 +00001204
Eli Friedman5fdeae12009-03-22 23:00:19 +00001205 ExprTy.addConst();
Mike Stump1eb44332009-09-09 15:08:12 +00001206 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001207 constAdded));
Steve Naroff090276f2008-10-10 01:28:17 +00001208 }
1209 // If this reference is not in a block or if the referenced variable is
1210 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +00001211
John McCallf7a1a742009-11-24 19:00:30 +00001212 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001213}
1214
Sebastian Redlcd965b92009-01-18 18:53:16 +00001215Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1216 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00001217 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001218
Reid Spencer5f016e22007-07-11 17:01:13 +00001219 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00001220 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00001221 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1222 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1223 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001224 }
Chris Lattner1423ea42008-01-12 18:39:25 +00001225
Chris Lattnerfa28b302008-01-12 08:14:25 +00001226 // Pre-defined identifiers are of type char[x], where x is the length of the
1227 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00001228
Anders Carlsson3a082d82009-09-08 18:24:21 +00001229 Decl *currentDecl = getCurFunctionOrMethodDecl();
1230 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00001231 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00001232 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00001233 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001234
Anders Carlsson773f3972009-09-11 01:22:35 +00001235 QualType ResTy;
1236 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1237 ResTy = Context.DependentTy;
1238 } else {
1239 unsigned Length =
1240 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001241
Anders Carlsson773f3972009-09-11 01:22:35 +00001242 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00001243 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001244 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1245 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00001246 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001247}
1248
Sebastian Redlcd965b92009-01-18 18:53:16 +00001249Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001250 llvm::SmallString<16> CharBuffer;
1251 CharBuffer.resize(Tok.getLength());
1252 const char *ThisTokBegin = &CharBuffer[0];
1253 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001254
Reid Spencer5f016e22007-07-11 17:01:13 +00001255 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1256 Tok.getLocation(), PP);
1257 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001258 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001259
1260 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1261
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001262 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1263 Literal.isWide(),
1264 type, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001265}
1266
Sebastian Redlcd965b92009-01-18 18:53:16 +00001267Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1268 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001269 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1270 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001271 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001272 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001273 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001274 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001275 }
Ted Kremenek28396602009-01-13 23:19:12 +00001276
Reid Spencer5f016e22007-07-11 17:01:13 +00001277 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001278 // Add padding so that NumericLiteralParser can overread by one character.
1279 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001280 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001281
Reid Spencer5f016e22007-07-11 17:01:13 +00001282 // Get the spelling of the token, which eliminates trigraphs, etc.
1283 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001284
Mike Stump1eb44332009-09-09 15:08:12 +00001285 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00001286 Tok.getLocation(), PP);
1287 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001288 return ExprError();
1289
Chris Lattner5d661452007-08-26 03:42:43 +00001290 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001291
Chris Lattner5d661452007-08-26 03:42:43 +00001292 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001293 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001294 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001295 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001296 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001297 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001298 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001299 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001300
1301 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1302
Ted Kremenek720c4ec2007-11-29 00:56:49 +00001303 // isExact will be set by GetFloatValue().
1304 bool isExact = false;
Chris Lattner001d64d2009-06-29 17:34:55 +00001305 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1306 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001307
Chris Lattner5d661452007-08-26 03:42:43 +00001308 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001309 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001310 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001311 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001312
Neil Boothb9449512007-08-29 22:00:19 +00001313 // long long is a C99 feature.
1314 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001315 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001316 Diag(Tok.getLocation(), diag::ext_longlong);
1317
Reid Spencer5f016e22007-07-11 17:01:13 +00001318 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001319 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001320
Reid Spencer5f016e22007-07-11 17:01:13 +00001321 if (Literal.GetIntegerValue(ResultVal)) {
1322 // If this value didn't fit into uintmax_t, warn and force to ull.
1323 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001324 Ty = Context.UnsignedLongLongTy;
1325 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001326 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001327 } else {
1328 // If this value fits into a ULL, try to figure out what else it fits into
1329 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001330
Reid Spencer5f016e22007-07-11 17:01:13 +00001331 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1332 // be an unsigned int.
1333 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1334
1335 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001336 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00001337 if (!Literal.isLong && !Literal.isLongLong) {
1338 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001339 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001340
Reid Spencer5f016e22007-07-11 17:01:13 +00001341 // Does it fit in a unsigned int?
1342 if (ResultVal.isIntN(IntSize)) {
1343 // Does it fit in a signed int?
1344 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001345 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001346 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001347 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001348 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001349 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001350 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001351
Reid Spencer5f016e22007-07-11 17:01:13 +00001352 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001353 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001354 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001355
Reid Spencer5f016e22007-07-11 17:01:13 +00001356 // Does it fit in a unsigned long?
1357 if (ResultVal.isIntN(LongSize)) {
1358 // Does it fit in a signed long?
1359 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001360 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001361 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001362 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001363 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001364 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001365 }
1366
Reid Spencer5f016e22007-07-11 17:01:13 +00001367 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001368 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001369 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001370
Reid Spencer5f016e22007-07-11 17:01:13 +00001371 // Does it fit in a unsigned long long?
1372 if (ResultVal.isIntN(LongLongSize)) {
1373 // Does it fit in a signed long long?
1374 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001375 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001376 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001377 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001378 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001379 }
1380 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001381
Reid Spencer5f016e22007-07-11 17:01:13 +00001382 // If we still couldn't decide a type, we probably have something that
1383 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001384 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001385 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001386 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001387 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001388 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001389
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001390 if (ResultVal.getBitWidth() != Width)
1391 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001392 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001393 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001394 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001395
Chris Lattner5d661452007-08-26 03:42:43 +00001396 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1397 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00001398 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001399 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001400
1401 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001402}
1403
Sebastian Redlcd965b92009-01-18 18:53:16 +00001404Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1405 SourceLocation R, ExprArg Val) {
Anders Carlssone9146f22009-05-01 19:49:17 +00001406 Expr *E = Val.takeAs<Expr>();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001407 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001408 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001409}
1410
1411/// The UsualUnaryConversions() function is *not* called by this routine.
1412/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00001413bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00001414 SourceLocation OpLoc,
1415 const SourceRange &ExprRange,
1416 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00001417 if (exprType->isDependentType())
1418 return false;
1419
Sebastian Redl5d484e82009-11-23 17:18:46 +00001420 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1421 // the result is the size of the referenced type."
1422 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1423 // result shall be the alignment of the referenced type."
1424 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
1425 exprType = Ref->getPointeeType();
1426
Reid Spencer5f016e22007-07-11 17:01:13 +00001427 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00001428 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001429 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001430 if (isSizeof)
1431 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1432 return false;
1433 }
Mike Stump1eb44332009-09-09 15:08:12 +00001434
Chris Lattner1efaa952009-04-24 00:30:45 +00001435 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001436 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001437 Diag(OpLoc, diag::ext_sizeof_void_type)
1438 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001439 return false;
1440 }
Mike Stump1eb44332009-09-09 15:08:12 +00001441
Chris Lattner1efaa952009-04-24 00:30:45 +00001442 if (RequireCompleteType(OpLoc, exprType,
Mike Stump1eb44332009-09-09 15:08:12 +00001443 isSizeof ? diag::err_sizeof_incomplete_type :
Anders Carlssonb7906612009-08-26 23:45:07 +00001444 PDiag(diag::err_alignof_incomplete_type)
1445 << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00001446 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001447
Chris Lattner1efaa952009-04-24 00:30:45 +00001448 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianced1e282009-04-24 17:34:33 +00001449 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001450 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00001451 << exprType << isSizeof << ExprRange;
1452 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00001453 }
Mike Stump1eb44332009-09-09 15:08:12 +00001454
Chris Lattner1efaa952009-04-24 00:30:45 +00001455 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001456}
1457
Chris Lattner31e21e02009-01-24 20:17:12 +00001458bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1459 const SourceRange &ExprRange) {
1460 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00001461
Mike Stump1eb44332009-09-09 15:08:12 +00001462 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00001463 if (isa<DeclRefExpr>(E))
1464 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00001465
1466 // Cannot know anything else if the expression is dependent.
1467 if (E->isTypeDependent())
1468 return false;
1469
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001470 if (E->getBitField()) {
1471 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1472 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00001473 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001474
1475 // Alignment of a field access is always okay, so long as it isn't a
1476 // bit-field.
1477 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00001478 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001479 return false;
1480
Chris Lattner31e21e02009-01-24 20:17:12 +00001481 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1482}
1483
Douglas Gregorba498172009-03-13 21:01:28 +00001484/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001485Action::OwningExprResult
John McCall5ab75172009-11-04 07:28:41 +00001486Sema::CreateSizeOfAlignOfExpr(DeclaratorInfo *DInfo,
1487 SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001488 bool isSizeOf, SourceRange R) {
John McCall5ab75172009-11-04 07:28:41 +00001489 if (!DInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00001490 return ExprError();
1491
John McCall5ab75172009-11-04 07:28:41 +00001492 QualType T = DInfo->getType();
1493
Douglas Gregorba498172009-03-13 21:01:28 +00001494 if (!T->isDependentType() &&
1495 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1496 return ExprError();
1497
1498 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCall5ab75172009-11-04 07:28:41 +00001499 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, DInfo,
Douglas Gregorba498172009-03-13 21:01:28 +00001500 Context.getSizeType(), OpLoc,
1501 R.getEnd()));
1502}
1503
1504/// \brief Build a sizeof or alignof expression given an expression
1505/// operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001506Action::OwningExprResult
1507Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001508 bool isSizeOf, SourceRange R) {
1509 // Verify that the operand is valid.
1510 bool isInvalid = false;
1511 if (E->isTypeDependent()) {
1512 // Delay type-checking for type-dependent expressions.
1513 } else if (!isSizeOf) {
1514 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001515 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00001516 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1517 isInvalid = true;
1518 } else {
1519 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1520 }
1521
1522 if (isInvalid)
1523 return ExprError();
1524
1525 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1526 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1527 Context.getSizeType(), OpLoc,
1528 R.getEnd()));
1529}
1530
Sebastian Redl05189992008-11-11 17:56:53 +00001531/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1532/// the same for @c alignof and @c __alignof
1533/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001534Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001535Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1536 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001537 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001538 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001539
Sebastian Redl05189992008-11-11 17:56:53 +00001540 if (isType) {
John McCall5ab75172009-11-04 07:28:41 +00001541 DeclaratorInfo *DInfo;
1542 (void) GetTypeFromParser(TyOrEx, &DInfo);
1543 return CreateSizeOfAlignOfExpr(DInfo, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00001544 }
Sebastian Redl05189992008-11-11 17:56:53 +00001545
Douglas Gregorba498172009-03-13 21:01:28 +00001546 Expr *ArgEx = (Expr *)TyOrEx;
1547 Action::OwningExprResult Result
1548 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1549
1550 if (Result.isInvalid())
1551 DeleteExpr(ArgEx);
1552
1553 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001554}
1555
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001556QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00001557 if (V->isTypeDependent())
1558 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001559
Chris Lattnercc26ed72007-08-26 05:39:26 +00001560 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00001561 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00001562 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00001563
Chris Lattnercc26ed72007-08-26 05:39:26 +00001564 // Otherwise they pass through real integer and floating point types here.
1565 if (V->getType()->isArithmeticType())
1566 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001567
Chris Lattnercc26ed72007-08-26 05:39:26 +00001568 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001569 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1570 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00001571 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001572}
1573
1574
Reid Spencer5f016e22007-07-11 17:01:13 +00001575
Sebastian Redl0eb23302009-01-19 00:08:26 +00001576Action::OwningExprResult
1577Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1578 tok::TokenKind Kind, ExprArg Input) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001579 UnaryOperator::Opcode Opc;
1580 switch (Kind) {
1581 default: assert(0 && "Unknown unary op!");
1582 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1583 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1584 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001585
Eli Friedmane4216e92009-11-18 03:38:04 +00001586 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Reid Spencer5f016e22007-07-11 17:01:13 +00001587}
1588
Sebastian Redl0eb23302009-01-19 00:08:26 +00001589Action::OwningExprResult
1590Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1591 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00001592 // Since this might be a postfix expression, get rid of ParenListExprs.
1593 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1594
Sebastian Redl0eb23302009-01-19 00:08:26 +00001595 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1596 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001597
Douglas Gregor337c6b92008-11-19 17:17:41 +00001598 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00001599 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1600 Base.release();
1601 Idx.release();
1602 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1603 Context.DependentTy, RLoc));
1604 }
1605
Mike Stump1eb44332009-09-09 15:08:12 +00001606 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00001607 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00001608 LHSExp->getType()->isEnumeralType() ||
1609 RHSExp->getType()->isRecordType() ||
1610 RHSExp->getType()->isEnumeralType())) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00001611 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor337c6b92008-11-19 17:17:41 +00001612 }
1613
Sebastian Redlf322ed62009-10-29 20:17:01 +00001614 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
1615}
1616
1617
1618Action::OwningExprResult
1619Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
1620 ExprArg Idx, SourceLocation RLoc) {
1621 Expr *LHSExp = static_cast<Expr*>(Base.get());
1622 Expr *RHSExp = static_cast<Expr*>(Idx.get());
1623
Chris Lattner12d9ff62007-07-16 00:14:47 +00001624 // Perform default conversions.
1625 DefaultFunctionArrayConversion(LHSExp);
1626 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001627
Chris Lattner12d9ff62007-07-16 00:14:47 +00001628 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001629
Reid Spencer5f016e22007-07-11 17:01:13 +00001630 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001631 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00001632 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00001633 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001634 Expr *BaseExpr, *IndexExpr;
1635 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00001636 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1637 BaseExpr = LHSExp;
1638 IndexExpr = RHSExp;
1639 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001640 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001641 BaseExpr = LHSExp;
1642 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001643 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001644 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001645 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001646 BaseExpr = RHSExp;
1647 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001648 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001649 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00001650 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001651 BaseExpr = LHSExp;
1652 IndexExpr = RHSExp;
1653 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001654 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00001655 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001656 // Handle the uncommon case of "123[Ptr]".
1657 BaseExpr = RHSExp;
1658 IndexExpr = LHSExp;
1659 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001660 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00001661 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001662 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00001663
Chris Lattner12d9ff62007-07-16 00:14:47 +00001664 // FIXME: need to deal with const...
1665 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001666 } else if (LHSTy->isArrayType()) {
1667 // If we see an array that wasn't promoted by
1668 // DefaultFunctionArrayConversion, it must be an array that
1669 // wasn't promoted because of the C90 rule that doesn't
1670 // allow promoting non-lvalue arrays. Warn, then
1671 // force the promotion here.
1672 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1673 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00001674 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
1675 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001676 LHSTy = LHSExp->getType();
1677
1678 BaseExpr = LHSExp;
1679 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001680 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001681 } else if (RHSTy->isArrayType()) {
1682 // Same as previous, except for 123[f().a] case
1683 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1684 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00001685 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
1686 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001687 RHSTy = RHSExp->getType();
1688
1689 BaseExpr = RHSExp;
1690 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001691 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001692 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00001693 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1694 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001695 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001696 // C99 6.5.2.1p1
Nate Begeman2ef13e52009-08-10 23:49:36 +00001697 if (!(IndexExpr->getType()->isIntegerType() &&
1698 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00001699 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1700 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001701
Daniel Dunbar7e88a602009-09-17 06:31:17 +00001702 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00001703 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
1704 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00001705 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
1706
Douglas Gregore7450f52009-03-24 19:52:54 +00001707 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00001708 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1709 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00001710 // incomplete types are not object types.
1711 if (ResultType->isFunctionType()) {
1712 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1713 << ResultType << BaseExpr->getSourceRange();
1714 return ExprError();
1715 }
Mike Stump1eb44332009-09-09 15:08:12 +00001716
Douglas Gregore7450f52009-03-24 19:52:54 +00001717 if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001718 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001719 PDiag(diag::err_subscript_incomplete_type)
1720 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00001721 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001722
Chris Lattner1efaa952009-04-24 00:30:45 +00001723 // Diagnose bad cases where we step over interface counts.
1724 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1725 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1726 << ResultType << BaseExpr->getSourceRange();
1727 return ExprError();
1728 }
Mike Stump1eb44332009-09-09 15:08:12 +00001729
Sebastian Redl0eb23302009-01-19 00:08:26 +00001730 Base.release();
1731 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001732 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001733 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001734}
1735
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001736QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001737CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001738 const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001739 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00001740 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
1741 // see FIXME there.
1742 //
1743 // FIXME: This logic can be greatly simplified by splitting it along
1744 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00001745 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00001746
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001747 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00001748 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00001749
Mike Stumpeed9cac2009-02-19 03:04:26 +00001750 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00001751 // special names that indicate a subset of exactly half the elements are
1752 // to be selected.
1753 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00001754
Nate Begeman353417a2009-01-18 01:47:54 +00001755 // This flag determines whether or not CompName has an 's' char prefix,
1756 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00001757 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00001758
1759 // Check that we've found one of the special components, or that the component
1760 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001761 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00001762 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1763 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00001764 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001765 do
1766 compStr++;
1767 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00001768 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001769 do
1770 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001771 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00001772 }
Nate Begeman353417a2009-01-18 01:47:54 +00001773
Mike Stumpeed9cac2009-02-19 03:04:26 +00001774 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001775 // We didn't get to the end of the string. This means the component names
1776 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001777 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1778 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001779 return QualType();
1780 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001781
Nate Begeman353417a2009-01-18 01:47:54 +00001782 // Ensure no component accessor exceeds the width of the vector type it
1783 // operates on.
1784 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00001785 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00001786
1787 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001788 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001789
1790 while (*compStr) {
1791 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1792 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1793 << baseType << SourceRange(CompLoc);
1794 return QualType();
1795 }
1796 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001797 }
Nate Begeman8a997642008-05-09 06:41:27 +00001798
Nate Begeman353417a2009-01-18 01:47:54 +00001799 // If this is a halving swizzle, verify that the base type has an even
1800 // number of elements.
1801 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001802 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00001803 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00001804 return QualType();
1805 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001806
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001807 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001808 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001809 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00001810 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00001811 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman353417a2009-01-18 01:47:54 +00001812 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00001813 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00001814 if (HexSwizzle)
1815 CompSize--;
1816
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001817 if (CompSize == 1)
1818 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001819
Nate Begeman213541a2008-04-18 23:10:10 +00001820 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00001821 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00001822 // diagostics look bad. We want extended vector types to appear built-in.
1823 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1824 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1825 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00001826 }
1827 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001828}
1829
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001830static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001831 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001832 const Selector &Sel,
1833 ASTContext &Context) {
Mike Stump1eb44332009-09-09 15:08:12 +00001834
Anders Carlsson8f28f992009-08-26 18:25:21 +00001835 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001836 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001837 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001838 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00001839
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001840 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1841 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00001842 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001843 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001844 return D;
1845 }
1846 return 0;
1847}
1848
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001849static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001850 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001851 const Selector &Sel,
1852 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001853 // Check protocols on qualified interfaces.
1854 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001855 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001856 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00001857 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001858 GDecl = PD;
1859 break;
1860 }
1861 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001862 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001863 GDecl = OMD;
1864 break;
1865 }
1866 }
1867 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001868 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001869 E = QIdTy->qual_end(); I != E; ++I) {
1870 // Search in the protocol-qualifier list of current protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001871 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001872 if (GDecl)
1873 return GDecl;
1874 }
1875 }
1876 return GDecl;
1877}
Chris Lattner76a642f2009-02-15 22:43:40 +00001878
Mike Stump1eb44332009-09-09 15:08:12 +00001879Action::OwningExprResult
Anders Carlsson8f28f992009-08-26 18:25:21 +00001880Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001881 tok::TokenKind OpKind, SourceLocation MemberLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001882 DeclarationName MemberName,
John McCalld5532b62009-11-23 01:53:49 +00001883 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorc68afe22009-09-03 21:38:09 +00001884 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS,
1885 NamedDecl *FirstQualifierInScope) {
Douglas Gregorfe85ced2009-08-06 03:17:00 +00001886 if (SS && SS->isInvalid())
1887 return ExprError();
1888
Nate Begeman2ef13e52009-08-10 23:49:36 +00001889 // Since this might be a postfix expression, get rid of ParenListExprs.
1890 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1891
Anders Carlssonf1b1d592009-05-01 19:30:39 +00001892 Expr *BaseExpr = Base.takeAs<Expr>();
Douglas Gregora71d8192009-09-04 17:36:40 +00001893 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00001894
Steve Naroff3cc4af82007-12-16 21:42:28 +00001895 // Perform default conversions.
1896 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001897
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001898 QualType BaseType = BaseExpr->getType();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00001899
1900 // If the user is trying to apply -> or . to a function pointer
1901 // type, it's probably because the forgot parentheses to call that
1902 // function. Suggest the addition of those parentheses, build the
1903 // call, and continue on.
1904 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1905 if (const FunctionProtoType *Fun
1906 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
1907 QualType ResultTy = Fun->getResultType();
1908 if (Fun->getNumArgs() == 0 &&
1909 ((OpKind == tok::period && ResultTy->isRecordType()) ||
1910 (OpKind == tok::arrow && ResultTy->isPointerType() &&
1911 ResultTy->getAs<PointerType>()->getPointeeType()
1912 ->isRecordType()))) {
1913 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
1914 Diag(Loc, diag::err_member_reference_needs_call)
1915 << QualType(Fun, 0)
1916 << CodeModificationHint::CreateInsertion(Loc, "()");
1917
1918 OwningExprResult NewBase
1919 = ActOnCallExpr(S, ExprArg(*this, BaseExpr), Loc,
1920 MultiExprArg(*this, 0, 0), 0, Loc);
1921 if (NewBase.isInvalid())
1922 return move(NewBase);
1923
1924 BaseExpr = NewBase.takeAs<Expr>();
1925 DefaultFunctionArrayConversion(BaseExpr);
1926 BaseType = BaseExpr->getType();
1927 }
1928 }
1929 }
1930
David Chisnall0f436562009-08-17 16:35:33 +00001931 // If this is an Objective-C pseudo-builtin and a definition is provided then
1932 // use that.
1933 if (BaseType->isObjCIdType()) {
1934 // We have an 'id' type. Rather than fall through, we check if this
1935 // is a reference to 'isa'.
1936 if (BaseType != Context.ObjCIdRedefinitionType) {
1937 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00001938 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00001939 }
David Chisnall0f436562009-08-17 16:35:33 +00001940 }
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +00001941 // If this is an Objective-C pseudo-builtin and a definition is provided then
1942 // use that.
1943 if (Context.isObjCSelType(BaseType)) {
1944 // We have an 'SEL' type. Rather than fall through, we check if this
1945 // is a reference to 'sel_id'.
1946 if (BaseType != Context.ObjCSelRedefinitionType) {
1947 BaseType = Context.ObjCSelRedefinitionType;
1948 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
1949 }
1950 }
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001951 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00001952
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00001953 // Handle properties on ObjC 'Class' types.
1954 if (OpKind == tok::period && BaseType->isObjCClassType()) {
1955 // Also must look for a getter name which uses property syntax.
1956 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1957 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1958 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
1959 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1960 ObjCMethodDecl *Getter;
1961 // FIXME: need to also look locally in the implementation.
1962 if ((Getter = IFace->lookupClassMethod(Sel))) {
1963 // Check the use of this method.
1964 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1965 return ExprError();
1966 }
1967 // If we found a getter then this may be a valid dot-reference, we
1968 // will look for the matching setter, in case it is needed.
1969 Selector SetterSel =
1970 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1971 PP.getSelectorTable(), Member);
1972 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1973 if (!Setter) {
1974 // If this reference is in an @implementation, also check for 'private'
1975 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00001976 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00001977 }
1978 // Look through local category implementations associated with the class.
1979 if (!Setter)
1980 Setter = IFace->getCategoryClassMethod(SetterSel);
1981
1982 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1983 return ExprError();
1984
1985 if (Getter || Setter) {
1986 QualType PType;
1987
1988 if (Getter)
1989 PType = Getter->getResultType();
1990 else
1991 // Get the expression type from Setter's incoming parameter.
1992 PType = (*(Setter->param_end() -1))->getType();
1993 // FIXME: we must check that the setter has property type.
1994 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
1995 PType,
1996 Setter, MemberLoc, BaseExpr));
1997 }
1998 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1999 << MemberName << BaseType);
2000 }
2001 }
2002
2003 if (BaseType->isObjCClassType() &&
2004 BaseType != Context.ObjCClassRedefinitionType) {
2005 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002006 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002007 }
2008
Chris Lattner68a057b2008-07-21 04:36:39 +00002009 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2010 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +00002011 if (OpKind == tok::arrow) {
Douglas Gregorc68afe22009-09-03 21:38:09 +00002012 if (BaseType->isDependentType()) {
2013 NestedNameSpecifier *Qualifier = 0;
2014 if (SS) {
2015 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2016 if (!FirstQualifierInScope)
2017 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2018 }
Mike Stump1eb44332009-09-09 15:08:12 +00002019
John McCall865d4472009-11-19 22:55:06 +00002020 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, true,
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00002021 OpLoc, Qualifier,
Douglas Gregora38c6872009-09-03 16:14:30 +00002022 SS? SS->getRange() : SourceRange(),
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00002023 FirstQualifierInScope,
2024 MemberName,
2025 MemberLoc,
John McCalld5532b62009-11-23 01:53:49 +00002026 ExplicitTemplateArgs));
Douglas Gregorc68afe22009-09-03 21:38:09 +00002027 }
Ted Kremenek6217b802009-07-29 21:53:49 +00002028 else if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002029 BaseType = PT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00002030 else if (BaseType->isObjCObjectPointerType())
2031 ;
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002032 else
Sebastian Redl0eb23302009-01-19 00:08:26 +00002033 return ExprError(Diag(MemberLoc,
2034 diag::err_typecheck_member_reference_arrow)
2035 << BaseType << BaseExpr->getSourceRange());
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002036 } else if (BaseType->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002037 // Require that the base type isn't a pointer type
Anders Carlsson4ef27702009-05-16 20:31:20 +00002038 // (so we'll report an error for)
2039 // T* t;
2040 // t.f;
Mike Stump1eb44332009-09-09 15:08:12 +00002041 //
Anders Carlsson4ef27702009-05-16 20:31:20 +00002042 // In Obj-C++, however, the above expression is valid, since it could be
2043 // accessing the 'f' property if T is an Obj-C interface. The extra check
2044 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenek6217b802009-07-29 21:53:49 +00002045 const PointerType *PT = BaseType->getAs<PointerType>();
Anders Carlsson4ef27702009-05-16 20:31:20 +00002046
Mike Stump1eb44332009-09-09 15:08:12 +00002047 if (!PT || (getLangOptions().ObjC1 &&
Douglas Gregorc68afe22009-09-03 21:38:09 +00002048 !PT->getPointeeType()->isRecordType())) {
2049 NestedNameSpecifier *Qualifier = 0;
2050 if (SS) {
2051 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2052 if (!FirstQualifierInScope)
2053 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2054 }
Mike Stump1eb44332009-09-09 15:08:12 +00002055
John McCall865d4472009-11-19 22:55:06 +00002056 return Owned(CXXDependentScopeMemberExpr::Create(Context,
Mike Stump1eb44332009-09-09 15:08:12 +00002057 BaseExpr, false,
2058 OpLoc,
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00002059 Qualifier,
Douglas Gregora38c6872009-09-03 16:14:30 +00002060 SS? SS->getRange() : SourceRange(),
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00002061 FirstQualifierInScope,
2062 MemberName,
2063 MemberLoc,
John McCalld5532b62009-11-23 01:53:49 +00002064 ExplicitTemplateArgs));
Douglas Gregorc68afe22009-09-03 21:38:09 +00002065 }
Anders Carlsson4ef27702009-05-16 20:31:20 +00002066 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002067
Chris Lattner68a057b2008-07-21 04:36:39 +00002068 // Handle field access to simple records. This also handles access to fields
2069 // of the ObjC 'id' struct.
Ted Kremenek6217b802009-07-29 21:53:49 +00002070 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002071 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor86447ec2009-03-09 16:13:40 +00002072 if (RequireCompleteType(OpLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002073 PDiag(diag::err_typecheck_incomplete_tag)
2074 << BaseExpr->getSourceRange()))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002075 return ExprError();
2076
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002077 DeclContext *DC = RDecl;
2078 if (SS && SS->isSet()) {
2079 // If the member name was a qualified-id, look into the
2080 // nested-name-specifier.
2081 DC = computeDeclContext(*SS, false);
Douglas Gregor8d1c9ae2009-10-17 22:37:54 +00002082
2083 if (!isa<TypeDecl>(DC)) {
2084 Diag(MemberLoc, diag::err_qualified_member_nonclass)
2085 << DC << SS->getRange();
2086 return ExprError();
2087 }
Mike Stump1eb44332009-09-09 15:08:12 +00002088
2089 // FIXME: If DC is not computable, we should build a
John McCall865d4472009-11-19 22:55:06 +00002090 // CXXDependentScopeMemberExpr.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002091 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2092 }
2093
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002094 // The record definition is complete, now make sure the member is valid.
John McCalla24dc2e2009-11-17 02:14:36 +00002095 LookupResult Result(*this, MemberName, MemberLoc, LookupMemberName);
2096 LookupQualifiedName(Result, DC);
Douglas Gregor7176fff2009-01-15 00:26:24 +00002097
John McCallf36e02d2009-10-09 21:13:30 +00002098 if (Result.empty())
Douglas Gregor3f093272009-10-13 21:16:44 +00002099 return ExprError(Diag(MemberLoc, diag::err_no_member)
2100 << MemberName << DC << BaseExpr->getSourceRange());
John McCalla24dc2e2009-11-17 02:14:36 +00002101 if (Result.isAmbiguous())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002102 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002103
John McCallf36e02d2009-10-09 21:13:30 +00002104 NamedDecl *MemberDecl = Result.getAsSingleDecl(Context);
2105
Douglas Gregora38c6872009-09-03 16:14:30 +00002106 if (SS && SS->isSet()) {
John McCallf36e02d2009-10-09 21:13:30 +00002107 TypeDecl* TyD = cast<TypeDecl>(MemberDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00002108 QualType BaseTypeCanon
Douglas Gregora38c6872009-09-03 16:14:30 +00002109 = Context.getCanonicalType(BaseType).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002110 QualType MemberTypeCanon
John McCallf36e02d2009-10-09 21:13:30 +00002111 = Context.getCanonicalType(Context.getTypeDeclType(TyD));
Mike Stump1eb44332009-09-09 15:08:12 +00002112
Douglas Gregora38c6872009-09-03 16:14:30 +00002113 if (BaseTypeCanon != MemberTypeCanon &&
2114 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2115 return ExprError(Diag(SS->getBeginLoc(),
2116 diag::err_not_direct_base_or_virtual)
2117 << MemberTypeCanon << BaseTypeCanon);
2118 }
Mike Stump1eb44332009-09-09 15:08:12 +00002119
Chris Lattner56cd21b2009-02-13 22:08:30 +00002120 // If the decl being referenced had an error, return an error for this
2121 // sub-expr without emitting another error, in order to avoid cascading
2122 // error cases.
2123 if (MemberDecl->isInvalidDecl())
2124 return ExprError();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002125
Anders Carlsson0f728562009-09-10 20:48:14 +00002126 bool ShouldCheckUse = true;
2127 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2128 // Don't diagnose the use of a virtual member function unless it's
2129 // explicitly qualified.
2130 if (MD->isVirtual() && (!SS || !SS->isSet()))
2131 ShouldCheckUse = false;
2132 }
Daniel Dunbar7e88a602009-09-17 06:31:17 +00002133
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002134 // Check the use of this field
Anders Carlsson0f728562009-09-10 20:48:14 +00002135 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002136 return ExprError();
Chris Lattner56cd21b2009-02-13 22:08:30 +00002137
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002138 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002139 // We may have found a field within an anonymous union or struct
2140 // (C++ [class.union]).
2141 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002142 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl0eb23302009-01-19 00:08:26 +00002143 BaseExpr, OpLoc);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002144
Douglas Gregor86f19402008-12-20 23:49:58 +00002145 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002146 QualType MemberType = FD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002147 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
Douglas Gregor86f19402008-12-20 23:49:58 +00002148 MemberType = Ref->getPointeeType();
2149 else {
John McCall0953e762009-09-24 19:53:00 +00002150 Qualifiers BaseQuals = BaseType.getQualifiers();
2151 BaseQuals.removeObjCGCAttr();
2152 if (FD->isMutable()) BaseQuals.removeConst();
2153
2154 Qualifiers MemberQuals
2155 = Context.getCanonicalType(MemberType).getQualifiers();
2156
2157 Qualifiers Combined = BaseQuals + MemberQuals;
2158 if (Combined != MemberQuals)
2159 MemberType = Context.getQualifiedType(MemberType, Combined);
Douglas Gregor86f19402008-12-20 23:49:58 +00002160 }
Eli Friedman51019072008-02-06 22:48:16 +00002161
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002162 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00002163 if (PerformObjectMemberConversion(BaseExpr, FD))
2164 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002165 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002166 FD, MemberLoc, MemberType));
Chris Lattnera3d25242009-03-31 08:18:48 +00002167 }
Mike Stump1eb44332009-09-09 15:08:12 +00002168
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002169 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2170 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002171 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2172 Var, MemberLoc,
2173 Var->getType().getNonReferenceType()));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002174 }
2175 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2176 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002177 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2178 MemberFn, MemberLoc,
2179 MemberFn->getType()));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002180 }
Mike Stump1eb44332009-09-09 15:08:12 +00002181 if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6b906862009-08-21 00:16:32 +00002182 = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2183 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00002184
John McCalld5532b62009-11-23 01:53:49 +00002185 if (ExplicitTemplateArgs)
Mike Stump1eb44332009-09-09 15:08:12 +00002186 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2187 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002188 SS? SS->getRange() : SourceRange(),
John McCalld5532b62009-11-23 01:53:49 +00002189 FunTmpl, MemberLoc,
2190 ExplicitTemplateArgs,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002191 Context.OverloadTy));
Mike Stump1eb44332009-09-09 15:08:12 +00002192
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002193 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2194 FunTmpl, MemberLoc,
2195 Context.OverloadTy));
Douglas Gregor6b906862009-08-21 00:16:32 +00002196 }
Chris Lattnera3d25242009-03-31 08:18:48 +00002197 if (OverloadedFunctionDecl *Ovl
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002198 = dyn_cast<OverloadedFunctionDecl>(MemberDecl)) {
John McCalld5532b62009-11-23 01:53:49 +00002199 if (ExplicitTemplateArgs)
Mike Stump1eb44332009-09-09 15:08:12 +00002200 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2201 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002202 SS? SS->getRange() : SourceRange(),
John McCalld5532b62009-11-23 01:53:49 +00002203 Ovl, MemberLoc, ExplicitTemplateArgs,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002204 Context.OverloadTy));
2205
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002206 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2207 Ovl, MemberLoc, Context.OverloadTy));
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002208 }
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002209 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2210 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002211 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2212 Enum, MemberLoc, Enum->getType()));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002213 }
Chris Lattnera3d25242009-03-31 08:18:48 +00002214 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002215 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002216 << MemberName << int(OpKind == tok::arrow));
Eli Friedman51019072008-02-06 22:48:16 +00002217
Douglas Gregor86f19402008-12-20 23:49:58 +00002218 // We found a declaration kind that we didn't expect. This is a
2219 // generic error message that tells the user that she can't refer
2220 // to this member with '.' or '->'.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002221 return ExprError(Diag(MemberLoc,
2222 diag::err_typecheck_member_reference_unknown)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002223 << MemberName << int(OpKind == tok::arrow));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002224 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002225
Douglas Gregora71d8192009-09-04 17:36:40 +00002226 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2227 // into a record type was handled above, any destructor we see here is a
2228 // pseudo-destructor.
2229 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2230 // C++ [expr.pseudo]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002231 // The left hand side of the dot operator shall be of scalar type. The
2232 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregora71d8192009-09-04 17:36:40 +00002233 // type.
2234 if (!BaseType->isScalarType())
2235 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2236 << BaseType << BaseExpr->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00002237
Douglas Gregora71d8192009-09-04 17:36:40 +00002238 // [...] The type designated by the pseudo-destructor-name shall be the
2239 // same as the object type.
2240 if (!MemberName.getCXXNameType()->isDependentType() &&
2241 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2242 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2243 << BaseType << MemberName.getCXXNameType()
2244 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00002245
2246 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregora71d8192009-09-04 17:36:40 +00002247 // the form
2248 //
Mike Stump1eb44332009-09-09 15:08:12 +00002249 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2250 //
Douglas Gregora71d8192009-09-04 17:36:40 +00002251 // shall designate the same scalar type.
2252 //
2253 // FIXME: DPG can't see any way to trigger this particular clause, so it
2254 // isn't checked here.
Mike Stump1eb44332009-09-09 15:08:12 +00002255
Douglas Gregora71d8192009-09-04 17:36:40 +00002256 // FIXME: We've lost the precise spelling of the type by going through
2257 // DeclarationName. Can we do better?
2258 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00002259 OpKind == tok::arrow,
Douglas Gregora71d8192009-09-04 17:36:40 +00002260 OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002261 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregora71d8192009-09-04 17:36:40 +00002262 SS? SS->getRange() : SourceRange(),
2263 MemberName.getCXXNameType(),
2264 MemberLoc));
2265 }
Mike Stump1eb44332009-09-09 15:08:12 +00002266
Chris Lattnera38e6b12008-07-21 04:59:05 +00002267 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2268 // (*Obj).ivar.
Steve Naroff14108da2009-07-10 23:34:53 +00002269 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2270 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
John McCall183700f2009-09-21 23:43:11 +00002271 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002272 const ObjCInterfaceType *IFaceT =
John McCall183700f2009-09-21 23:43:11 +00002273 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffc70e8d92009-07-16 00:25:06 +00002274 if (IFaceT) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002275 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2276
Steve Naroffc70e8d92009-07-16 00:25:06 +00002277 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2278 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson8f28f992009-08-26 18:25:21 +00002279 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump1eb44332009-09-09 15:08:12 +00002280
Steve Naroffc70e8d92009-07-16 00:25:06 +00002281 if (IV) {
2282 // If the decl being referenced had an error, return an error for this
2283 // sub-expr without emitting another error, in order to avoid cascading
2284 // error cases.
2285 if (IV->isInvalidDecl())
2286 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002287
Steve Naroffc70e8d92009-07-16 00:25:06 +00002288 // Check whether we can reference this field.
2289 if (DiagnoseUseOfDecl(IV, MemberLoc))
2290 return ExprError();
2291 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2292 IV->getAccessControl() != ObjCIvarDecl::Package) {
2293 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2294 if (ObjCMethodDecl *MD = getCurMethodDecl())
2295 ClassOfMethodDecl = MD->getClassInterface();
2296 else if (ObjCImpDecl && getCurFunctionDecl()) {
2297 // Case of a c-function declared inside an objc implementation.
2298 // FIXME: For a c-style function nested inside an objc implementation
2299 // class, there is no implementation context available, so we pass
2300 // down the context as argument to this routine. Ideally, this context
2301 // need be passed down in the AST node and somehow calculated from the
2302 // AST for a function decl.
2303 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump1eb44332009-09-09 15:08:12 +00002304 if (ObjCImplementationDecl *IMPD =
Steve Naroffc70e8d92009-07-16 00:25:06 +00002305 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2306 ClassOfMethodDecl = IMPD->getClassInterface();
2307 else if (ObjCCategoryImplDecl* CatImplClass =
2308 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2309 ClassOfMethodDecl = CatImplClass->getClassInterface();
2310 }
Mike Stump1eb44332009-09-09 15:08:12 +00002311
2312 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2313 if (ClassDeclared != IDecl ||
Steve Naroffc70e8d92009-07-16 00:25:06 +00002314 ClassOfMethodDecl != ClassDeclared)
Mike Stump1eb44332009-09-09 15:08:12 +00002315 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002316 << IV->getDeclName();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002317 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2318 // @protected
Mike Stump1eb44332009-09-09 15:08:12 +00002319 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002320 << IV->getDeclName();
Steve Naroffb06d8752009-03-04 18:34:24 +00002321 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002322
2323 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2324 MemberLoc, BaseExpr,
2325 OpKind == tok::arrow));
Fariborz Jahanian935fd762009-03-03 01:21:12 +00002326 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002327 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002328 << IDecl->getDeclName() << MemberName
Steve Naroffc70e8d92009-07-16 00:25:06 +00002329 << BaseExpr->getSourceRange());
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00002330 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002331 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00002332 // Handle properties on 'id' and qualified "id".
Mike Stump1eb44332009-09-09 15:08:12 +00002333 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
Steve Naroffde2e22d2009-07-15 18:40:39 +00002334 BaseType->isObjCQualifiedIdType())) {
John McCall183700f2009-09-21 23:43:11 +00002335 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002336 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002337
Steve Naroff14108da2009-07-10 23:34:53 +00002338 // Check protocols on qualified interfaces.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002339 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff14108da2009-07-10 23:34:53 +00002340 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2341 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2342 // Check the use of this declaration
2343 if (DiagnoseUseOfDecl(PD, MemberLoc))
2344 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002345
Steve Naroff14108da2009-07-10 23:34:53 +00002346 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2347 MemberLoc, BaseExpr));
2348 }
2349 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2350 // Check the use of this method.
2351 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2352 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002353
Steve Naroff14108da2009-07-10 23:34:53 +00002354 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump1eb44332009-09-09 15:08:12 +00002355 OMD->getResultType(),
2356 OMD, OpLoc, MemberLoc,
Steve Naroff14108da2009-07-10 23:34:53 +00002357 NULL, 0));
2358 }
2359 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002360
Steve Naroff14108da2009-07-10 23:34:53 +00002361 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002362 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00002363 }
Chris Lattnera38e6b12008-07-21 04:59:05 +00002364 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2365 // pointer to a (potentially qualified) interface type.
Steve Naroff14108da2009-07-10 23:34:53 +00002366 const ObjCObjectPointerType *OPT;
Mike Stump1eb44332009-09-09 15:08:12 +00002367 if (OpKind == tok::period &&
Steve Naroff14108da2009-07-10 23:34:53 +00002368 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2369 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2370 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002371 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002372
Daniel Dunbar2307d312008-09-03 01:05:41 +00002373 // Search for a declared property first.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002374 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002375 // Check whether we can reference this property.
2376 if (DiagnoseUseOfDecl(PD, MemberLoc))
2377 return ExprError();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002378 QualType ResTy = PD->getType();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002379 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002380 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianc001e892009-05-08 20:20:55 +00002381 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2382 ResTy = Getter->getResultType();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002383 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner7eba82e2009-02-16 18:35:08 +00002384 MemberLoc, BaseExpr));
2385 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002386 // Check protocols on qualified interfaces.
Steve Naroff67ef8ea2009-07-20 17:56:53 +00002387 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2388 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002389 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002390 // Check whether we can reference this property.
2391 if (DiagnoseUseOfDecl(PD, MemberLoc))
2392 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00002393
Steve Naroff6ece14c2009-01-21 00:14:39 +00002394 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00002395 MemberLoc, BaseExpr));
2396 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002397 // If that failed, look for an "implicit" property by seeing if the nullary
2398 // selector is implemented.
2399
2400 // FIXME: The logic for looking up nullary and unary selectors should be
2401 // shared with the code in ActOnInstanceMessage.
2402
Anders Carlsson8f28f992009-08-26 18:25:21 +00002403 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002404 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002405
Daniel Dunbar2307d312008-09-03 01:05:41 +00002406 // If this reference is in an @implementation, check for 'private' methods.
2407 if (!Getter)
Steve Naroffd789d3d2009-10-01 23:46:04 +00002408 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002409
Steve Naroff7692ed62008-10-22 19:16:27 +00002410 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002411 if (!Getter)
2412 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002413 if (Getter) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002414 // Check if we can reference this property.
2415 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2416 return ExprError();
Steve Naroff1ca66942009-03-11 13:48:17 +00002417 }
2418 // If we found a getter then this may be a valid dot-reference, we
2419 // will look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +00002420 Selector SetterSel =
2421 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson8f28f992009-08-26 18:25:21 +00002422 PP.getSelectorTable(), Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002423 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002424 if (!Setter) {
2425 // If this reference is in an @implementation, also check for 'private'
2426 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00002427 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002428 }
2429 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002430 if (!Setter)
2431 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002432
Steve Naroff1ca66942009-03-11 13:48:17 +00002433 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2434 return ExprError();
2435
2436 if (Getter || Setter) {
2437 QualType PType;
2438
2439 if (Getter)
2440 PType = Getter->getResultType();
Fariborz Jahanian154440e2009-08-18 20:50:23 +00002441 else
2442 // Get the expression type from Setter's incoming parameter.
2443 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1ca66942009-03-11 13:48:17 +00002444 // FIXME: we must check that the setter has property type.
Fariborz Jahanian09105f52009-08-20 17:02:02 +00002445 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1ca66942009-03-11 13:48:17 +00002446 Setter, MemberLoc, BaseExpr));
2447 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002448 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002449 << MemberName << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00002450 }
Mike Stump1eb44332009-09-09 15:08:12 +00002451
Steve Narofff242b1b2009-07-24 17:54:45 +00002452 // Handle the following exceptional case (*Obj).isa.
Mike Stump1eb44332009-09-09 15:08:12 +00002453 if (OpKind == tok::period &&
Steve Narofff242b1b2009-07-24 17:54:45 +00002454 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson8f28f992009-08-26 18:25:21 +00002455 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Narofff242b1b2009-07-24 17:54:45 +00002456 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2457 Context.getObjCIdType()));
2458
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002459 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00002460 if (BaseType->isExtVectorType()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002461 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002462 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2463 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002464 return ExprError();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002465 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002466 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002467 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002468
Douglas Gregor214f31a2009-03-27 06:00:30 +00002469 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2470 << BaseType << BaseExpr->getSourceRange();
2471
Douglas Gregor214f31a2009-03-27 06:00:30 +00002472 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002473}
2474
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002475Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg Base,
2476 SourceLocation OpLoc,
2477 tok::TokenKind OpKind,
2478 const CXXScopeSpec &SS,
2479 UnqualifiedId &Member,
2480 DeclPtrTy ObjCImpDecl,
2481 bool HasTrailingLParen) {
2482 if (Member.getKind() == UnqualifiedId::IK_TemplateId) {
2483 TemplateName Template
2484 = TemplateName::getFromVoidPointer(Member.TemplateId->Template);
2485
2486 // FIXME: We're going to end up looking up the template based on its name,
2487 // twice!
2488 DeclarationName Name;
2489 if (TemplateDecl *ActualTemplate = Template.getAsTemplateDecl())
2490 Name = ActualTemplate->getDeclName();
2491 else if (OverloadedFunctionDecl *Ovl = Template.getAsOverloadedFunctionDecl())
2492 Name = Ovl->getDeclName();
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002493 else {
2494 DependentTemplateName *DTN = Template.getAsDependentTemplateName();
2495 if (DTN->isIdentifier())
2496 Name = DTN->getIdentifier();
2497 else
2498 Name = Context.DeclarationNames.getCXXOperatorName(DTN->getOperator());
2499 }
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002500
2501 // Translate the parser's template argument list in our AST format.
2502 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2503 Member.TemplateId->getTemplateArgs(),
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002504 Member.TemplateId->NumArgs);
2505
John McCalld5532b62009-11-23 01:53:49 +00002506 TemplateArgumentListInfo TemplateArgs;
2507 TemplateArgs.setLAngleLoc(Member.TemplateId->LAngleLoc);
2508 TemplateArgs.setRAngleLoc(Member.TemplateId->RAngleLoc);
2509 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002510 TemplateArgsPtr.release();
2511
2512 // Do we have the save the actual template name? We might need it...
2513 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind,
2514 Member.TemplateId->TemplateNameLoc,
John McCalld5532b62009-11-23 01:53:49 +00002515 Name, &TemplateArgs, DeclPtrTy(),
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002516 &SS);
2517 }
2518
2519 // FIXME: We lose a lot of source information by mapping directly to the
2520 // DeclarationName.
2521 OwningExprResult Result
2522 = BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind,
2523 Member.getSourceRange().getBegin(),
2524 GetNameFromUnqualifiedId(Member),
2525 ObjCImpDecl, &SS);
2526
2527 if (Result.isInvalid() || HasTrailingLParen ||
2528 Member.getKind() != UnqualifiedId::IK_DestructorName)
2529 return move(Result);
2530
2531 // The only way a reference to a destructor can be used is to
2532 // immediately call them. Since the next token is not a '(', produce a
2533 // diagnostic and build the call now.
2534 Expr *E = (Expr *)Result.get();
2535 SourceLocation ExpectedLParenLoc
2536 = PP.getLocForEndOfToken(Member.getSourceRange().getEnd());
2537 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2538 << isa<CXXPseudoDestructorExpr>(E)
2539 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2540
2541 return ActOnCallExpr(0, move(Result), ExpectedLParenLoc,
2542 MultiExprArg(*this, 0, 0), 0, ExpectedLParenLoc);
Anders Carlsson8f28f992009-08-26 18:25:21 +00002543}
2544
Anders Carlsson56c5e332009-08-25 03:49:14 +00002545Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2546 FunctionDecl *FD,
2547 ParmVarDecl *Param) {
2548 if (Param->hasUnparsedDefaultArg()) {
2549 Diag (CallLoc,
2550 diag::err_use_of_default_argument_to_function_declared_later) <<
2551 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00002552 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson56c5e332009-08-25 03:49:14 +00002553 diag::note_default_argument_declared_here);
2554 } else {
2555 if (Param->hasUninstantiatedDefaultArg()) {
2556 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2557
2558 // Instantiate the expression.
Douglas Gregord6350ae2009-08-28 20:31:08 +00002559 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00002560
Mike Stump1eb44332009-09-09 15:08:12 +00002561 InstantiatingTemplate Inst(*this, CallLoc, Param,
2562 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregord6350ae2009-08-28 20:31:08 +00002563 ArgList.getInnermost().flat_size());
Anders Carlsson56c5e332009-08-25 03:49:14 +00002564
John McCallce3ff2b2009-08-25 22:02:44 +00002565 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump1eb44332009-09-09 15:08:12 +00002566 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00002567 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002568
2569 if (SetParamDefaultArgument(Param, move(Result),
Anders Carlsson56c5e332009-08-25 03:49:14 +00002570 /*FIXME:EqualLoc*/
2571 UninstExpr->getSourceRange().getBegin()))
2572 return ExprError();
2573 }
Mike Stump1eb44332009-09-09 15:08:12 +00002574
Anders Carlsson56c5e332009-08-25 03:49:14 +00002575 Expr *DefaultExpr = Param->getDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +00002576
Anders Carlsson56c5e332009-08-25 03:49:14 +00002577 // If the default expression creates temporaries, we need to
2578 // push them to the current stack of expression temporaries so they'll
2579 // be properly destroyed.
Mike Stump1eb44332009-09-09 15:08:12 +00002580 if (CXXExprWithTemporaries *E
Anders Carlsson56c5e332009-08-25 03:49:14 +00002581 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002582 assert(!E->shouldDestroyTemporaries() &&
Anders Carlsson56c5e332009-08-25 03:49:14 +00002583 "Can't destroy temporaries in a default argument expr!");
2584 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2585 ExprTemporaries.push_back(E->getTemporary(I));
2586 }
2587 }
2588
2589 // We already type-checked the argument, so we know it works.
2590 return Owned(CXXDefaultArgExpr::Create(Context, Param));
2591}
2592
Douglas Gregor88a35142008-12-22 05:46:06 +00002593/// ConvertArgumentsForCall - Converts the arguments specified in
2594/// Args/NumArgs to the parameter types of the function FDecl with
2595/// function prototype Proto. Call is the call expression itself, and
2596/// Fn is the function expression. For a C++ member function, this
2597/// routine does not attempt to convert the object argument. Returns
2598/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002599bool
2600Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00002601 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00002602 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00002603 Expr **Args, unsigned NumArgs,
2604 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002605 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00002606 // assignment, to the types of the corresponding parameter, ...
2607 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002608 bool Invalid = false;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002609
Douglas Gregor88a35142008-12-22 05:46:06 +00002610 // If too few arguments are available (and we don't have default
2611 // arguments for the remaining parameters), don't make the call.
2612 if (NumArgs < NumArgsInProto) {
2613 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2614 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2615 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00002616 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00002617 }
2618
2619 // If too many are passed and not variadic, error on the extras and drop
2620 // them.
2621 if (NumArgs > NumArgsInProto) {
2622 if (!Proto->isVariadic()) {
2623 Diag(Args[NumArgsInProto]->getLocStart(),
2624 diag::err_typecheck_call_too_many_args)
2625 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2626 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2627 Args[NumArgs-1]->getLocEnd());
2628 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002629 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002630 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002631 }
Douglas Gregor88a35142008-12-22 05:46:06 +00002632 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002633 llvm::SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00002634 VariadicCallType CallType =
2635 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
2636 if (Fn->getType()->isBlockPointerType())
2637 CallType = VariadicBlock; // Block
2638 else if (isa<MemberExpr>(Fn))
2639 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002640 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00002641 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002642 if (Invalid)
2643 return true;
2644 unsigned TotalNumArgs = AllArgs.size();
2645 for (unsigned i = 0; i < TotalNumArgs; ++i)
2646 Call->setArg(i, AllArgs[i]);
2647
2648 return false;
2649}
Mike Stumpeed9cac2009-02-19 03:04:26 +00002650
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002651bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
2652 FunctionDecl *FDecl,
2653 const FunctionProtoType *Proto,
2654 unsigned FirstProtoArg,
2655 Expr **Args, unsigned NumArgs,
2656 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00002657 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002658 unsigned NumArgsInProto = Proto->getNumArgs();
2659 unsigned NumArgsToCheck = NumArgs;
2660 bool Invalid = false;
2661 if (NumArgs != NumArgsInProto)
2662 // Use default arguments for missing arguments
2663 NumArgsToCheck = NumArgsInProto;
2664 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00002665 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002666 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002667 QualType ProtoArgType = Proto->getArgType(i);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002668
Douglas Gregor88a35142008-12-22 05:46:06 +00002669 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002670 if (ArgIx < NumArgs) {
2671 Arg = Args[ArgIx++];
2672
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002673 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2674 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002675 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002676 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002677 return true;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002678
Douglas Gregor61366e92008-12-24 00:01:03 +00002679 // Pass the argument.
2680 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2681 return true;
Anders Carlsson03d8ed42009-11-13 04:34:45 +00002682
Anders Carlsson4b3cbea2009-11-13 17:04:35 +00002683 if (!ProtoArgType->isReferenceType())
2684 Arg = MaybeBindToTemporary(Arg).takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00002685 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00002686 ParmVarDecl *Param = FDecl->getParamDecl(i);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002687
Mike Stump1eb44332009-09-09 15:08:12 +00002688 OwningExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002689 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00002690 if (ArgExpr.isInvalid())
2691 return true;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002692
Anders Carlsson56c5e332009-08-25 03:49:14 +00002693 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00002694 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002695 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00002696 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002697
Douglas Gregor88a35142008-12-22 05:46:06 +00002698 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00002699 if (CallType != VariadicDoesNotApply) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002700 // Promote the arguments (C99 6.5.2.2p7).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002701 for (unsigned i = ArgIx; i < NumArgs; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002702 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00002703 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00002704 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00002705 }
2706 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002707 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00002708}
2709
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002710/// \brief "Deconstruct" the function argument of a call expression to find
2711/// the underlying declaration (if any), the name of the called function,
2712/// whether argument-dependent lookup is available, whether it has explicit
2713/// template arguments, etc.
2714void Sema::DeconstructCallFunction(Expr *FnExpr,
John McCallba135432009-11-21 08:51:07 +00002715 llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002716 DeclarationName &Name,
2717 NestedNameSpecifier *&Qualifier,
2718 SourceRange &QualifierRange,
2719 bool &ArgumentDependentLookup,
John McCall7453ed42009-11-22 00:44:51 +00002720 bool &Overloaded,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002721 bool &HasExplicitTemplateArguments,
John McCalld5532b62009-11-23 01:53:49 +00002722 TemplateArgumentListInfo &ExplicitTemplateArgs) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002723 // Set defaults for all of the output parameters.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002724 Name = DeclarationName();
2725 Qualifier = 0;
2726 QualifierRange = SourceRange();
John McCallf7a1a742009-11-24 19:00:30 +00002727 ArgumentDependentLookup = false;
John McCall7453ed42009-11-22 00:44:51 +00002728 Overloaded = false;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002729 HasExplicitTemplateArguments = false;
John McCall7453ed42009-11-22 00:44:51 +00002730
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002731 // If we're directly calling a function, get the appropriate declaration.
2732 // Also, in C++, keep track of whether we should perform argument-dependent
2733 // lookup and whether there were any explicitly-specified template arguments.
2734 while (true) {
2735 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2736 FnExpr = IcExpr->getSubExpr();
2737 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002738 FnExpr = PExpr->getSubExpr();
2739 } else if (isa<UnaryOperator>(FnExpr) &&
2740 cast<UnaryOperator>(FnExpr)->getOpcode()
2741 == UnaryOperator::AddrOf) {
2742 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002743 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
John McCallba135432009-11-21 08:51:07 +00002744 Fns.push_back(cast<NamedDecl>(DRExpr->getDecl()));
2745 ArgumentDependentLookup = false;
2746 if ((Qualifier = DRExpr->getQualifier()))
Douglas Gregora2813ce2009-10-23 18:54:35 +00002747 QualifierRange = DRExpr->getQualifierRange();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002748 break;
John McCallba135432009-11-21 08:51:07 +00002749 } else if (UnresolvedLookupExpr *UnresLookup
2750 = dyn_cast<UnresolvedLookupExpr>(FnExpr)) {
2751 Name = UnresLookup->getName();
2752 Fns.append(UnresLookup->decls_begin(), UnresLookup->decls_end());
2753 ArgumentDependentLookup = UnresLookup->requiresADL();
John McCall7453ed42009-11-22 00:44:51 +00002754 Overloaded = UnresLookup->isOverloaded();
John McCallba135432009-11-21 08:51:07 +00002755 if ((Qualifier = UnresLookup->getQualifier()))
2756 QualifierRange = UnresLookup->getQualifierRange();
John McCallf7a1a742009-11-24 19:00:30 +00002757 if (UnresLookup->hasExplicitTemplateArgs()) {
2758 HasExplicitTemplateArguments = true;
2759 UnresLookup->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002760 }
2761 break;
2762 } else {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002763 break;
2764 }
2765 }
2766}
2767
Steve Narofff69936d2007-09-16 03:34:24 +00002768/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00002769/// This provides the location of the left/right parens and a list of comma
2770/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002771Action::OwningExprResult
2772Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2773 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00002774 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00002775 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00002776
2777 // Since this might be a postfix expression, get rid of ParenListExprs.
2778 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump1eb44332009-09-09 15:08:12 +00002779
Anders Carlssonf1b1d592009-05-01 19:30:39 +00002780 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl0eb23302009-01-19 00:08:26 +00002781 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00002782 assert(Fn && "no function call expression");
Mike Stump1eb44332009-09-09 15:08:12 +00002783
Douglas Gregor88a35142008-12-22 05:46:06 +00002784 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00002785 // If this is a pseudo-destructor expression, build the call immediately.
2786 if (isa<CXXPseudoDestructorExpr>(Fn)) {
2787 if (NumArgs > 0) {
2788 // Pseudo-destructor calls should not have any arguments.
2789 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
2790 << CodeModificationHint::CreateRemoval(
2791 SourceRange(Args[0]->getLocStart(),
2792 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00002793
Douglas Gregora71d8192009-09-04 17:36:40 +00002794 for (unsigned I = 0; I != NumArgs; ++I)
2795 Args[I]->Destroy(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002796
Douglas Gregora71d8192009-09-04 17:36:40 +00002797 NumArgs = 0;
2798 }
Mike Stump1eb44332009-09-09 15:08:12 +00002799
Douglas Gregora71d8192009-09-04 17:36:40 +00002800 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
2801 RParenLoc));
2802 }
Mike Stump1eb44332009-09-09 15:08:12 +00002803
Douglas Gregor17330012009-02-04 15:01:18 +00002804 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00002805 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00002806 // FIXME: Will need to cache the results of name lookup (including ADL) in
2807 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00002808 bool Dependent = false;
2809 if (Fn->isTypeDependent())
2810 Dependent = true;
2811 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2812 Dependent = true;
2813
2814 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00002815 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00002816 Context.DependentTy, RParenLoc));
2817
2818 // Determine whether this is a call to an object (C++ [over.call.object]).
2819 if (Fn->getType()->isRecordType())
2820 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2821 CommaLocs, RParenLoc));
2822
Douglas Gregorfa047642009-02-04 00:32:51 +00002823 // Determine whether this is a call to a member function.
Douglas Gregore53060f2009-06-25 22:08:12 +00002824 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2825 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2826 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2827 isa<CXXMethodDecl>(MemDecl) ||
2828 (isa<FunctionTemplateDecl>(MemDecl) &&
2829 isa<CXXMethodDecl>(
2830 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002831 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2832 CommaLocs, RParenLoc));
Douglas Gregore53060f2009-06-25 22:08:12 +00002833 }
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002834
2835 // Determine whether this is a call to a pointer-to-member function.
2836 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Fn->IgnoreParens())) {
2837 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
2838 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002839 if (const FunctionProtoType *FPT =
2840 dyn_cast<FunctionProtoType>(BO->getType())) {
2841 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002842
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002843 ExprOwningPtr<CXXMemberCallExpr>
2844 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
2845 NumArgs, ResultTy,
2846 RParenLoc));
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002847
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002848 if (CheckCallReturnType(FPT->getResultType(),
2849 BO->getRHS()->getSourceRange().getBegin(),
2850 TheCall.get(), 0))
2851 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00002852
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002853 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
2854 RParenLoc))
2855 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002856
Fariborz Jahanian5de24502009-10-28 16:49:46 +00002857 return Owned(MaybeBindToTemporary(TheCall.release()).release());
2858 }
2859 return ExprError(Diag(Fn->getLocStart(),
2860 diag::err_typecheck_call_not_function)
2861 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00002862 }
2863 }
Douglas Gregor88a35142008-12-22 05:46:06 +00002864 }
2865
Douglas Gregorfa047642009-02-04 00:32:51 +00002866 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002867 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002868 // lookup and whether there were any explicitly-specified template arguments.
John McCallba135432009-11-21 08:51:07 +00002869 llvm::SmallVector<NamedDecl*,8> Fns;
2870 DeclarationName UnqualifiedName;
John McCall7453ed42009-11-22 00:44:51 +00002871 bool Overloaded;
2872 bool ADL;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002873 bool HasExplicitTemplateArgs = 0;
John McCalld5532b62009-11-23 01:53:49 +00002874 TemplateArgumentListInfo ExplicitTemplateArgs;
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002875 NestedNameSpecifier *Qualifier = 0;
2876 SourceRange QualifierRange;
John McCallba135432009-11-21 08:51:07 +00002877 DeconstructCallFunction(Fn, Fns, UnqualifiedName, Qualifier, QualifierRange,
John McCall7453ed42009-11-22 00:44:51 +00002878 ADL, Overloaded, HasExplicitTemplateArgs,
John McCalld5532b62009-11-23 01:53:49 +00002879 ExplicitTemplateArgs);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002880
John McCall7453ed42009-11-22 00:44:51 +00002881 NamedDecl *NDecl; // the specific declaration we're calling, if applicable
2882 FunctionDecl *FDecl; // same, if it's known to be a function
John McCallba135432009-11-21 08:51:07 +00002883
John McCall7453ed42009-11-22 00:44:51 +00002884 if (Overloaded || ADL) {
2885#ifndef NDEBUG
2886 if (ADL) {
2887 // To do ADL, we must have found an unqualified name.
2888 assert(UnqualifiedName && "found no unqualified name for ADL");
2889
2890 // We don't perform ADL for implicit declarations of builtins.
2891 // Verify that this was correctly set up.
2892 if (Fns.size() == 1 && (FDecl = dyn_cast<FunctionDecl>(Fns[0])) &&
2893 FDecl->getBuiltinID() && FDecl->isImplicit())
2894 assert(0 && "performing ADL for builtin");
2895
2896 // We don't perform ADL in C.
2897 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
2898 }
2899
2900 if (Overloaded) {
2901 // To be overloaded, we must either have multiple functions or
2902 // at least one function template (which is effectively an
2903 // infinite set of functions).
2904 assert((Fns.size() > 1 ||
2905 (Fns.size() == 1 &&
2906 isa<FunctionTemplateDecl>(Fns[0]->getUnderlyingDecl())))
2907 && "unrecognized overload situation");
2908 }
2909#endif
2910
2911 FDecl = ResolveOverloadedCallFn(Fn, Fns, UnqualifiedName,
John McCalld5532b62009-11-23 01:53:49 +00002912 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
John McCall7453ed42009-11-22 00:44:51 +00002913 LParenLoc, Args, NumArgs, CommaLocs,
2914 RParenLoc, ADL);
2915 if (!FDecl)
2916 return ExprError();
2917
2918 Fn = FixOverloadedFunctionReference(Fn, FDecl);
2919
2920 NDecl = FDecl;
2921 } else {
2922 assert(Fns.size() <= 1 && "overloaded without Overloaded flag");
2923 if (Fns.empty())
2924 NDecl = FDecl = 0;
2925 else {
2926 NDecl = Fns[0];
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002927 FDecl = dyn_cast<FunctionDecl>(NDecl);
Douglas Gregorfa047642009-02-04 00:32:51 +00002928 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002929 }
Chris Lattner04421082008-04-08 04:40:51 +00002930
2931 // Promote the function operand.
2932 UsualUnaryConversions(Fn);
2933
Chris Lattner925e60d2007-12-28 05:29:59 +00002934 // Make the call expr early, before semantic checks. This guarantees cleanup
2935 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00002936 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2937 Args, NumArgs,
2938 Context.BoolTy,
2939 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00002940
Steve Naroffdd972f22008-09-05 22:11:13 +00002941 const FunctionType *FuncT;
2942 if (!Fn->getType()->isBlockPointerType()) {
2943 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2944 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00002945 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00002946 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002947 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2948 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00002949 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00002950 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00002951 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00002952 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00002953 }
Chris Lattner925e60d2007-12-28 05:29:59 +00002954 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002955 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2956 << Fn->getType() << Fn->getSourceRange());
2957
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002958 // Check for a valid return type
Anders Carlsson8c8d9192009-10-09 23:51:55 +00002959 if (CheckCallReturnType(FuncT->getResultType(),
2960 Fn->getSourceRange().getBegin(), TheCall.get(),
2961 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002962 return ExprError();
2963
Chris Lattner925e60d2007-12-28 05:29:59 +00002964 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00002965 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002966
Douglas Gregor72564e72009-02-26 23:50:07 +00002967 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002968 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00002969 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002970 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00002971 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00002972 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002973
Douglas Gregor74734d52009-04-02 15:37:10 +00002974 if (FDecl) {
2975 // Check if we have too few/too many template arguments, based
2976 // on our knowledge of the function definition.
2977 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002978 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002979 const FunctionProtoType *Proto =
John McCall183700f2009-09-21 23:43:11 +00002980 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002981 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2982 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2983 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2984 }
2985 }
Douglas Gregor74734d52009-04-02 15:37:10 +00002986 }
2987
Steve Naroffb291ab62007-08-28 23:30:39 +00002988 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00002989 for (unsigned i = 0; i != NumArgs; i++) {
2990 Expr *Arg = Args[i];
2991 DefaultArgumentPromotion(Arg);
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002992 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2993 Arg->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00002994 PDiag(diag::err_call_incomplete_argument)
2995 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002996 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00002997 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00002998 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002999 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003000
Douglas Gregor88a35142008-12-22 05:46:06 +00003001 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3002 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003003 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3004 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003005
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003006 // Check for sentinels
3007 if (NDecl)
3008 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003009
Chris Lattner59907c42007-08-10 20:18:51 +00003010 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003011 if (FDecl) {
3012 if (CheckFunctionCall(FDecl, TheCall.get()))
3013 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003014
Douglas Gregor7814e6d2009-09-12 00:22:50 +00003015 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssond406bf02009-08-16 01:56:34 +00003016 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3017 } else if (NDecl) {
3018 if (CheckBlockCall(NDecl, TheCall.get()))
3019 return ExprError();
3020 }
Chris Lattner59907c42007-08-10 20:18:51 +00003021
Anders Carlssonec74c592009-08-16 03:06:32 +00003022 return MaybeBindToTemporary(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00003023}
3024
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003025Action::OwningExprResult
3026Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3027 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003028 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003029 //FIXME: Preserve type source info.
3030 QualType literalType = GetTypeFromParser(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00003031 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003032 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003033 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00003034
Eli Friedman6223c222008-05-20 05:22:08 +00003035 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003036 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003037 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3038 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003039 } else if (!literalType->isDependentType() &&
3040 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003041 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003042 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003043 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003044 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003045
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003046 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003047 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003048 return ExprError();
Steve Naroffe9b12192008-01-14 18:19:28 +00003049
Chris Lattner371f2582008-12-04 23:50:19 +00003050 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003051 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003052 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003053 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003054 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003055 InitExpr.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003056 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003057 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003058}
3059
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003060Action::OwningExprResult
3061Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003062 SourceLocation RBraceLoc) {
3063 unsigned NumInit = initlist.size();
3064 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003065
Steve Naroff08d92e42007-09-15 18:49:24 +00003066 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003067 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003068
Mike Stumpeed9cac2009-02-19 03:04:26 +00003069 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00003070 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003071 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003072 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003073}
3074
Anders Carlsson82debc72009-10-18 18:12:03 +00003075static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3076 QualType SrcTy, QualType DestTy) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003077 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson82debc72009-10-18 18:12:03 +00003078 return CastExpr::CK_NoOp;
3079
3080 if (SrcTy->hasPointerRepresentation()) {
3081 if (DestTy->hasPointerRepresentation())
3082 return CastExpr::CK_BitCast;
3083 if (DestTy->isIntegerType())
3084 return CastExpr::CK_PointerToIntegral;
3085 }
3086
3087 if (SrcTy->isIntegerType()) {
3088 if (DestTy->isIntegerType())
3089 return CastExpr::CK_IntegralCast;
3090 if (DestTy->hasPointerRepresentation())
3091 return CastExpr::CK_IntegralToPointer;
3092 if (DestTy->isRealFloatingType())
3093 return CastExpr::CK_IntegralToFloating;
3094 }
3095
3096 if (SrcTy->isRealFloatingType()) {
3097 if (DestTy->isRealFloatingType())
3098 return CastExpr::CK_FloatingCast;
3099 if (DestTy->isIntegerType())
3100 return CastExpr::CK_FloatingToIntegral;
3101 }
3102
3103 // FIXME: Assert here.
3104 // assert(false && "Unhandled cast combination!");
3105 return CastExpr::CK_Unknown;
3106}
3107
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003108/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00003109bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00003110 CastExpr::CastKind& Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003111 CXXMethodDecl *& ConversionDecl,
3112 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003113 if (getLangOptions().CPlusPlus)
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003114 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3115 ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003116
Eli Friedman199ea952009-08-15 19:02:19 +00003117 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003118
3119 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3120 // type needs to be scalar.
3121 if (castType->isVoidType()) {
3122 // Cast to void allows any expr type.
Anders Carlssonebeaf202009-10-16 02:35:04 +00003123 Kind = CastExpr::CK_ToVoid;
3124 return false;
3125 }
3126
3127 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003128 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003129 (castType->isStructureType() || castType->isUnionType())) {
3130 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003131 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003132 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3133 << castType << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003134 Kind = CastExpr::CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00003135 return false;
3136 }
3137
3138 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003139 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00003140 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003141 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003142 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003143 Field != FieldEnd; ++Field) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003144 if (Context.hasSameUnqualifiedType(Field->getType(),
3145 castExpr->getType())) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003146 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3147 << castExpr->getSourceRange();
3148 break;
3149 }
3150 }
3151 if (Field == FieldEnd)
3152 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3153 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003154 Kind = CastExpr::CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00003155 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003156 }
Anders Carlssonc3516322009-10-16 02:48:28 +00003157
3158 // Reject any other conversions to non-scalar types.
3159 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3160 << castType << castExpr->getSourceRange();
3161 }
3162
3163 if (!castExpr->getType()->isScalarType() &&
3164 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003165 return Diag(castExpr->getLocStart(),
3166 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003167 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00003168 }
3169
Anders Carlsson16a89042009-10-16 05:23:41 +00003170 if (castType->isExtVectorType())
3171 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3172
Anders Carlssonc3516322009-10-16 02:48:28 +00003173 if (castType->isVectorType())
3174 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3175 if (castExpr->getType()->isVectorType())
3176 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3177
3178 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffa0c3e9c2009-04-08 23:52:26 +00003179 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlssonc3516322009-10-16 02:48:28 +00003180
Anders Carlsson16a89042009-10-16 05:23:41 +00003181 if (isa<ObjCSelectorExpr>(castExpr))
3182 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3183
Anders Carlssonc3516322009-10-16 02:48:28 +00003184 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00003185 QualType castExprType = castExpr->getType();
3186 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3187 return Diag(castExpr->getLocStart(),
3188 diag::err_cast_pointer_from_non_pointer_int)
3189 << castExprType << castExpr->getSourceRange();
3190 } else if (!castExpr->getType()->isArithmeticType()) {
3191 if (!castType->isIntegralType() && castType->isArithmeticType())
3192 return Diag(castExpr->getLocStart(),
3193 diag::err_cast_pointer_to_non_pointer_int)
3194 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003195 }
Anders Carlsson82debc72009-10-18 18:12:03 +00003196
3197 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003198 return false;
3199}
3200
Anders Carlssonc3516322009-10-16 02:48:28 +00003201bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3202 CastExpr::CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00003203 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00003204
Anders Carlssona64db8f2007-11-27 05:51:55 +00003205 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00003206 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00003207 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00003208 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00003209 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003210 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003211 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003212 } else
3213 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003214 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00003215 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003216
Anders Carlssonc3516322009-10-16 02:48:28 +00003217 Kind = CastExpr::CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003218 return false;
3219}
3220
Anders Carlsson16a89042009-10-16 05:23:41 +00003221bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3222 CastExpr::CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00003223 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson16a89042009-10-16 05:23:41 +00003224
3225 QualType SrcTy = CastExpr->getType();
3226
Nate Begeman9b10da62009-06-27 22:05:55 +00003227 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3228 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00003229 if (SrcTy->isVectorType()) {
3230 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3231 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3232 << DestTy << SrcTy << R;
Anders Carlsson16a89042009-10-16 05:23:41 +00003233 Kind = CastExpr::CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00003234 return false;
3235 }
3236
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003237 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00003238 // conversion will take place first from scalar to elt type, and then
3239 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003240 if (SrcTy->isPointerType())
3241 return Diag(R.getBegin(),
3242 diag::err_invalid_conversion_between_vector_and_scalar)
3243 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00003244
3245 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3246 ImpCastExprToType(CastExpr, DestElemTy,
3247 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson16a89042009-10-16 05:23:41 +00003248
3249 Kind = CastExpr::CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00003250 return false;
3251}
3252
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003253Action::OwningExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00003254Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003255 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssoncdb61972009-08-07 22:21:05 +00003256 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump1eb44332009-09-09 15:08:12 +00003257
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003258 assert((Ty != 0) && (Op.get() != 0) &&
3259 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00003260
Nate Begeman2ef13e52009-08-10 23:49:36 +00003261 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003262 //FIXME: Preserve type source info.
3263 QualType castType = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003264
Nate Begeman2ef13e52009-08-10 23:49:36 +00003265 // If the Expr being casted is a ParenListExpr, handle it specially.
3266 if (isa<ParenListExpr>(castExpr))
3267 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlsson0aebc812009-09-09 21:33:21 +00003268 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003269 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003270 Kind, Method))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003271 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00003272
3273 if (Method) {
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003274 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003275 Method, move(Op));
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003276
Anders Carlsson0aebc812009-09-09 21:33:21 +00003277 if (CastArg.isInvalid())
3278 return ExprError();
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003279
Anders Carlsson0aebc812009-09-09 21:33:21 +00003280 castExpr = CastArg.takeAs<Expr>();
3281 } else {
3282 Op.release();
Fariborz Jahanian31976592009-08-29 19:15:16 +00003283 }
Mike Stump1eb44332009-09-09 15:08:12 +00003284
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003285 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump1eb44332009-09-09 15:08:12 +00003286 Kind, castExpr, castType,
Anders Carlssoncdb61972009-08-07 22:21:05 +00003287 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003288}
3289
Nate Begeman2ef13e52009-08-10 23:49:36 +00003290/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3291/// of comma binary operators.
3292Action::OwningExprResult
3293Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3294 Expr *expr = EA.takeAs<Expr>();
3295 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3296 if (!E)
3297 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00003298
Nate Begeman2ef13e52009-08-10 23:49:36 +00003299 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00003300
Nate Begeman2ef13e52009-08-10 23:49:36 +00003301 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3302 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3303 Owned(E->getExpr(i)));
Mike Stump1eb44332009-09-09 15:08:12 +00003304
Nate Begeman2ef13e52009-08-10 23:49:36 +00003305 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3306}
3307
3308Action::OwningExprResult
3309Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3310 SourceLocation RParenLoc, ExprArg Op,
3311 QualType Ty) {
3312 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003313
3314 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman2ef13e52009-08-10 23:49:36 +00003315 // then handle it as such.
3316 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3317 if (PE->getNumExprs() == 0) {
3318 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3319 return ExprError();
3320 }
3321
3322 llvm::SmallVector<Expr *, 8> initExprs;
3323 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3324 initExprs.push_back(PE->getExpr(i));
3325
3326 // FIXME: This means that pretty-printing the final AST will produce curly
3327 // braces instead of the original commas.
3328 Op.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003329 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00003330 initExprs.size(), RParenLoc);
3331 E->setType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003332 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003333 Owned(E));
3334 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003335 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00003336 // sequence of BinOp comma operators.
3337 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3338 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3339 }
3340}
3341
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003342Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003343 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003344 MultiExprArg Val,
3345 TypeTy *TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003346 unsigned nexprs = Val.size();
3347 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003348 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
3349 Expr *expr;
3350 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
3351 expr = new (Context) ParenExpr(L, R, exprs[0]);
3352 else
3353 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00003354 return Owned(expr);
3355}
3356
Sebastian Redl28507842009-02-26 14:39:58 +00003357/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3358/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00003359/// C99 6.5.15
3360QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3361 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003362 // C++ is sufficiently different to merit its own checker.
3363 if (getLangOptions().CPlusPlus)
3364 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3365
John McCallb13c87f2009-11-05 09:23:39 +00003366 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
3367
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003368 UsualUnaryConversions(Cond);
3369 UsualUnaryConversions(LHS);
3370 UsualUnaryConversions(RHS);
3371 QualType CondTy = Cond->getType();
3372 QualType LHSTy = LHS->getType();
3373 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003374
Reid Spencer5f016e22007-07-11 17:01:13 +00003375 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003376 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3377 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3378 << CondTy;
3379 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003380 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003381
Chris Lattner70d67a92008-01-06 22:42:25 +00003382 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00003383 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3384 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00003385
Chris Lattner70d67a92008-01-06 22:42:25 +00003386 // If both operands have arithmetic type, do the usual arithmetic conversions
3387 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003388 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3389 UsualArithmeticConversions(LHS, RHS);
3390 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00003391 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003392
Chris Lattner70d67a92008-01-06 22:42:25 +00003393 // If both operands are the same structure or union type, the result is that
3394 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003395 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3396 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00003397 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00003398 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00003399 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003400 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003401 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00003402 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003403
Chris Lattner70d67a92008-01-06 22:42:25 +00003404 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00003405 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003406 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3407 if (!LHSTy->isVoidType())
3408 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3409 << RHS->getSourceRange();
3410 if (!RHSTy->isVoidType())
3411 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3412 << LHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003413 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
3414 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00003415 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00003416 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00003417 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3418 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003419 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00003420 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003421 // promote the null to a pointer.
3422 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003423 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003424 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003425 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00003426 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003427 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003428 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003429 }
David Chisnall0f436562009-08-17 16:35:33 +00003430 // Handle things like Class and struct objc_class*. Here we case the result
3431 // to the pseudo-builtin, because that will be implicitly cast back to the
3432 // redefinition type if an attempt is made to access its fields.
3433 if (LHSTy->isObjCClassType() &&
3434 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003435 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003436 return LHSTy;
3437 }
3438 if (RHSTy->isObjCClassType() &&
3439 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003440 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003441 return RHSTy;
3442 }
3443 // And the same for struct objc_object* / id
3444 if (LHSTy->isObjCIdType() &&
3445 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003446 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003447 return LHSTy;
3448 }
3449 if (RHSTy->isObjCIdType() &&
3450 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00003451 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00003452 return RHSTy;
3453 }
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +00003454 // And the same for struct objc_selector* / SEL
3455 if (Context.isObjCSelType(LHSTy) &&
3456 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
3457 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
3458 return LHSTy;
3459 }
3460 if (Context.isObjCSelType(RHSTy) &&
3461 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
3462 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
3463 return RHSTy;
3464 }
Steve Naroff7154a772009-07-01 14:36:47 +00003465 // Handle block pointer types.
3466 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3467 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3468 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3469 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003470 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
3471 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003472 return destType;
3473 }
3474 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3475 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3476 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00003477 }
Steve Naroff7154a772009-07-01 14:36:47 +00003478 // We have 2 block pointer types.
3479 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3480 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00003481 return LHSTy;
3482 }
Steve Naroff7154a772009-07-01 14:36:47 +00003483 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00003484 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3485 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003486
Steve Naroff7154a772009-07-01 14:36:47 +00003487 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3488 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00003489 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3490 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3491 // In this situation, we assume void* type. No especially good
3492 // reason, but this is what gcc does, and we do have to pick
3493 // to get a consistent AST.
3494 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003495 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3496 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00003497 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003498 }
Steve Naroff7154a772009-07-01 14:36:47 +00003499 // The block pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003500 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3501 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00003502 return LHSTy;
3503 }
Steve Naroff7154a772009-07-01 14:36:47 +00003504 // Check constraints for Objective-C object pointers types.
Steve Naroff14108da2009-07-10 23:34:53 +00003505 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003506
Steve Naroff7154a772009-07-01 14:36:47 +00003507 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3508 // Two identical object pointer types are always compatible.
3509 return LHSTy;
3510 }
John McCall183700f2009-09-21 23:43:11 +00003511 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
3512 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
Steve Naroff7154a772009-07-01 14:36:47 +00003513 QualType compositeType = LHSTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003514
Steve Naroff7154a772009-07-01 14:36:47 +00003515 // If both operands are interfaces and either operand can be
3516 // assigned to the other, use that type as the composite
3517 // type. This allows
3518 // xxx ? (A*) a : (B*) b
3519 // where B is a subclass of A.
3520 //
3521 // Additionally, as for assignment, if either type is 'id'
3522 // allow silent coercion. Finally, if the types are
3523 // incompatible then make sure to use 'id' as the composite
3524 // type so the result is acceptable for sending messages to.
3525
3526 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3527 // It could return the composite type.
Steve Naroff14108da2009-07-10 23:34:53 +00003528 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahanian9ec22a32009-08-22 22:27:17 +00003529 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff14108da2009-07-10 23:34:53 +00003530 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahanian9ec22a32009-08-22 22:27:17 +00003531 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003532 } else if ((LHSTy->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00003533 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff4084c302009-07-23 01:01:38 +00003534 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003535 // Need to handle "id<xx>" explicitly.
Steve Naroff14108da2009-07-10 23:34:53 +00003536 // GCC allows qualified id and any Objective-C type to devolve to
3537 // id. Currently localizing to here until clear this should be
3538 // part of ObjCQualifiedIdTypesAreCompatible.
3539 compositeType = Context.getObjCIdType();
3540 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff7154a772009-07-01 14:36:47 +00003541 compositeType = Context.getObjCIdType();
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00003542 } else if (!(compositeType =
3543 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
3544 ;
3545 else {
Steve Naroff7154a772009-07-01 14:36:47 +00003546 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3547 << LHSTy << RHSTy
3548 << LHS->getSourceRange() << RHS->getSourceRange();
3549 QualType incompatTy = Context.getObjCIdType();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003550 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3551 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003552 return incompatTy;
3553 }
3554 // The object pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003555 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
3556 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003557 return compositeType;
3558 }
Steve Naroffc715e782009-07-29 15:09:39 +00003559 // Check Objective-C object pointer types and 'void *'
3560 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003561 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003562 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00003563 QualType destPointee
3564 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroffc715e782009-07-29 15:09:39 +00003565 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003566 // Add qualifiers if necessary.
3567 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3568 // Promote to void*.
3569 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroffc715e782009-07-29 15:09:39 +00003570 return destType;
3571 }
3572 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
John McCall183700f2009-09-21 23:43:11 +00003573 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003574 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00003575 QualType destPointee
3576 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroffc715e782009-07-29 15:09:39 +00003577 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003578 // Add qualifiers if necessary.
3579 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
3580 // Promote to void*.
3581 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroffc715e782009-07-29 15:09:39 +00003582 return destType;
3583 }
Steve Naroff7154a772009-07-01 14:36:47 +00003584 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3585 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3586 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00003587 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3588 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00003589
3590 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3591 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3592 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00003593 QualType destPointee
3594 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00003595 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003596 // Add qualifiers if necessary.
3597 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3598 // Promote to void*.
3599 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003600 return destType;
3601 }
3602 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00003603 QualType destPointee
3604 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00003605 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003606 // Add qualifiers if necessary.
Eli Friedman16fea9b2009-11-17 01:22:05 +00003607 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003608 // Promote to void*.
Eli Friedman16fea9b2009-11-17 01:22:05 +00003609 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003610 return destType;
3611 }
3612
3613 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3614 // Two identical pointer types are always compatible.
3615 return LHSTy;
3616 }
3617 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3618 rhptee.getUnqualifiedType())) {
3619 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3620 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3621 // In this situation, we assume void* type. No especially good
3622 // reason, but this is what gcc does, and we do have to pick
3623 // to get a consistent AST.
3624 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00003625 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3626 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003627 return incompatTy;
3628 }
3629 // The pointer types are compatible.
3630 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3631 // differently qualified versions of compatible types, the result type is
3632 // a pointer to an appropriately qualified version of the *composite*
3633 // type.
3634 // FIXME: Need to calculate the composite type.
3635 // FIXME: Need to add qualifiers
Eli Friedman73c39ab2009-10-20 08:27:19 +00003636 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3637 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00003638 return LHSTy;
3639 }
Mike Stump1eb44332009-09-09 15:08:12 +00003640
Steve Naroff7154a772009-07-01 14:36:47 +00003641 // GCC compatibility: soften pointer/integer mismatch.
3642 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3643 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3644 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003645 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00003646 return RHSTy;
3647 }
3648 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3649 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3650 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00003651 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00003652 return LHSTy;
3653 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00003654
Chris Lattner70d67a92008-01-06 22:42:25 +00003655 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003656 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3657 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003658 return QualType();
3659}
3660
Steve Narofff69936d2007-09-16 03:34:24 +00003661/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00003662/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003663Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3664 SourceLocation ColonLoc,
3665 ExprArg Cond, ExprArg LHS,
3666 ExprArg RHS) {
3667 Expr *CondExpr = (Expr *) Cond.get();
3668 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00003669
3670 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3671 // was the condition.
3672 bool isLHSNull = LHSExpr == 0;
3673 if (isLHSNull)
3674 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003675
3676 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00003677 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00003678 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003679 return ExprError();
3680
3681 Cond.release();
3682 LHS.release();
3683 RHS.release();
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003684 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003685 isLHSNull ? 0 : LHSExpr,
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003686 ColonLoc, RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00003687}
3688
Reid Spencer5f016e22007-07-11 17:01:13 +00003689// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00003690// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00003691// routine is it effectively iqnores the qualifiers on the top level pointee.
3692// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3693// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003694Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00003695Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3696 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003697
David Chisnall0f436562009-08-17 16:35:33 +00003698 if ((lhsType->isObjCClassType() &&
3699 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3700 (rhsType->isObjCClassType() &&
3701 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3702 return Compatible;
3703 }
3704
Reid Spencer5f016e22007-07-11 17:01:13 +00003705 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00003706 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3707 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003708
Reid Spencer5f016e22007-07-11 17:01:13 +00003709 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00003710 lhptee = Context.getCanonicalType(lhptee);
3711 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00003712
Chris Lattner5cf216b2008-01-04 18:04:52 +00003713 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003714
3715 // C99 6.5.16.1p1: This following citation is common to constraints
3716 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3717 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00003718 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00003719 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00003720 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00003721
Mike Stumpeed9cac2009-02-19 03:04:26 +00003722 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3723 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00003724 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003725 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00003726 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00003727 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003728
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003729 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00003730 assert(rhptee->isFunctionType());
3731 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003732 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003733
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003734 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00003735 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00003736 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003737
3738 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00003739 assert(lhptee->isFunctionType());
3740 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003741 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003742 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00003743 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003744 lhptee = lhptee.getUnqualifiedType();
3745 rhptee = rhptee.getUnqualifiedType();
3746 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3747 // Check if the pointee types are compatible ignoring the sign.
3748 // We explicitly check for char so that we catch "char" vs
3749 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00003750 if (lhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003751 lhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00003752 else if (lhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003753 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00003754
3755 if (rhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003756 rhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00003757 else if (rhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003758 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00003759
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003760 if (lhptee == rhptee) {
3761 // Types are compatible ignoring the sign. Qualifier incompatibility
3762 // takes priority over sign incompatibility because the sign
3763 // warning can be disabled.
3764 if (ConvTy != Compatible)
3765 return ConvTy;
3766 return IncompatiblePointerSign;
3767 }
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00003768
3769 // If we are a multi-level pointer, it's possible that our issue is simply
3770 // one of qualification - e.g. char ** -> const char ** is not allowed. If
3771 // the eventual target type is the same and the pointers have the same
3772 // level of indirection, this must be the issue.
3773 if (lhptee->isPointerType() && rhptee->isPointerType()) {
3774 do {
3775 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
3776 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
3777
3778 lhptee = Context.getCanonicalType(lhptee);
3779 rhptee = Context.getCanonicalType(rhptee);
3780 } while (lhptee->isPointerType() && rhptee->isPointerType());
3781
Douglas Gregora4923eb2009-11-16 21:35:15 +00003782 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Sean Huntc9132b62009-11-08 07:46:34 +00003783 return IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00003784 }
3785
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003786 // General pointer incompatibility takes priority over qualifiers.
Mike Stump1eb44332009-09-09 15:08:12 +00003787 return IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003788 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00003789 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003790}
3791
Steve Naroff1c7d0672008-09-04 15:10:53 +00003792/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3793/// block pointer types are compatible or whether a block and normal pointer
3794/// are compatible. It is more restrict than comparing two function pointer
3795// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003796Sema::AssignConvertType
3797Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00003798 QualType rhsType) {
3799 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003800
Steve Naroff1c7d0672008-09-04 15:10:53 +00003801 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00003802 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3803 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003804
Steve Naroff1c7d0672008-09-04 15:10:53 +00003805 // make sure we operate on the canonical type
3806 lhptee = Context.getCanonicalType(lhptee);
3807 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003808
Steve Naroff1c7d0672008-09-04 15:10:53 +00003809 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003810
Steve Naroff1c7d0672008-09-04 15:10:53 +00003811 // For blocks we enforce that qualifiers are identical.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003812 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff1c7d0672008-09-04 15:10:53 +00003813 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003814
Eli Friedman26784c12009-06-08 05:08:54 +00003815 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00003816 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003817 return ConvTy;
3818}
3819
Mike Stumpeed9cac2009-02-19 03:04:26 +00003820/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3821/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00003822/// pointers. Here are some objectionable examples that GCC considers warnings:
3823///
3824/// int a, *pint;
3825/// short *pshort;
3826/// struct foo *pfoo;
3827///
3828/// pint = pshort; // warning: assignment from incompatible pointer type
3829/// a = pint; // warning: assignment makes integer from pointer without a cast
3830/// pint = a; // warning: assignment makes pointer from integer without a cast
3831/// pint = pfoo; // warning: assignment from incompatible pointer type
3832///
3833/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00003834/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00003835///
Chris Lattner5cf216b2008-01-04 18:04:52 +00003836Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00003837Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00003838 // Get canonical types. We're not formatting these types, just comparing
3839 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003840 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3841 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003842
3843 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00003844 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00003845
David Chisnall0f436562009-08-17 16:35:33 +00003846 if ((lhsType->isObjCClassType() &&
3847 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3848 (rhsType->isObjCClassType() &&
3849 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3850 return Compatible;
3851 }
3852
Douglas Gregor9d293df2008-10-28 00:22:11 +00003853 // If the left-hand side is a reference type, then we are in a
3854 // (rare!) case where we've allowed the use of references in C,
3855 // e.g., as a parameter type in a built-in function. In this case,
3856 // just make sure that the type referenced is compatible with the
3857 // right-hand side type. The caller is responsible for adjusting
3858 // lhsType so that the resulting expression does not have reference
3859 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003860 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor9d293df2008-10-28 00:22:11 +00003861 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00003862 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003863 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00003864 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003865 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3866 // to the same ExtVector type.
3867 if (lhsType->isExtVectorType()) {
3868 if (rhsType->isExtVectorType())
3869 return lhsType == rhsType ? Compatible : Incompatible;
3870 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3871 return Compatible;
3872 }
Mike Stump1eb44332009-09-09 15:08:12 +00003873
Nate Begemanbe2341d2008-07-14 18:02:46 +00003874 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003875 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00003876 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00003877 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00003878 if (getLangOptions().LaxVectorConversions &&
3879 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003880 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00003881 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00003882 }
3883 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003884 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003885
Chris Lattnere8b3e962008-01-04 23:32:24 +00003886 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00003887 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003888
Chris Lattner78eca282008-04-07 06:49:41 +00003889 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003890 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00003891 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003892
Chris Lattner78eca282008-04-07 06:49:41 +00003893 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003894 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003895
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003896 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00003897 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003898 if (lhsType->isVoidPointerType()) // an exception to the rule.
3899 return Compatible;
3900 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003901 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003902 if (rhsType->getAs<BlockPointerType>()) {
3903 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003904 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00003905
3906 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00003907 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00003908 return Compatible;
3909 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00003910 return Incompatible;
3911 }
3912
3913 if (isa<BlockPointerType>(lhsType)) {
3914 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00003915 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003916
Steve Naroffb4406862008-09-29 18:10:17 +00003917 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00003918 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00003919 return Compatible;
3920
Steve Naroff1c7d0672008-09-04 15:10:53 +00003921 if (rhsType->isBlockPointerType())
3922 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003923
Ted Kremenek6217b802009-07-29 21:53:49 +00003924 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff1c7d0672008-09-04 15:10:53 +00003925 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003926 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003927 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00003928 return Incompatible;
3929 }
3930
Steve Naroff14108da2009-07-10 23:34:53 +00003931 if (isa<ObjCObjectPointerType>(lhsType)) {
3932 if (rhsType->isIntegerType())
3933 return IntToPointer;
Mike Stump1eb44332009-09-09 15:08:12 +00003934
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003935 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00003936 if (isa<PointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003937 if (rhsType->isVoidPointerType()) // an exception to the rule.
3938 return Compatible;
3939 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003940 }
3941 if (rhsType->isObjCObjectPointerType()) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003942 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3943 return Compatible;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003944 if (Context.typesAreCompatible(lhsType, rhsType))
3945 return Compatible;
Steve Naroff4084c302009-07-23 01:01:38 +00003946 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3947 return IncompatibleObjCQualifiedId;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003948 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003949 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003950 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003951 if (RHSPT->getPointeeType()->isVoidType())
3952 return Compatible;
3953 }
3954 // Treat block pointers as objects.
3955 if (rhsType->isBlockPointerType())
3956 return Compatible;
3957 return Incompatible;
3958 }
Chris Lattner78eca282008-04-07 06:49:41 +00003959 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003960 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003961 if (lhsType == Context.BoolTy)
3962 return Compatible;
3963
3964 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00003965 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00003966
Mike Stumpeed9cac2009-02-19 03:04:26 +00003967 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003968 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003969
3970 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003971 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003972 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003973 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003974 }
Steve Naroff14108da2009-07-10 23:34:53 +00003975 if (isa<ObjCObjectPointerType>(rhsType)) {
3976 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3977 if (lhsType == Context.BoolTy)
3978 return Compatible;
3979
3980 if (lhsType->isIntegerType())
3981 return PointerToInt;
3982
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003983 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00003984 if (isa<PointerType>(lhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003985 if (lhsType->isVoidPointerType()) // an exception to the rule.
3986 return Compatible;
3987 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003988 }
3989 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003990 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff14108da2009-07-10 23:34:53 +00003991 return Compatible;
3992 return Incompatible;
3993 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003994
Chris Lattnerfc144e22008-01-04 23:18:45 +00003995 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00003996 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003997 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00003998 }
3999 return Incompatible;
4000}
4001
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004002/// \brief Constructs a transparent union from an expression that is
4003/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00004004static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004005 QualType UnionType, FieldDecl *Field) {
4006 // Build an initializer list that designates the appropriate member
4007 // of the transparent union.
4008 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
4009 &E, 1,
4010 SourceLocation());
4011 Initializer->setType(UnionType);
4012 Initializer->setInitializedFieldInUnion(Field);
4013
4014 // Build a compound literal constructing a value of the transparent
4015 // union type from this initializer list.
4016 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
4017 false);
4018}
4019
4020Sema::AssignConvertType
4021Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4022 QualType FromType = rExpr->getType();
4023
Mike Stump1eb44332009-09-09 15:08:12 +00004024 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004025 // transparent_union GCC extension.
4026 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004027 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004028 return Incompatible;
4029
4030 // The field to initialize within the transparent union.
4031 RecordDecl *UD = UT->getDecl();
4032 FieldDecl *InitField = 0;
4033 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004034 for (RecordDecl::field_iterator it = UD->field_begin(),
4035 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004036 it != itend; ++it) {
4037 if (it->getType()->isPointerType()) {
4038 // If the transparent union contains a pointer type, we allow:
4039 // 1) void pointer
4040 // 2) null pointer constant
4041 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004042 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004043 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004044 InitField = *it;
4045 break;
4046 }
Mike Stump1eb44332009-09-09 15:08:12 +00004047
Douglas Gregorce940492009-09-25 04:25:58 +00004048 if (rExpr->isNullPointerConstant(Context,
4049 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004050 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004051 InitField = *it;
4052 break;
4053 }
4054 }
4055
4056 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4057 == Compatible) {
4058 InitField = *it;
4059 break;
4060 }
4061 }
4062
4063 if (!InitField)
4064 return Incompatible;
4065
4066 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4067 return Compatible;
4068}
4069
Chris Lattner5cf216b2008-01-04 18:04:52 +00004070Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00004071Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00004072 if (getLangOptions().CPlusPlus) {
4073 if (!lhsType->isRecordType()) {
4074 // C++ 5.17p3: If the left operand is not of class type, the
4075 // expression is implicitly converted (C++ 4) to the
4076 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00004077 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
4078 "assigning"))
Douglas Gregor98cd5992008-10-21 23:43:52 +00004079 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00004080 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00004081 }
4082
4083 // FIXME: Currently, we fall through and treat C++ classes like C
4084 // structures.
4085 }
4086
Steve Naroff529a4ad2007-11-27 17:58:44 +00004087 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4088 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00004089 if ((lhsType->isPointerType() ||
4090 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00004091 lhsType->isBlockPointerType())
Douglas Gregorce940492009-09-25 04:25:58 +00004092 && rExpr->isNullPointerConstant(Context,
4093 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004094 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff529a4ad2007-11-27 17:58:44 +00004095 return Compatible;
4096 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004097
Chris Lattner943140e2007-10-16 02:55:40 +00004098 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00004099 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00004100 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00004101 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00004102 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00004103 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00004104 if (!lhsType->isReferenceType())
4105 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00004106
Chris Lattner5cf216b2008-01-04 18:04:52 +00004107 Sema::AssignConvertType result =
4108 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004109
Steve Narofff1120de2007-08-24 22:33:52 +00004110 // C99 6.5.16.1p2: The value of the right operand is converted to the
4111 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00004112 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4113 // so that we can use references in built-in functions even in C.
4114 // The getNonReferenceType() call makes sure that the resulting expression
4115 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004116 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004117 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4118 CastExpr::CK_Unknown);
Steve Narofff1120de2007-08-24 22:33:52 +00004119 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00004120}
4121
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004122QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004123 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00004124 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004125 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00004126 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004127}
4128
Mike Stumpeed9cac2009-02-19 03:04:26 +00004129inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00004130 Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004131 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004132 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004133 QualType lhsType =
4134 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4135 QualType rhsType =
4136 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004137
Nate Begemanbe2341d2008-07-14 18:02:46 +00004138 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004139 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00004140 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00004141
Nate Begemanbe2341d2008-07-14 18:02:46 +00004142 // Handle the case of a vector & extvector type of the same size and element
4143 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004144 if (getLangOptions().LaxVectorConversions) {
4145 // FIXME: Should we warn here?
John McCall183700f2009-09-21 23:43:11 +00004146 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4147 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begemanbe2341d2008-07-14 18:02:46 +00004148 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004149 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004150 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004151 }
4152 }
4153 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004154
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004155 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4156 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4157 bool swapped = false;
4158 if (rhsType->isExtVectorType()) {
4159 swapped = true;
4160 std::swap(rex, lex);
4161 std::swap(rhsType, lhsType);
4162 }
Mike Stump1eb44332009-09-09 15:08:12 +00004163
Nate Begemandde25982009-06-28 19:12:57 +00004164 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00004165 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004166 QualType EltTy = LV->getElementType();
4167 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4168 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004169 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004170 if (swapped) std::swap(rex, lex);
4171 return lhsType;
4172 }
4173 }
4174 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4175 rhsType->isRealFloatingType()) {
4176 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004177 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004178 if (swapped) std::swap(rex, lex);
4179 return lhsType;
4180 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00004181 }
4182 }
Mike Stump1eb44332009-09-09 15:08:12 +00004183
Nate Begemandde25982009-06-28 19:12:57 +00004184 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004185 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00004186 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004187 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004188 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00004189}
4190
Reid Spencer5f016e22007-07-11 17:01:13 +00004191inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004192 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00004193 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004194 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004195
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004196 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004197
Steve Naroffa4332e22007-07-17 00:58:39 +00004198 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004199 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004200 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004201}
4202
4203inline QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004204 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00004205 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4206 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4207 return CheckVectorOperands(Loc, lex, rex);
4208 return InvalidOperands(Loc, lex, rex);
4209 }
Steve Naroff90045e82007-07-13 23:32:42 +00004210
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004211 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004212
Steve Naroffa4332e22007-07-17 00:58:39 +00004213 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004214 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004215 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004216}
4217
4218inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00004219 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004220 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4221 QualType compType = CheckVectorOperands(Loc, lex, rex);
4222 if (CompLHSTy) *CompLHSTy = compType;
4223 return compType;
4224 }
Steve Naroff49b45262007-07-13 16:58:59 +00004225
Eli Friedmanab3a8522009-03-28 01:22:36 +00004226 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00004227
Reid Spencer5f016e22007-07-11 17:01:13 +00004228 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00004229 if (lex->getType()->isArithmeticType() &&
4230 rex->getType()->isArithmeticType()) {
4231 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004232 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004233 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004234
Eli Friedmand72d16e2008-05-18 18:08:51 +00004235 // Put any potential pointer into PExp
4236 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004237 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00004238 std::swap(PExp, IExp);
4239
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004240 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004241
Eli Friedmand72d16e2008-05-18 18:08:51 +00004242 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00004243 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004244
Chris Lattnerb5f15622009-04-24 23:50:08 +00004245 // Check for arithmetic on pointers to incomplete types.
4246 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004247 if (getLangOptions().CPlusPlus) {
4248 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004249 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004250 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00004251 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004252
4253 // GNU extension: arithmetic on pointer to void
4254 Diag(Loc, diag::ext_gnu_void_ptr)
4255 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00004256 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004257 if (getLangOptions().CPlusPlus) {
4258 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4259 << lex->getType() << lex->getSourceRange();
4260 return QualType();
4261 }
4262
4263 // GNU extension: arithmetic on pointer to function
4264 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4265 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00004266 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00004267 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00004268 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00004269 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00004270 PExp->getType()->isObjCObjectPointerType()) &&
4271 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00004272 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4273 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004274 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00004275 return QualType();
4276 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00004277 // Diagnose bad cases where we step over interface counts.
4278 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4279 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4280 << PointeeTy << PExp->getSourceRange();
4281 return QualType();
4282 }
Mike Stump1eb44332009-09-09 15:08:12 +00004283
Eli Friedmanab3a8522009-03-28 01:22:36 +00004284 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00004285 QualType LHSTy = Context.isPromotableBitField(lex);
4286 if (LHSTy.isNull()) {
4287 LHSTy = lex->getType();
4288 if (LHSTy->isPromotableIntegerType())
4289 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004290 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00004291 *CompLHSTy = LHSTy;
4292 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00004293 return PExp->getType();
4294 }
4295 }
4296
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004297 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004298}
4299
Chris Lattnereca7be62008-04-07 05:30:13 +00004300// C99 6.5.6
4301QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00004302 SourceLocation Loc, QualType* CompLHSTy) {
4303 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4304 QualType compType = CheckVectorOperands(Loc, lex, rex);
4305 if (CompLHSTy) *CompLHSTy = compType;
4306 return compType;
4307 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004308
Eli Friedmanab3a8522009-03-28 01:22:36 +00004309 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004310
Chris Lattner6e4ab612007-12-09 21:53:25 +00004311 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004312
Chris Lattner6e4ab612007-12-09 21:53:25 +00004313 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00004314 if (lex->getType()->isArithmeticType()
4315 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004316 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004317 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004318 }
Mike Stump1eb44332009-09-09 15:08:12 +00004319
Chris Lattner6e4ab612007-12-09 21:53:25 +00004320 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004321 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00004322 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004323
Douglas Gregore7450f52009-03-24 19:52:54 +00004324 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00004325
Douglas Gregore7450f52009-03-24 19:52:54 +00004326 bool ComplainAboutVoid = false;
4327 Expr *ComplainAboutFunc = 0;
4328 if (lpointee->isVoidType()) {
4329 if (getLangOptions().CPlusPlus) {
4330 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4331 << lex->getSourceRange() << rex->getSourceRange();
4332 return QualType();
4333 }
4334
4335 // GNU C extension: arithmetic on pointer to void
4336 ComplainAboutVoid = true;
4337 } else if (lpointee->isFunctionType()) {
4338 if (getLangOptions().CPlusPlus) {
4339 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004340 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004341 return QualType();
4342 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004343
4344 // GNU C extension: arithmetic on pointer to function
4345 ComplainAboutFunc = lex;
4346 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004347 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004348 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00004349 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004350 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004351 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004352
Chris Lattnerb5f15622009-04-24 23:50:08 +00004353 // Diagnose bad cases where we step over interface counts.
4354 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4355 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4356 << lpointee << lex->getSourceRange();
4357 return QualType();
4358 }
Mike Stump1eb44332009-09-09 15:08:12 +00004359
Chris Lattner6e4ab612007-12-09 21:53:25 +00004360 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00004361 if (rex->getType()->isIntegerType()) {
4362 if (ComplainAboutVoid)
4363 Diag(Loc, diag::ext_gnu_void_ptr)
4364 << lex->getSourceRange() << rex->getSourceRange();
4365 if (ComplainAboutFunc)
4366 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004367 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004368 << ComplainAboutFunc->getSourceRange();
4369
Eli Friedmanab3a8522009-03-28 01:22:36 +00004370 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004371 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00004372 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004373
Chris Lattner6e4ab612007-12-09 21:53:25 +00004374 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004375 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00004376 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004377
Douglas Gregore7450f52009-03-24 19:52:54 +00004378 // RHS must be a completely-type object type.
4379 // Handle the GNU void* extension.
4380 if (rpointee->isVoidType()) {
4381 if (getLangOptions().CPlusPlus) {
4382 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4383 << lex->getSourceRange() << rex->getSourceRange();
4384 return QualType();
4385 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004386
Douglas Gregore7450f52009-03-24 19:52:54 +00004387 ComplainAboutVoid = true;
4388 } else if (rpointee->isFunctionType()) {
4389 if (getLangOptions().CPlusPlus) {
4390 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004391 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004392 return QualType();
4393 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004394
4395 // GNU extension: arithmetic on pointer to function
4396 if (!ComplainAboutFunc)
4397 ComplainAboutFunc = rex;
4398 } else if (!rpointee->isDependentType() &&
4399 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004400 PDiag(diag::err_typecheck_sub_ptr_object)
4401 << rex->getSourceRange()
4402 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004403 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004404
Eli Friedman88d936b2009-05-16 13:54:38 +00004405 if (getLangOptions().CPlusPlus) {
4406 // Pointee types must be the same: C++ [expr.add]
4407 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4408 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4409 << lex->getType() << rex->getType()
4410 << lex->getSourceRange() << rex->getSourceRange();
4411 return QualType();
4412 }
4413 } else {
4414 // Pointee types must be compatible C99 6.5.6p3
4415 if (!Context.typesAreCompatible(
4416 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4417 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4418 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4419 << lex->getType() << rex->getType()
4420 << lex->getSourceRange() << rex->getSourceRange();
4421 return QualType();
4422 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00004423 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004424
Douglas Gregore7450f52009-03-24 19:52:54 +00004425 if (ComplainAboutVoid)
4426 Diag(Loc, diag::ext_gnu_void_ptr)
4427 << lex->getSourceRange() << rex->getSourceRange();
4428 if (ComplainAboutFunc)
4429 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004430 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004431 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00004432
4433 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004434 return Context.getPointerDiffType();
4435 }
4436 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004437
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004438 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004439}
4440
Chris Lattnereca7be62008-04-07 05:30:13 +00004441// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004442QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00004443 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00004444 // C99 6.5.7p2: Each of the operands shall have integer type.
4445 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004446 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004447
Nate Begeman2207d792009-10-25 02:26:48 +00004448 // Vector shifts promote their scalar inputs to vector type.
4449 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4450 return CheckVectorOperands(Loc, lex, rex);
4451
Chris Lattnerca5eede2007-12-12 05:47:28 +00004452 // Shifts don't perform usual arithmetic conversions, they just do integer
4453 // promotions on each operand. C99 6.5.7p3
Eli Friedman04e83572009-08-20 04:21:42 +00004454 QualType LHSTy = Context.isPromotableBitField(lex);
4455 if (LHSTy.isNull()) {
4456 LHSTy = lex->getType();
4457 if (LHSTy->isPromotableIntegerType())
4458 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004459 }
Chris Lattner1dcf2c82007-12-13 07:28:16 +00004460 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004461 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedmanab3a8522009-03-28 01:22:36 +00004462
Chris Lattnerca5eede2007-12-12 05:47:28 +00004463 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004464
Ryan Flynnd0439682009-08-07 16:20:20 +00004465 // Sanity-check shift operands
4466 llvm::APSInt Right;
4467 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00004468 if (!rex->isValueDependent() &&
4469 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00004470 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00004471 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4472 else {
4473 llvm::APInt LeftBits(Right.getBitWidth(),
4474 Context.getTypeSize(lex->getType()));
4475 if (Right.uge(LeftBits))
4476 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4477 }
4478 }
4479
Chris Lattnerca5eede2007-12-12 05:47:28 +00004480 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00004481 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004482}
4483
John McCall5dbad3d2009-11-06 08:49:08 +00004484/// \brief Implements -Wsign-compare.
4485///
4486/// \param lex the left-hand expression
4487/// \param rex the right-hand expression
4488/// \param OpLoc the location of the joining operator
John McCall48f5e632009-11-06 08:53:51 +00004489/// \param Equality whether this is an "equality-like" join, which
4490/// suppresses the warning in some cases
John McCallb13c87f2009-11-05 09:23:39 +00004491void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
John McCall5dbad3d2009-11-06 08:49:08 +00004492 const PartialDiagnostic &PD, bool Equality) {
John McCall7d62a8f2009-11-06 18:16:06 +00004493 // Don't warn if we're in an unevaluated context.
Douglas Gregor2afce722009-11-26 00:44:06 +00004494 if (ExprEvalContexts.back().Context == Unevaluated)
John McCall7d62a8f2009-11-06 18:16:06 +00004495 return;
4496
John McCall45aa4552009-11-05 00:40:04 +00004497 QualType lt = lex->getType(), rt = rex->getType();
4498
4499 // Only warn if both operands are integral.
4500 if (!lt->isIntegerType() || !rt->isIntegerType())
4501 return;
4502
Sebastian Redl732429c2009-11-05 21:09:23 +00004503 // If either expression is value-dependent, don't warn. We'll get another
4504 // chance at instantiation time.
4505 if (lex->isValueDependent() || rex->isValueDependent())
4506 return;
4507
John McCall45aa4552009-11-05 00:40:04 +00004508 // The rule is that the signed operand becomes unsigned, so isolate the
4509 // signed operand.
John McCall5dbad3d2009-11-06 08:49:08 +00004510 Expr *signedOperand, *unsignedOperand;
John McCall45aa4552009-11-05 00:40:04 +00004511 if (lt->isSignedIntegerType()) {
4512 if (rt->isSignedIntegerType()) return;
4513 signedOperand = lex;
John McCall5dbad3d2009-11-06 08:49:08 +00004514 unsignedOperand = rex;
John McCall45aa4552009-11-05 00:40:04 +00004515 } else {
4516 if (!rt->isSignedIntegerType()) return;
4517 signedOperand = rex;
John McCall5dbad3d2009-11-06 08:49:08 +00004518 unsignedOperand = lex;
John McCall45aa4552009-11-05 00:40:04 +00004519 }
4520
John McCall5dbad3d2009-11-06 08:49:08 +00004521 // If the unsigned type is strictly smaller than the signed type,
John McCall48f5e632009-11-06 08:53:51 +00004522 // then (1) the result type will be signed and (2) the unsigned
4523 // value will fit fully within the signed type, and thus the result
John McCall5dbad3d2009-11-06 08:49:08 +00004524 // of the comparison will be exact.
4525 if (Context.getIntWidth(signedOperand->getType()) >
4526 Context.getIntWidth(unsignedOperand->getType()))
4527 return;
4528
John McCall45aa4552009-11-05 00:40:04 +00004529 // If the value is a non-negative integer constant, then the
4530 // signed->unsigned conversion won't change it.
4531 llvm::APSInt value;
John McCallb13c87f2009-11-05 09:23:39 +00004532 if (signedOperand->isIntegerConstantExpr(value, Context)) {
John McCall45aa4552009-11-05 00:40:04 +00004533 assert(value.isSigned() && "result of signed expression not signed");
4534
4535 if (value.isNonNegative())
4536 return;
4537 }
4538
John McCall5dbad3d2009-11-06 08:49:08 +00004539 if (Equality) {
4540 // For (in)equality comparisons, if the unsigned operand is a
John McCall48f5e632009-11-06 08:53:51 +00004541 // constant which cannot collide with a overflowed signed operand,
4542 // then reinterpreting the signed operand as unsigned will not
4543 // change the result of the comparison.
John McCall5dbad3d2009-11-06 08:49:08 +00004544 if (unsignedOperand->isIntegerConstantExpr(value, Context)) {
4545 assert(!value.isSigned() && "result of unsigned expression is signed");
4546
4547 // 2's complement: test the top bit.
4548 if (value.isNonNegative())
4549 return;
4550 }
4551 }
4552
John McCallb13c87f2009-11-05 09:23:39 +00004553 Diag(OpLoc, PD)
John McCall45aa4552009-11-05 00:40:04 +00004554 << lex->getType() << rex->getType()
4555 << lex->getSourceRange() << rex->getSourceRange();
4556}
4557
Douglas Gregor0c6db942009-05-04 06:07:12 +00004558// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004559QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00004560 unsigned OpaqueOpc, bool isRelational) {
4561 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4562
Nate Begemanbe2341d2008-07-14 18:02:46 +00004563 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004564 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004565
John McCall5dbad3d2009-11-06 08:49:08 +00004566 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
4567 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall45aa4552009-11-05 00:40:04 +00004568
Chris Lattnera5937dd2007-08-26 01:18:55 +00004569 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00004570 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4571 UsualArithmeticConversions(lex, rex);
4572 else {
4573 UsualUnaryConversions(lex);
4574 UsualUnaryConversions(rex);
4575 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004576 QualType lType = lex->getType();
4577 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004578
Mike Stumpaf199f32009-05-07 18:43:07 +00004579 if (!lType->isFloatingType()
4580 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner55660a72009-03-08 19:39:53 +00004581 // For non-floating point types, check for self-comparisons of the form
4582 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4583 // often indicate logic errors in the program.
Mike Stump1eb44332009-09-09 15:08:12 +00004584 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenek9ecede72009-03-20 19:57:37 +00004585 // from macro expansions, and are usually quite deliberate.
Chris Lattner55660a72009-03-08 19:39:53 +00004586 Expr *LHSStripped = lex->IgnoreParens();
4587 Expr *RHSStripped = rex->IgnoreParens();
4588 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4589 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekb82dcd82009-03-20 18:35:45 +00004590 if (DRL->getDecl() == DRR->getDecl() &&
4591 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stumpeed9cac2009-02-19 03:04:26 +00004592 Diag(Loc, diag::warn_selfcomparison);
Mike Stump1eb44332009-09-09 15:08:12 +00004593
Chris Lattner55660a72009-03-08 19:39:53 +00004594 if (isa<CastExpr>(LHSStripped))
4595 LHSStripped = LHSStripped->IgnoreParenCasts();
4596 if (isa<CastExpr>(RHSStripped))
4597 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00004598
Chris Lattner55660a72009-03-08 19:39:53 +00004599 // Warn about comparisons against a string constant (unless the other
4600 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00004601 Expr *literalString = 0;
4602 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00004603 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004604 !RHSStripped->isNullPointerConstant(Context,
4605 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00004606 literalString = lex;
4607 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00004608 } else if ((isa<StringLiteral>(RHSStripped) ||
4609 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004610 !LHSStripped->isNullPointerConstant(Context,
4611 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00004612 literalString = rex;
4613 literalStringStripped = RHSStripped;
4614 }
4615
4616 if (literalString) {
4617 std::string resultComparison;
4618 switch (Opc) {
4619 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4620 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4621 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4622 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4623 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4624 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4625 default: assert(false && "Invalid comparison operator");
4626 }
4627 Diag(Loc, diag::warn_stringcompare)
4628 << isa<ObjCEncodeExpr>(literalStringStripped)
4629 << literalString->getSourceRange()
Douglas Gregora3a83512009-04-01 23:51:29 +00004630 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4631 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4632 "strcmp(")
4633 << CodeModificationHint::CreateInsertion(
4634 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregora86b8322009-04-06 18:45:53 +00004635 resultComparison);
4636 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00004637 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004638
Douglas Gregor447b69e2008-11-19 03:25:36 +00004639 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner55660a72009-03-08 19:39:53 +00004640 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00004641
Chris Lattnera5937dd2007-08-26 01:18:55 +00004642 if (isRelational) {
4643 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00004644 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00004645 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00004646 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00004647 if (lType->isFloatingType()) {
Chris Lattner55660a72009-03-08 19:39:53 +00004648 assert(rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004649 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00004650 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004651
Chris Lattnera5937dd2007-08-26 01:18:55 +00004652 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00004653 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00004654 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004655
Douglas Gregorce940492009-09-25 04:25:58 +00004656 bool LHSIsNull = lex->isNullPointerConstant(Context,
4657 Expr::NPC_ValueDependentIsNull);
4658 bool RHSIsNull = rex->isNullPointerConstant(Context,
4659 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004660
Chris Lattnera5937dd2007-08-26 01:18:55 +00004661 // All of the following pointer related warnings are GCC extensions, except
4662 // when handling null pointer constants. One day, we can consider making them
4663 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00004664 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00004665 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00004666 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00004667 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00004668 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004669
Douglas Gregor0c6db942009-05-04 06:07:12 +00004670 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00004671 if (LCanPointeeTy == RCanPointeeTy)
4672 return ResultTy;
4673
Douglas Gregor0c6db942009-05-04 06:07:12 +00004674 // C++ [expr.rel]p2:
4675 // [...] Pointer conversions (4.10) and qualification
4676 // conversions (4.4) are performed on pointer operands (or on
4677 // a pointer operand and a null pointer constant) to bring
4678 // them to their composite pointer type. [...]
4679 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00004680 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00004681 // comparisons of pointers.
Douglas Gregorde866f32009-05-05 04:50:50 +00004682 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor0c6db942009-05-04 06:07:12 +00004683 if (T.isNull()) {
4684 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4685 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4686 return QualType();
4687 }
4688
Eli Friedman73c39ab2009-10-20 08:27:19 +00004689 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
4690 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00004691 return ResultTy;
4692 }
Eli Friedman3075e762009-08-23 00:27:47 +00004693 // C99 6.5.9p2 and C99 6.5.8p2
4694 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4695 RCanPointeeTy.getUnqualifiedType())) {
4696 // Valid unless a relational comparison of function pointers
4697 if (isRelational && LCanPointeeTy->isFunctionType()) {
4698 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4699 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4700 }
4701 } else if (!isRelational &&
4702 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4703 // Valid unless comparison between non-null pointer and function pointer
4704 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4705 && !LHSIsNull && !RHSIsNull) {
4706 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4707 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4708 }
4709 } else {
4710 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004711 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00004712 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004713 }
Eli Friedman3075e762009-08-23 00:27:47 +00004714 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004715 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004716 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00004717 }
Mike Stump1eb44332009-09-09 15:08:12 +00004718
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004719 if (getLangOptions().CPlusPlus) {
Mike Stump1eb44332009-09-09 15:08:12 +00004720 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00004721 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00004722 if (RHSIsNull &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00004723 (lType->isPointerType() ||
4724 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00004725 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004726 return ResultTy;
4727 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00004728 if (LHSIsNull &&
4729 (rType->isPointerType() ||
4730 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00004731 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004732 return ResultTy;
4733 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00004734
4735 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00004736 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00004737 lType->isMemberPointerType() && rType->isMemberPointerType()) {
4738 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004739 // In addition, pointers to members can be compared, or a pointer to
4740 // member and a null pointer constant. Pointer to member conversions
4741 // (4.11) and qualification conversions (4.4) are performed to bring
4742 // them to a common type. If one operand is a null pointer constant,
4743 // the common type is the type of the other operand. Otherwise, the
4744 // common type is a pointer to member type similar (4.4) to the type
4745 // of one of the operands, with a cv-qualification signature (4.4)
4746 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00004747 // types.
4748 QualType T = FindCompositePointerType(lex, rex);
4749 if (T.isNull()) {
4750 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4751 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4752 return QualType();
4753 }
Mike Stump1eb44332009-09-09 15:08:12 +00004754
Eli Friedman73c39ab2009-10-20 08:27:19 +00004755 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
4756 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004757 return ResultTy;
4758 }
Mike Stump1eb44332009-09-09 15:08:12 +00004759
Douglas Gregor20b3e992009-08-24 17:42:35 +00004760 // Comparison of nullptr_t with itself.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004761 if (lType->isNullPtrType() && rType->isNullPtrType())
4762 return ResultTy;
4763 }
Mike Stump1eb44332009-09-09 15:08:12 +00004764
Steve Naroff1c7d0672008-09-04 15:10:53 +00004765 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004766 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004767 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4768 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004769
Steve Naroff1c7d0672008-09-04 15:10:53 +00004770 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00004771 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004772 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00004773 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00004774 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004775 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004776 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004777 }
Steve Naroff59f53942008-09-28 01:11:11 +00004778 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004779 if (!isRelational
4780 && ((lType->isBlockPointerType() && rType->isPointerType())
4781 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00004782 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004783 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00004784 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004785 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00004786 ->getPointeeType()->isVoidType())))
4787 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4788 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00004789 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004790 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004791 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00004792 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00004793
Steve Naroff14108da2009-07-10 23:34:53 +00004794 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00004795 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004796 const PointerType *LPT = lType->getAs<PointerType>();
4797 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004798 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00004799 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004800 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00004801 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004802
Steve Naroffa8069f12008-11-17 19:49:16 +00004803 if (!LPtrToVoid && !RPtrToVoid &&
4804 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004805 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00004806 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00004807 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004808 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004809 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00004810 }
Steve Naroff14108da2009-07-10 23:34:53 +00004811 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00004812 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00004813 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4814 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004815 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004816 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00004817 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00004818 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004819 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004820 unsigned DiagID = 0;
4821 if (RHSIsNull) {
4822 if (isRelational)
4823 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4824 } else if (isRelational)
4825 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4826 else
4827 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00004828
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004829 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00004830 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00004831 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00004832 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004833 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004834 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00004835 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004836 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004837 unsigned DiagID = 0;
4838 if (LHSIsNull) {
4839 if (isRelational)
4840 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4841 } else if (isRelational)
4842 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4843 else
4844 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00004845
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004846 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00004847 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00004848 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00004849 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00004850 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004851 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004852 }
Steve Naroff39218df2008-09-04 16:56:14 +00004853 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00004854 if (!isRelational && RHSIsNull
4855 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004856 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004857 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00004858 }
Mike Stumpaf199f32009-05-07 18:43:07 +00004859 if (!isRelational && LHSIsNull
4860 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004861 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004862 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00004863 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004864 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004865}
4866
Nate Begemanbe2341d2008-07-14 18:02:46 +00004867/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00004868/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00004869/// like a scalar comparison, a vector comparison produces a vector of integer
4870/// types.
4871QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004872 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00004873 bool isRelational) {
4874 // Check to make sure we're operating on vectors of the same type and width,
4875 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004876 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004877 if (vType.isNull())
4878 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004879
Nate Begemanbe2341d2008-07-14 18:02:46 +00004880 QualType lType = lex->getType();
4881 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004882
Nate Begemanbe2341d2008-07-14 18:02:46 +00004883 // For non-floating point types, check for self-comparisons of the form
4884 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4885 // often indicate logic errors in the program.
4886 if (!lType->isFloatingType()) {
4887 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4888 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4889 if (DRL->getDecl() == DRR->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004890 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004891 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004892
Nate Begemanbe2341d2008-07-14 18:02:46 +00004893 // Check for comparisons of floating point operands using != and ==.
4894 if (!isRelational && lType->isFloatingType()) {
4895 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004896 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004897 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004898
Nate Begemanbe2341d2008-07-14 18:02:46 +00004899 // Return the type for the comparison, which is the same as vector type for
4900 // integer vectors, or an integer type of identical size and number of
4901 // elements for floating point vectors.
4902 if (lType->isIntegerType())
4903 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004904
John McCall183700f2009-09-21 23:43:11 +00004905 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00004906 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00004907 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00004908 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00004909 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00004910 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4911
Mike Stumpeed9cac2009-02-19 03:04:26 +00004912 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00004913 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00004914 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4915}
4916
Reid Spencer5f016e22007-07-11 17:01:13 +00004917inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004918 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00004919 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004920 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00004921
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004922 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004923
Steve Naroffa4332e22007-07-17 00:58:39 +00004924 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004925 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004926 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004927}
4928
4929inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump1eb44332009-09-09 15:08:12 +00004930 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Anders Carlssona4c98cd2009-11-23 21:47:44 +00004931 if (!Context.getLangOptions().CPlusPlus) {
4932 UsualUnaryConversions(lex);
4933 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004934
Anders Carlssona4c98cd2009-11-23 21:47:44 +00004935 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
4936 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00004937
Anders Carlssona4c98cd2009-11-23 21:47:44 +00004938 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00004939 }
Anders Carlssona4c98cd2009-11-23 21:47:44 +00004940
4941 // C++ [expr.log.and]p1
4942 // C++ [expr.log.or]p1
4943 // The operands are both implicitly converted to type bool (clause 4).
4944 StandardConversionSequence LHS;
4945 if (!IsStandardConversion(lex, Context.BoolTy,
4946 /*InOverloadResolution=*/false, LHS))
4947 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00004948
Anders Carlssona4c98cd2009-11-23 21:47:44 +00004949 if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
4950 "passing", /*IgnoreBaseAccess=*/false))
4951 return InvalidOperands(Loc, lex, rex);
4952
4953 StandardConversionSequence RHS;
4954 if (!IsStandardConversion(rex, Context.BoolTy,
4955 /*InOverloadResolution=*/false, RHS))
4956 return InvalidOperands(Loc, lex, rex);
4957
4958 if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
4959 "passing", /*IgnoreBaseAccess=*/false))
4960 return InvalidOperands(Loc, lex, rex);
4961
4962 // C++ [expr.log.and]p2
4963 // C++ [expr.log.or]p2
4964 // The result is a bool.
4965 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004966}
4967
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004968/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4969/// is a read-only property; return true if so. A readonly property expression
4970/// depends on various declarations and thus must be treated specially.
4971///
Mike Stump1eb44332009-09-09 15:08:12 +00004972static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004973 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4974 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4975 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4976 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004977 if (const ObjCObjectPointerType *OPT =
Steve Naroff14108da2009-07-10 23:34:53 +00004978 BaseType->getAsObjCInterfacePointerType())
4979 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4980 if (S.isPropertyReadonly(PDecl, IFace))
4981 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004982 }
4983 }
4984 return false;
4985}
4986
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004987/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4988/// emit an error and return true. If so, return false.
4989static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004990 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00004991 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004992 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004993 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4994 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004995 if (IsLV == Expr::MLV_Valid)
4996 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004997
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004998 unsigned Diag = 0;
4999 bool NeedType = false;
5000 switch (IsLV) { // C99 6.5.16p2
5001 default: assert(0 && "Unknown result from isModifiableLvalue!");
5002 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005003 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005004 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5005 NeedType = true;
5006 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005007 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005008 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5009 NeedType = true;
5010 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00005011 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005012 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5013 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005014 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005015 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5016 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005017 case Expr::MLV_IncompleteType:
5018 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00005019 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00005020 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
5021 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00005022 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005023 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5024 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00005025 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005026 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5027 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00005028 case Expr::MLV_ReadonlyProperty:
5029 Diag = diag::error_readonly_property_assignment;
5030 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00005031 case Expr::MLV_NoSetterProperty:
5032 Diag = diag::error_nosetter_property_assignment;
5033 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005034 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00005035
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005036 SourceRange Assign;
5037 if (Loc != OrigLoc)
5038 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005039 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005040 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005041 else
Mike Stump1eb44332009-09-09 15:08:12 +00005042 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005043 return true;
5044}
5045
5046
5047
5048// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005049QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5050 SourceLocation Loc,
5051 QualType CompoundType) {
5052 // Verify that LHS is a modifiable lvalue, and emit error if not.
5053 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005054 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005055
5056 QualType LHSType = LHS->getType();
5057 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005058
Chris Lattner5cf216b2008-01-04 18:04:52 +00005059 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005060 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00005061 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005062 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005063 // Special case of NSObject attributes on c-style pointer types.
5064 if (ConvTy == IncompatiblePointer &&
5065 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005066 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005067 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005068 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005069 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005070
Chris Lattner2c156472008-08-21 18:04:13 +00005071 // If the RHS is a unary plus or minus, check to see if they = and + are
5072 // right next to each other. If so, the user may have typo'd "x =+ 4"
5073 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005074 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00005075 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5076 RHSCheck = ICE->getSubExpr();
5077 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5078 if ((UO->getOpcode() == UnaryOperator::Plus ||
5079 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005080 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00005081 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00005082 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5083 // And there is a space or other character before the subexpr of the
5084 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00005085 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5086 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005087 Diag(Loc, diag::warn_not_compound_assign)
5088 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5089 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00005090 }
Chris Lattner2c156472008-08-21 18:04:13 +00005091 }
5092 } else {
5093 // Compound assignment "x += y"
Eli Friedman623712b2009-05-16 05:56:02 +00005094 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00005095 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005096
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005097 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
5098 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00005099 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005100
Reid Spencer5f016e22007-07-11 17:01:13 +00005101 // C99 6.5.16p3: The type of an assignment expression is the type of the
5102 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00005103 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00005104 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5105 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005106 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00005107 // operand.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005108 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005109}
5110
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005111// C99 6.5.17
5112QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00005113 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005114 DefaultFunctionArrayConversion(RHS);
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005115
5116 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5117 // incomplete in C++).
5118
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005119 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005120}
5121
Steve Naroff49b45262007-07-13 16:58:59 +00005122/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5123/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005124QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5125 bool isInc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005126 if (Op->isTypeDependent())
5127 return Context.DependentTy;
5128
Chris Lattner3528d352008-11-21 07:05:48 +00005129 QualType ResType = Op->getType();
5130 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005131
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005132 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5133 // Decrement of bool is not allowed.
5134 if (!isInc) {
5135 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5136 return QualType();
5137 }
5138 // Increment of bool sets it to true, but is deprecated.
5139 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5140 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00005141 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005142 } else if (ResType->isAnyPointerType()) {
5143 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005144
Chris Lattner3528d352008-11-21 07:05:48 +00005145 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00005146 if (PointeeTy->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005147 if (getLangOptions().CPlusPlus) {
5148 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5149 << Op->getSourceRange();
5150 return QualType();
5151 }
5152
5153 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00005154 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005155 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005156 if (getLangOptions().CPlusPlus) {
5157 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5158 << Op->getType() << Op->getSourceRange();
5159 return QualType();
5160 }
5161
5162 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00005163 << ResType << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005164 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssond497ba72009-08-26 22:59:12 +00005165 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00005166 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005167 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005168 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00005169 // Diagnose bad cases where we step over interface counts.
5170 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5171 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5172 << PointeeTy << Op->getSourceRange();
5173 return QualType();
5174 }
Chris Lattner3528d352008-11-21 07:05:48 +00005175 } else if (ResType->isComplexType()) {
5176 // C99 does not support ++/-- on complex types, we allow as an extension.
5177 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00005178 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005179 } else {
5180 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00005181 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005182 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005183 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005184 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00005185 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00005186 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00005187 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00005188 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005189}
5190
Anders Carlsson369dee42008-02-01 07:15:58 +00005191/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00005192/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005193/// where the declaration is needed for type checking. We only need to
5194/// handle cases when the expression references a function designator
5195/// or is an lvalue. Here are some examples:
5196/// - &(x) => x
5197/// - &*****f => f for f a function designator.
5198/// - &s.xx => s
5199/// - &s.zz[1].yy -> s, if zz is an array
5200/// - *(x + 1) -> x, if x is an array
5201/// - &"123"[2] -> 0
5202/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005203static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00005204 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005205 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005206 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00005207 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005208 // If this is an arrow operator, the address is an offset from
5209 // the base's value, so the object the base refers to is
5210 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005211 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00005212 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00005213 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00005214 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00005215 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00005216 // FIXME: This code shouldn't be necessary! We should catch the implicit
5217 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00005218 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5219 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5220 if (ICE->getSubExpr()->getType()->isArrayType())
5221 return getPrimaryDecl(ICE->getSubExpr());
5222 }
5223 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00005224 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005225 case Stmt::UnaryOperatorClass: {
5226 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005227
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005228 switch(UO->getOpcode()) {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005229 case UnaryOperator::Real:
5230 case UnaryOperator::Imag:
5231 case UnaryOperator::Extension:
5232 return getPrimaryDecl(UO->getSubExpr());
5233 default:
5234 return 0;
5235 }
5236 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005237 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005238 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00005239 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005240 // If the result of an implicit cast is an l-value, we care about
5241 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005242 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00005243 default:
5244 return 0;
5245 }
5246}
5247
5248/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00005249/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00005250/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005251/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00005252/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005253/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00005254/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00005255QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00005256 // Make sure to ignore parentheses in subsequent checks
5257 op = op->IgnoreParens();
5258
Douglas Gregor9103bb22008-12-17 22:52:20 +00005259 if (op->isTypeDependent())
5260 return Context.DependentTy;
5261
Steve Naroff08f19672008-01-13 17:10:08 +00005262 if (getLangOptions().C99) {
5263 // Implement C99-only parts of addressof rules.
5264 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5265 if (uOp->getOpcode() == UnaryOperator::Deref)
5266 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5267 // (assuming the deref expression is valid).
5268 return uOp->getSubExpr()->getType();
5269 }
5270 // Technically, there should be a check for array subscript
5271 // expressions here, but the result of one is always an lvalue anyway.
5272 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005273 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00005274 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00005275
Eli Friedman441cf102009-05-16 23:27:50 +00005276 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5277 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005278 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00005279 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00005280 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00005281 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5282 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005283 return QualType();
5284 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00005285 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005286 // The operand cannot be a bit-field
5287 Diag(OpLoc, diag::err_typecheck_address_of)
5288 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00005289 return QualType();
Nate Begemanb104b1f2009-02-15 22:45:20 +00005290 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5291 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman23d58ce2009-04-20 08:23:18 +00005292 // The operand cannot be an element of a vector
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005293 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00005294 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00005295 return QualType();
Fariborz Jahanian0337f212009-07-07 18:50:52 +00005296 } else if (isa<ObjCPropertyRefExpr>(op)) {
5297 // cannot take address of a property expression.
5298 Diag(OpLoc, diag::err_typecheck_address_of)
5299 << "property expression" << op->getSourceRange();
5300 return QualType();
Anders Carlsson1d524c32009-09-14 23:15:26 +00005301 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5302 // FIXME: Can LHS ever be null here?
Anders Carlsson474e1022009-09-15 16:03:44 +00005303 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5304 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCallba135432009-11-21 08:51:07 +00005305 } else if (isa<UnresolvedLookupExpr>(op)) {
5306 return Context.OverloadTy;
Steve Naroffbcb2b612008-02-29 23:30:25 +00005307 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00005308 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00005309 // with the register storage-class specifier.
5310 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
5311 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005312 Diag(OpLoc, diag::err_typecheck_address_of)
5313 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005314 return QualType();
5315 }
John McCallba135432009-11-21 08:51:07 +00005316 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005317 return Context.OverloadTy;
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005318 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00005319 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00005320 // Could be a pointer to member, though, if there is an explicit
5321 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005322 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00005323 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005324 if (Ctx && Ctx->isRecord()) {
5325 if (FD->getType()->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005326 Diag(OpLoc,
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005327 diag::err_cannot_form_pointer_to_member_of_reference_type)
5328 << FD->getDeclName() << FD->getType();
5329 return QualType();
5330 }
Mike Stump1eb44332009-09-09 15:08:12 +00005331
Sebastian Redlebc07d52009-02-03 20:19:35 +00005332 return Context.getMemberPointerType(op->getType(),
5333 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005334 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00005335 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00005336 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes6fea8d22008-12-16 22:58:26 +00005337 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00005338 // As above.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005339 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5340 MD->isInstance())
Anders Carlsson196f7d02009-05-16 21:43:42 +00005341 return Context.getMemberPointerType(op->getType(),
5342 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5343 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00005344 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00005345 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00005346
Eli Friedman441cf102009-05-16 23:27:50 +00005347 if (lval == Expr::LV_IncompleteVoidType) {
5348 // Taking the address of a void variable is technically illegal, but we
5349 // allow it in cases which are otherwise valid.
5350 // Example: "extern void x; void* y = &x;".
5351 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5352 }
5353
Reid Spencer5f016e22007-07-11 17:01:13 +00005354 // If the operand has type "type", the result has type "pointer to type".
5355 return Context.getPointerType(op->getType());
5356}
5357
Chris Lattner22caddc2008-11-23 09:13:29 +00005358QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005359 if (Op->isTypeDependent())
5360 return Context.DependentTy;
5361
Chris Lattner22caddc2008-11-23 09:13:29 +00005362 UsualUnaryConversions(Op);
5363 QualType Ty = Op->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005364
Chris Lattner22caddc2008-11-23 09:13:29 +00005365 // Note that per both C89 and C99, this is always legal, even if ptype is an
5366 // incomplete type or void. It would be possible to warn about dereferencing
5367 // a void pointer, but it's completely well-defined, and such a warning is
5368 // unlikely to catch any mistakes.
Ted Kremenek6217b802009-07-29 21:53:49 +00005369 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff08f19672008-01-13 17:10:08 +00005370 return PT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005371
John McCall183700f2009-09-21 23:43:11 +00005372 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanian16b10372009-09-03 00:43:07 +00005373 return OPT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00005374
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005375 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00005376 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005377 return QualType();
5378}
5379
5380static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5381 tok::TokenKind Kind) {
5382 BinaryOperator::Opcode Opc;
5383 switch (Kind) {
5384 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00005385 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5386 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005387 case tok::star: Opc = BinaryOperator::Mul; break;
5388 case tok::slash: Opc = BinaryOperator::Div; break;
5389 case tok::percent: Opc = BinaryOperator::Rem; break;
5390 case tok::plus: Opc = BinaryOperator::Add; break;
5391 case tok::minus: Opc = BinaryOperator::Sub; break;
5392 case tok::lessless: Opc = BinaryOperator::Shl; break;
5393 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5394 case tok::lessequal: Opc = BinaryOperator::LE; break;
5395 case tok::less: Opc = BinaryOperator::LT; break;
5396 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5397 case tok::greater: Opc = BinaryOperator::GT; break;
5398 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5399 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5400 case tok::amp: Opc = BinaryOperator::And; break;
5401 case tok::caret: Opc = BinaryOperator::Xor; break;
5402 case tok::pipe: Opc = BinaryOperator::Or; break;
5403 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5404 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5405 case tok::equal: Opc = BinaryOperator::Assign; break;
5406 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5407 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5408 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5409 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5410 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5411 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5412 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5413 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5414 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5415 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5416 case tok::comma: Opc = BinaryOperator::Comma; break;
5417 }
5418 return Opc;
5419}
5420
5421static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5422 tok::TokenKind Kind) {
5423 UnaryOperator::Opcode Opc;
5424 switch (Kind) {
5425 default: assert(0 && "Unknown unary op!");
5426 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5427 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5428 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5429 case tok::star: Opc = UnaryOperator::Deref; break;
5430 case tok::plus: Opc = UnaryOperator::Plus; break;
5431 case tok::minus: Opc = UnaryOperator::Minus; break;
5432 case tok::tilde: Opc = UnaryOperator::Not; break;
5433 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005434 case tok::kw___real: Opc = UnaryOperator::Real; break;
5435 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5436 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5437 }
5438 return Opc;
5439}
5440
Douglas Gregoreaebc752008-11-06 23:29:22 +00005441/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5442/// operator @p Opc at location @c TokLoc. This routine only supports
5443/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005444Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5445 unsigned Op,
5446 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005447 QualType ResultTy; // Result type of the binary operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00005448 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005449 // The following two variables are used for compound assignment operators
5450 QualType CompLHSTy; // Type of LHS after promotions for computation
5451 QualType CompResultTy; // Type of computation result
Douglas Gregoreaebc752008-11-06 23:29:22 +00005452
5453 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00005454 case BinaryOperator::Assign:
5455 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5456 break;
Sebastian Redl22460502009-02-07 00:15:38 +00005457 case BinaryOperator::PtrMemD:
5458 case BinaryOperator::PtrMemI:
5459 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5460 Opc == BinaryOperator::PtrMemI);
5461 break;
5462 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00005463 case BinaryOperator::Div:
5464 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5465 break;
5466 case BinaryOperator::Rem:
5467 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5468 break;
5469 case BinaryOperator::Add:
5470 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5471 break;
5472 case BinaryOperator::Sub:
5473 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5474 break;
Sebastian Redl22460502009-02-07 00:15:38 +00005475 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00005476 case BinaryOperator::Shr:
5477 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5478 break;
5479 case BinaryOperator::LE:
5480 case BinaryOperator::LT:
5481 case BinaryOperator::GE:
5482 case BinaryOperator::GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00005483 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005484 break;
5485 case BinaryOperator::EQ:
5486 case BinaryOperator::NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00005487 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005488 break;
5489 case BinaryOperator::And:
5490 case BinaryOperator::Xor:
5491 case BinaryOperator::Or:
5492 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5493 break;
5494 case BinaryOperator::LAnd:
5495 case BinaryOperator::LOr:
5496 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5497 break;
5498 case BinaryOperator::MulAssign:
5499 case BinaryOperator::DivAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005500 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5501 CompLHSTy = CompResultTy;
5502 if (!CompResultTy.isNull())
5503 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005504 break;
5505 case BinaryOperator::RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005506 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5507 CompLHSTy = CompResultTy;
5508 if (!CompResultTy.isNull())
5509 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005510 break;
5511 case BinaryOperator::AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005512 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5513 if (!CompResultTy.isNull())
5514 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005515 break;
5516 case BinaryOperator::SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005517 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5518 if (!CompResultTy.isNull())
5519 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005520 break;
5521 case BinaryOperator::ShlAssign:
5522 case BinaryOperator::ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005523 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5524 CompLHSTy = CompResultTy;
5525 if (!CompResultTy.isNull())
5526 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005527 break;
5528 case BinaryOperator::AndAssign:
5529 case BinaryOperator::XorAssign:
5530 case BinaryOperator::OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005531 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5532 CompLHSTy = CompResultTy;
5533 if (!CompResultTy.isNull())
5534 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005535 break;
5536 case BinaryOperator::Comma:
5537 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5538 break;
5539 }
5540 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005541 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00005542 if (CompResultTy.isNull())
Steve Naroff6ece14c2009-01-21 00:14:39 +00005543 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5544 else
5545 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedmanab3a8522009-03-28 01:22:36 +00005546 CompLHSTy, CompResultTy,
5547 OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00005548}
5549
Sebastian Redlaee3c932009-10-27 12:10:02 +00005550/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
5551/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00005552static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5553 const PartialDiagnostic &PD,
5554 SourceRange ParenRange)
5555{
5556 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5557 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
5558 // We can't display the parentheses, so just dig the
5559 // warning/error and return.
5560 Self.Diag(Loc, PD);
5561 return;
5562 }
5563
5564 Self.Diag(Loc, PD)
5565 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
5566 << CodeModificationHint::CreateInsertion(EndLoc, ")");
5567}
5568
Sebastian Redlaee3c932009-10-27 12:10:02 +00005569/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
5570/// operators are mixed in a way that suggests that the programmer forgot that
5571/// comparison operators have higher precedence. The most typical example of
5572/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005573static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
5574 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00005575 typedef BinaryOperator BinOp;
5576 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
5577 rhsopc = static_cast<BinOp::Opcode>(-1);
5578 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005579 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00005580 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005581 rhsopc = BO->getOpcode();
5582
5583 // Subs are not binary operators.
5584 if (lhsopc == -1 && rhsopc == -1)
5585 return;
5586
5587 // Bitwise operations are sometimes used as eager logical ops.
5588 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00005589 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
5590 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005591 return;
5592
Sebastian Redlaee3c932009-10-27 12:10:02 +00005593 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00005594 SuggestParentheses(Self, OpLoc,
5595 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00005596 << SourceRange(lhs->getLocStart(), OpLoc)
5597 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
5598 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
5599 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00005600 SuggestParentheses(Self, OpLoc,
5601 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00005602 << SourceRange(OpLoc, rhs->getLocEnd())
5603 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
5604 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005605}
5606
5607/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
5608/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
5609/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
5610static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
5611 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00005612 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005613 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
5614}
5615
Reid Spencer5f016e22007-07-11 17:01:13 +00005616// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005617Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5618 tok::TokenKind Kind,
5619 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005620 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssone9146f22009-05-01 19:49:17 +00005621 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Reid Spencer5f016e22007-07-11 17:01:13 +00005622
Steve Narofff69936d2007-09-16 03:34:24 +00005623 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5624 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005625
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00005626 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
5627 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
5628
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005629 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
5630}
5631
5632Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
5633 BinaryOperator::Opcode Opc,
5634 Expr *lhs, Expr *rhs) {
Douglas Gregor063daf62009-03-13 18:40:31 +00005635 if (getLangOptions().CPlusPlus &&
Mike Stump1eb44332009-09-09 15:08:12 +00005636 (lhs->getType()->isOverloadableType() ||
Douglas Gregor063daf62009-03-13 18:40:31 +00005637 rhs->getType()->isOverloadableType())) {
5638 // Find all of the overloaded operators visible from this
5639 // point. We perform both an operator-name lookup from the local
5640 // scope and an argument-dependent lookup based on the types of
5641 // the arguments.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005642 FunctionSet Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00005643 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5644 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005645 if (S)
5646 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5647 Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00005648 Expr *Args[2] = { lhs, rhs };
Mike Stump1eb44332009-09-09 15:08:12 +00005649 DeclarationName OpName
Douglas Gregor063daf62009-03-13 18:40:31 +00005650 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00005651 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005652 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005653
Douglas Gregor063daf62009-03-13 18:40:31 +00005654 // Build the (potentially-overloaded, potentially-dependent)
5655 // binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005656 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005657 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005658
Douglas Gregoreaebc752008-11-06 23:29:22 +00005659 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005660 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00005661}
5662
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005663Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005664 unsigned OpcIn,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005665 ExprArg InputArg) {
5666 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00005667
Mike Stump390b4cc2009-05-16 07:39:55 +00005668 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005669 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00005670 QualType resultType;
5671 switch (Opc) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005672 case UnaryOperator::OffsetOf:
5673 assert(false && "Invalid unary operator");
5674 break;
5675
Reid Spencer5f016e22007-07-11 17:01:13 +00005676 case UnaryOperator::PreInc:
5677 case UnaryOperator::PreDec:
Eli Friedmande99a452009-07-22 22:25:00 +00005678 case UnaryOperator::PostInc:
5679 case UnaryOperator::PostDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005680 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedmande99a452009-07-22 22:25:00 +00005681 Opc == UnaryOperator::PreInc ||
5682 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00005683 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005684 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00005685 resultType = CheckAddressOfOperand(Input, OpLoc);
5686 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005687 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00005688 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00005689 resultType = CheckIndirectionOperand(Input, OpLoc);
5690 break;
5691 case UnaryOperator::Plus:
5692 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005693 UsualUnaryConversions(Input);
5694 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00005695 if (resultType->isDependentType())
5696 break;
Douglas Gregor74253732008-11-19 15:42:04 +00005697 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5698 break;
5699 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5700 resultType->isEnumeralType())
5701 break;
5702 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5703 Opc == UnaryOperator::Plus &&
5704 resultType->isPointerType())
5705 break;
5706
Sebastian Redl0eb23302009-01-19 00:08:26 +00005707 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5708 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00005709 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005710 UsualUnaryConversions(Input);
5711 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00005712 if (resultType->isDependentType())
5713 break;
Chris Lattner02a65142008-07-25 23:52:49 +00005714 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5715 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5716 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005717 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00005718 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00005719 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00005720 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5721 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00005722 break;
5723 case UnaryOperator::LNot: // logical negation
5724 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005725 DefaultFunctionArrayConversion(Input);
5726 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00005727 if (resultType->isDependentType())
5728 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005729 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00005730 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5731 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00005732 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00005733 // In C++, it's bool. C++ 5.3.1p8
5734 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005735 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00005736 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00005737 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00005738 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00005739 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005740 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00005741 resultType = Input->getType();
5742 break;
5743 }
5744 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00005745 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005746
5747 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00005748 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00005749}
5750
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005751Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
5752 UnaryOperator::Opcode Opc,
5753 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005754 Expr *Input = (Expr*)input.get();
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00005755 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
5756 Opc != UnaryOperator::Extension) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005757 // Find all of the overloaded operators visible from this
5758 // point. We perform both an operator-name lookup from the local
5759 // scope and an argument-dependent lookup based on the types of
5760 // the arguments.
5761 FunctionSet Functions;
5762 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5763 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005764 if (S)
5765 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5766 Functions);
Mike Stump1eb44332009-09-09 15:08:12 +00005767 DeclarationName OpName
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005768 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00005769 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005770 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005771
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005772 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5773 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005774
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005775 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5776}
5777
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005778// Unary Operators. 'Tok' is the token for the operator.
5779Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5780 tok::TokenKind Op, ExprArg input) {
5781 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
5782}
5783
Steve Naroff1b273c42007-09-16 14:56:35 +00005784/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00005785Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5786 SourceLocation LabLoc,
5787 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005788 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +00005789 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00005790
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00005791 // If we haven't seen this label yet, create a forward reference. It
5792 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00005793 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00005794 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005795
Reid Spencer5f016e22007-07-11 17:01:13 +00005796 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00005797 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5798 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00005799}
5800
Sebastian Redlf53597f2009-03-15 17:47:39 +00005801Sema::OwningExprResult
5802Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5803 SourceLocation RPLoc) { // "({..})"
5804 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005805 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5806 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5807
Eli Friedmandca2b732009-01-24 23:09:00 +00005808 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattner4a049f02009-04-25 19:11:05 +00005809 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00005810 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00005811
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005812 // FIXME: there are a variety of strange constraints to enforce here, for
5813 // example, it is not possible to goto into a stmt expression apparently.
5814 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005815
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005816 // If there are sub stmts in the compound stmt, take the type of the last one
5817 // as the type of the stmtexpr.
5818 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005819
Chris Lattner611b2ec2008-07-26 19:51:01 +00005820 if (!Compound->body_empty()) {
5821 Stmt *LastStmt = Compound->body_back();
5822 // If LastStmt is a label, skip down through into the body.
5823 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5824 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005825
Chris Lattner611b2ec2008-07-26 19:51:01 +00005826 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005827 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00005828 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005829
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005830 // FIXME: Check that expression type is complete/non-abstract; statement
5831 // expressions are not lvalues.
5832
Sebastian Redlf53597f2009-03-15 17:47:39 +00005833 substmt.release();
5834 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005835}
Steve Naroffd34e9152007-08-01 22:05:33 +00005836
Sebastian Redlf53597f2009-03-15 17:47:39 +00005837Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5838 SourceLocation BuiltinLoc,
5839 SourceLocation TypeLoc,
5840 TypeTy *argty,
5841 OffsetOfComponent *CompPtr,
5842 unsigned NumComponents,
5843 SourceLocation RPLoc) {
5844 // FIXME: This function leaks all expressions in the offset components on
5845 // error.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00005846 // FIXME: Preserve type source info.
5847 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005848 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005849
Sebastian Redl28507842009-02-26 14:39:58 +00005850 bool Dependent = ArgTy->isDependentType();
5851
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005852 // We must have at least one component that refers to the type, and the first
5853 // one is known to be a field designator. Verify that the ArgTy represents
5854 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00005855 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00005856 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005857
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005858 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5859 // with an incomplete type would be illegal.
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00005860
Eli Friedman35183ac2009-02-27 06:44:11 +00005861 // Otherwise, create a null pointer as the base, and iteratively process
5862 // the offsetof designators.
5863 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5864 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005865 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman35183ac2009-02-27 06:44:11 +00005866 ArgTy, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00005867
Chris Lattner9e2b75c2007-08-31 21:49:13 +00005868 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5869 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00005870 // FIXME: This diagnostic isn't actually visible because the location is in
5871 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00005872 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00005873 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5874 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005875
Sebastian Redl28507842009-02-26 14:39:58 +00005876 if (!Dependent) {
Eli Friedmanc0d600c2009-05-03 21:22:18 +00005877 bool DidWarnAboutNonPOD = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005878
John McCalld00f2002009-11-04 03:03:43 +00005879 if (RequireCompleteType(TypeLoc, Res->getType(),
5880 diag::err_offsetof_incomplete_type))
5881 return ExprError();
5882
Sebastian Redl28507842009-02-26 14:39:58 +00005883 // FIXME: Dependent case loses a lot of information here. And probably
5884 // leaks like a sieve.
5885 for (unsigned i = 0; i != NumComponents; ++i) {
5886 const OffsetOfComponent &OC = CompPtr[i];
5887 if (OC.isBrackets) {
5888 // Offset of an array sub-field. TODO: Should we allow vector elements?
5889 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5890 if (!AT) {
5891 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005892 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5893 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00005894 }
5895
5896 // FIXME: C++: Verify that operator[] isn't overloaded.
5897
Eli Friedman35183ac2009-02-27 06:44:11 +00005898 // Promote the array so it looks more like a normal array subscript
5899 // expression.
5900 DefaultFunctionArrayConversion(Res);
5901
Sebastian Redl28507842009-02-26 14:39:58 +00005902 // C99 6.5.2.1p1
5903 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005904 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00005905 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00005906 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner338395d2009-04-25 22:50:55 +00005907 diag::err_typecheck_subscript_not_integer)
Sebastian Redlf53597f2009-03-15 17:47:39 +00005908 << Idx->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00005909
5910 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5911 OC.LocEnd);
5912 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005913 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005914
Ted Kremenek6217b802009-07-29 21:53:49 +00005915 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl28507842009-02-26 14:39:58 +00005916 if (!RC) {
5917 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005918 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5919 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00005920 }
Chris Lattner704fe352007-08-30 17:59:59 +00005921
Sebastian Redl28507842009-02-26 14:39:58 +00005922 // Get the decl corresponding to this.
5923 RecordDecl *RD = RC->getDecl();
Anders Carlsson6d7f1492009-05-01 23:20:30 +00005924 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson5992e4a2009-05-02 18:36:10 +00005925 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonf9b8bc62009-05-02 17:45:47 +00005926 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5927 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5928 << Res->getType());
Anders Carlsson5992e4a2009-05-02 18:36:10 +00005929 DidWarnAboutNonPOD = true;
5930 }
Anders Carlsson6d7f1492009-05-01 23:20:30 +00005931 }
Mike Stump1eb44332009-09-09 15:08:12 +00005932
John McCalla24dc2e2009-11-17 02:14:36 +00005933 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
5934 LookupQualifiedName(R, RD);
John McCallf36e02d2009-10-09 21:13:30 +00005935
Sebastian Redl28507842009-02-26 14:39:58 +00005936 FieldDecl *MemberDecl
John McCallf36e02d2009-10-09 21:13:30 +00005937 = dyn_cast_or_null<FieldDecl>(R.getAsSingleDecl(Context));
Sebastian Redlf53597f2009-03-15 17:47:39 +00005938 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00005939 if (!MemberDecl)
Douglas Gregor3f093272009-10-13 21:16:44 +00005940 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
5941 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stumpeed9cac2009-02-19 03:04:26 +00005942
Sebastian Redl28507842009-02-26 14:39:58 +00005943 // FIXME: C++: Verify that MemberDecl isn't a static field.
5944 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedmane9356962009-04-26 20:50:44 +00005945 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00005946 Res = BuildAnonymousStructUnionMemberReference(
John McCall09b6d0e2009-11-11 03:23:23 +00005947 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedmane9356962009-04-26 20:50:44 +00005948 } else {
5949 // MemberDecl->getType() doesn't get the right qualifiers, but it
5950 // doesn't matter here.
5951 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5952 MemberDecl->getType().getNonReferenceType());
5953 }
Sebastian Redl28507842009-02-26 14:39:58 +00005954 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005955 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005956
Sebastian Redlf53597f2009-03-15 17:47:39 +00005957 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5958 Context.getSizeType(), BuiltinLoc));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005959}
5960
5961
Sebastian Redlf53597f2009-03-15 17:47:39 +00005962Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5963 TypeTy *arg1,TypeTy *arg2,
5964 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00005965 // FIXME: Preserve type source info.
5966 QualType argT1 = GetTypeFromParser(arg1);
5967 QualType argT2 = GetTypeFromParser(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005968
Steve Naroffd34e9152007-08-01 22:05:33 +00005969 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005970
Douglas Gregorc12a9c52009-05-19 22:28:02 +00005971 if (getLangOptions().CPlusPlus) {
5972 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5973 << SourceRange(BuiltinLoc, RPLoc);
5974 return ExprError();
5975 }
5976
Sebastian Redlf53597f2009-03-15 17:47:39 +00005977 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5978 argT1, argT2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00005979}
5980
Sebastian Redlf53597f2009-03-15 17:47:39 +00005981Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5982 ExprArg cond,
5983 ExprArg expr1, ExprArg expr2,
5984 SourceLocation RPLoc) {
5985 Expr *CondExpr = static_cast<Expr*>(cond.get());
5986 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5987 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005988
Steve Naroffd04fdd52007-08-03 21:21:27 +00005989 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5990
Sebastian Redl28507842009-02-26 14:39:58 +00005991 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00005992 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00005993 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00005994 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00005995 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00005996 } else {
5997 // The conditional expression is required to be a constant expression.
5998 llvm::APSInt condEval(32);
5999 SourceLocation ExpLoc;
6000 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00006001 return ExprError(Diag(ExpLoc,
6002 diag::err_typecheck_choose_expr_requires_constant)
6003 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00006004
Sebastian Redl28507842009-02-26 14:39:58 +00006005 // If the condition is > zero, then the AST type is the same as the LSHExpr.
6006 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregorce940492009-09-25 04:25:58 +00006007 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
6008 : RHSExpr->isValueDependent();
Sebastian Redl28507842009-02-26 14:39:58 +00006009 }
6010
Sebastian Redlf53597f2009-03-15 17:47:39 +00006011 cond.release(); expr1.release(); expr2.release();
6012 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregorce940492009-09-25 04:25:58 +00006013 resType, RPLoc,
6014 resType->isDependentType(),
6015 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00006016}
6017
Steve Naroff4eb206b2008-09-03 18:15:37 +00006018//===----------------------------------------------------------------------===//
6019// Clang Extensions.
6020//===----------------------------------------------------------------------===//
6021
6022/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00006023void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006024 // Analyze block parameters.
6025 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006026
Steve Naroff4eb206b2008-09-03 18:15:37 +00006027 // Add BSI to CurBlock.
6028 BSI->PrevBlockInfo = CurBlock;
6029 CurBlock = BSI;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006030
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006031 BSI->ReturnType = QualType();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006032 BSI->TheScope = BlockScope;
Mike Stumpb83d2872009-02-19 22:01:56 +00006033 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbar1d2154c2009-07-29 01:59:17 +00006034 BSI->hasPrototype = false;
Chris Lattner17a78302009-04-19 05:28:12 +00006035 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
6036 CurFunctionNeedsScopeChecking = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006037
Steve Naroff090276f2008-10-10 01:28:17 +00006038 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00006039 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00006040}
6041
Mike Stump98eb8a72009-02-04 22:31:32 +00006042void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00006043 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump98eb8a72009-02-04 22:31:32 +00006044
6045 if (ParamInfo.getNumTypeObjects() == 0
6046 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006047 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump98eb8a72009-02-04 22:31:32 +00006048 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6049
Mike Stump4eeab842009-04-28 01:10:27 +00006050 if (T->isArrayType()) {
6051 Diag(ParamInfo.getSourceRange().getBegin(),
6052 diag::err_block_returns_array);
6053 return;
6054 }
6055
Mike Stump98eb8a72009-02-04 22:31:32 +00006056 // The parameter list is optional, if there was none, assume ().
6057 if (!T->isFunctionType())
6058 T = Context.getFunctionType(T, NULL, 0, 0, 0);
6059
6060 CurBlock->hasPrototype = true;
6061 CurBlock->isVariadic = false;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006062 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006063 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006064 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006065 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006066 // FIXME: remove the attribute.
6067 }
John McCall183700f2009-09-21 23:43:11 +00006068 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006069
Chris Lattner9097af12009-04-11 19:27:54 +00006070 // Do not allow returning a objc interface by-value.
6071 if (RetTy->isObjCInterfaceType()) {
6072 Diag(ParamInfo.getSourceRange().getBegin(),
6073 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6074 return;
6075 }
Mike Stump98eb8a72009-02-04 22:31:32 +00006076 return;
6077 }
6078
Steve Naroff4eb206b2008-09-03 18:15:37 +00006079 // Analyze arguments to block.
6080 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6081 "Not a function declarator!");
6082 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006083
Steve Naroff090276f2008-10-10 01:28:17 +00006084 CurBlock->hasPrototype = FTI.hasPrototype;
6085 CurBlock->isVariadic = true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006086
Steve Naroff4eb206b2008-09-03 18:15:37 +00006087 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6088 // no arguments, not a function that takes a single void argument.
6089 if (FTI.hasPrototype &&
6090 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb28317a2009-03-28 19:18:32 +00006091 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6092 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006093 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00006094 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006095 } else if (FTI.hasPrototype) {
6096 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattnerb28317a2009-03-28 19:18:32 +00006097 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff090276f2008-10-10 01:28:17 +00006098 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006099 }
Jay Foadbeaaccd2009-05-21 09:52:38 +00006100 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner9097af12009-04-11 19:27:54 +00006101 CurBlock->Params.size());
Fariborz Jahaniand66f22d2009-05-19 17:08:59 +00006102 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006103 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff090276f2008-10-10 01:28:17 +00006104 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
6105 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
6106 // If this has an identifier, add it to the scope stack.
6107 if ((*AI)->getIdentifier())
6108 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner9097af12009-04-11 19:27:54 +00006109
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006110 // Check for a valid sentinel attribute on this block.
Mike Stump1eb44332009-09-09 15:08:12 +00006111 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006112 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006113 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006114 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006115 // FIXME: remove the attribute.
6116 }
Mike Stump1eb44332009-09-09 15:08:12 +00006117
Chris Lattner9097af12009-04-11 19:27:54 +00006118 // Analyze the return type.
6119 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall183700f2009-09-21 23:43:11 +00006120 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006121
Chris Lattner9097af12009-04-11 19:27:54 +00006122 // Do not allow returning a objc interface by-value.
6123 if (RetTy->isObjCInterfaceType()) {
6124 Diag(ParamInfo.getSourceRange().getBegin(),
6125 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6126 } else if (!RetTy->isDependentType())
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006127 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006128}
6129
6130/// ActOnBlockError - If there is an error parsing a block, this callback
6131/// is invoked to pop the information about the block from the action impl.
6132void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6133 // Ensure that CurBlock is deleted.
6134 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006135
Chris Lattner17a78302009-04-19 05:28:12 +00006136 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6137
Steve Naroff4eb206b2008-09-03 18:15:37 +00006138 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00006139 PopDeclContext();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006140 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006141 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff4eb206b2008-09-03 18:15:37 +00006142}
6143
6144/// ActOnBlockStmtExpr - This is called when the body of a block statement
6145/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00006146Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6147 StmtArg body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00006148 // If blocks are disabled, emit an error.
6149 if (!LangOpts.Blocks)
6150 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00006151
Steve Naroff4eb206b2008-09-03 18:15:37 +00006152 // Ensure that CurBlock is deleted.
6153 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006154
Steve Naroff090276f2008-10-10 01:28:17 +00006155 PopDeclContext();
6156
Steve Naroff4eb206b2008-09-03 18:15:37 +00006157 // Pop off CurBlock, handle nested blocks.
6158 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006159
Steve Naroff4eb206b2008-09-03 18:15:37 +00006160 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006161 if (!BSI->ReturnType.isNull())
6162 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006163
Steve Naroff4eb206b2008-09-03 18:15:37 +00006164 llvm::SmallVector<QualType, 8> ArgTypes;
6165 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6166 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006167
Mike Stump56925862009-07-28 22:04:01 +00006168 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006169 QualType BlockTy;
6170 if (!BSI->hasPrototype)
Mike Stump56925862009-07-28 22:04:01 +00006171 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6172 NoReturn);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006173 else
Jay Foadbeaaccd2009-05-21 09:52:38 +00006174 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump56925862009-07-28 22:04:01 +00006175 BSI->isVariadic, 0, false, false, 0, 0,
6176 NoReturn);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006177
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006178 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregore0762c92009-06-19 23:52:42 +00006179 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00006180 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006181
Chris Lattner17a78302009-04-19 05:28:12 +00006182 // If needed, diagnose invalid gotos and switches in the block.
6183 if (CurFunctionNeedsScopeChecking)
6184 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6185 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump1eb44332009-09-09 15:08:12 +00006186
Anders Carlssone9146f22009-05-01 19:49:17 +00006187 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump56925862009-07-28 22:04:01 +00006188 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redlf53597f2009-03-15 17:47:39 +00006189 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6190 BSI->hasBlockDeclRefExprs));
Steve Naroff4eb206b2008-09-03 18:15:37 +00006191}
6192
Sebastian Redlf53597f2009-03-15 17:47:39 +00006193Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6194 ExprArg expr, TypeTy *type,
6195 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006196 QualType T = GetTypeFromParser(type);
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006197 Expr *E = static_cast<Expr*>(expr.get());
6198 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00006199
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006200 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006201
6202 // Get the va_list type
6203 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00006204 if (VaListType->isArrayType()) {
6205 // Deal with implicit array decay; for example, on x86-64,
6206 // va_list is an array, but it's supposed to decay to
6207 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006208 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00006209 // Make sure the input expression also decays appropriately.
6210 UsualUnaryConversions(E);
6211 } else {
6212 // Otherwise, the va_list argument must be an l-value because
6213 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00006214 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00006215 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00006216 return ExprError();
6217 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006218
Douglas Gregordd027302009-05-19 23:10:31 +00006219 if (!E->isTypeDependent() &&
6220 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00006221 return ExprError(Diag(E->getLocStart(),
6222 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006223 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00006224 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006225
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006226 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006227 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006228
Sebastian Redlf53597f2009-03-15 17:47:39 +00006229 expr.release();
6230 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6231 RPLoc));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006232}
6233
Sebastian Redlf53597f2009-03-15 17:47:39 +00006234Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006235 // The type of __null will be int or long, depending on the size of
6236 // pointers on the target.
6237 QualType Ty;
6238 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6239 Ty = Context.IntTy;
6240 else
6241 Ty = Context.LongTy;
6242
Sebastian Redlf53597f2009-03-15 17:47:39 +00006243 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006244}
6245
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006246static void
6247MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6248 QualType DstType,
6249 Expr *SrcExpr,
6250 CodeModificationHint &Hint) {
6251 if (!SemaRef.getLangOptions().ObjC1)
6252 return;
6253
6254 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6255 if (!PT)
6256 return;
6257
6258 // Check if the destination is of type 'id'.
6259 if (!PT->isObjCIdType()) {
6260 // Check if the destination is the 'NSString' interface.
6261 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6262 if (!ID || !ID->getIdentifier()->isStr("NSString"))
6263 return;
6264 }
6265
6266 // Strip off any parens and casts.
6267 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
6268 if (!SL || SL->isWide())
6269 return;
6270
6271 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
6272}
6273
Chris Lattner5cf216b2008-01-04 18:04:52 +00006274bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6275 SourceLocation Loc,
6276 QualType DstType, QualType SrcType,
6277 Expr *SrcExpr, const char *Flavor) {
6278 // Decode the result (notice that AST's are still created for extensions).
6279 bool isInvalid = false;
6280 unsigned DiagKind;
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006281 CodeModificationHint Hint;
6282
Chris Lattner5cf216b2008-01-04 18:04:52 +00006283 switch (ConvTy) {
6284 default: assert(0 && "Unknown conversion type");
6285 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006286 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00006287 DiagKind = diag::ext_typecheck_convert_pointer_int;
6288 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006289 case IntToPointer:
6290 DiagKind = diag::ext_typecheck_convert_int_pointer;
6291 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006292 case IncompatiblePointer:
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006293 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00006294 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6295 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006296 case IncompatiblePointerSign:
6297 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6298 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006299 case FunctionVoidPointer:
6300 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6301 break;
6302 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00006303 // If the qualifiers lost were because we were applying the
6304 // (deprecated) C++ conversion from a string literal to a char*
6305 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
6306 // Ideally, this check would be performed in
6307 // CheckPointerTypesForAssignment. However, that would require a
6308 // bit of refactoring (so that the second argument is an
6309 // expression, rather than a type), which should be done as part
6310 // of a larger effort to fix CheckPointerTypesForAssignment for
6311 // C++ semantics.
6312 if (getLangOptions().CPlusPlus &&
6313 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6314 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006315 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6316 break;
Sean Huntc9132b62009-11-08 07:46:34 +00006317 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00006318 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006319 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006320 case IntToBlockPointer:
6321 DiagKind = diag::err_int_to_block_pointer;
6322 break;
6323 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00006324 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006325 break;
Steve Naroff39579072008-10-14 22:18:38 +00006326 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00006327 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00006328 // it can give a more specific diagnostic.
6329 DiagKind = diag::warn_incompatible_qualified_id;
6330 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006331 case IncompatibleVectors:
6332 DiagKind = diag::warn_incompatible_vectors;
6333 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006334 case Incompatible:
6335 DiagKind = diag::err_typecheck_convert_incompatible;
6336 isInvalid = true;
6337 break;
6338 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006339
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006340 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006341 << SrcExpr->getSourceRange() << Hint;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006342 return isInvalid;
6343}
Anders Carlssone21555e2008-11-30 19:50:32 +00006344
Chris Lattner3bf68932009-04-25 21:59:05 +00006345bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006346 llvm::APSInt ICEResult;
6347 if (E->isIntegerConstantExpr(ICEResult, Context)) {
6348 if (Result)
6349 *Result = ICEResult;
6350 return false;
6351 }
6352
Anders Carlssone21555e2008-11-30 19:50:32 +00006353 Expr::EvalResult EvalResult;
6354
Mike Stumpeed9cac2009-02-19 03:04:26 +00006355 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00006356 EvalResult.HasSideEffects) {
6357 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6358
6359 if (EvalResult.Diag) {
6360 // We only show the note if it's not the usual "invalid subexpression"
6361 // or if it's actually in a subexpression.
6362 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
6363 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6364 Diag(EvalResult.DiagLoc, EvalResult.Diag);
6365 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006366
Anders Carlssone21555e2008-11-30 19:50:32 +00006367 return true;
6368 }
6369
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006370 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6371 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00006372
Eli Friedman3b5ccca2009-04-25 22:26:58 +00006373 if (EvalResult.Diag &&
6374 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6375 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006376
Anders Carlssone21555e2008-11-30 19:50:32 +00006377 if (Result)
6378 *Result = EvalResult.Val.getInt();
6379 return false;
6380}
Douglas Gregore0762c92009-06-19 23:52:42 +00006381
Douglas Gregor2afce722009-11-26 00:44:06 +00006382void
Mike Stump1eb44332009-09-09 15:08:12 +00006383Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00006384 ExprEvalContexts.push_back(
6385 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00006386}
6387
Mike Stump1eb44332009-09-09 15:08:12 +00006388void
Douglas Gregor2afce722009-11-26 00:44:06 +00006389Sema::PopExpressionEvaluationContext() {
6390 // Pop the current expression evaluation context off the stack.
6391 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
6392 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00006393
Douglas Gregor2afce722009-11-26 00:44:06 +00006394 if (Rec.Context == PotentiallyPotentiallyEvaluated &&
6395 Rec.PotentiallyReferenced) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00006396 // Mark any remaining declarations in the current position of the stack
6397 // as "referenced". If they were not meant to be referenced, semantic
6398 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Douglas Gregor2afce722009-11-26 00:44:06 +00006399 for (PotentiallyReferencedDecls::iterator
6400 I = Rec.PotentiallyReferenced->begin(),
6401 IEnd = Rec.PotentiallyReferenced->end();
Douglas Gregorac7610d2009-06-22 20:57:11 +00006402 I != IEnd; ++I)
6403 MarkDeclarationReferenced(I->first, I->second);
Douglas Gregor2afce722009-11-26 00:44:06 +00006404 }
6405
6406 // When are coming out of an unevaluated context, clear out any
6407 // temporaries that we may have created as part of the evaluation of
6408 // the expression in that context: they aren't relevant because they
6409 // will never be constructed.
6410 if (Rec.Context == Unevaluated &&
6411 ExprTemporaries.size() > Rec.NumTemporaries)
6412 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
6413 ExprTemporaries.end());
6414
6415 // Destroy the popped expression evaluation record.
6416 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00006417}
Douglas Gregore0762c92009-06-19 23:52:42 +00006418
6419/// \brief Note that the given declaration was referenced in the source code.
6420///
6421/// This routine should be invoke whenever a given declaration is referenced
6422/// in the source code, and where that reference occurred. If this declaration
6423/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6424/// C99 6.9p3), then the declaration will be marked as used.
6425///
6426/// \param Loc the location where the declaration was referenced.
6427///
6428/// \param D the declaration that has been referenced by the source code.
6429void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6430 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00006431
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006432 if (D->isUsed())
6433 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006434
Douglas Gregorb5352cf2009-10-08 21:35:42 +00006435 // Mark a parameter or variable declaration "used", regardless of whether we're in a
6436 // template or not. The reason for this is that unevaluated expressions
6437 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
6438 // -Wunused-parameters)
6439 if (isa<ParmVarDecl>(D) ||
6440 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregore0762c92009-06-19 23:52:42 +00006441 D->setUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00006442
Douglas Gregore0762c92009-06-19 23:52:42 +00006443 // Do not mark anything as "used" within a dependent context; wait for
6444 // an instantiation.
6445 if (CurContext->isDependentContext())
6446 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006447
Douglas Gregor2afce722009-11-26 00:44:06 +00006448 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00006449 case Unevaluated:
6450 // We are in an expression that is not potentially evaluated; do nothing.
6451 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006452
Douglas Gregorac7610d2009-06-22 20:57:11 +00006453 case PotentiallyEvaluated:
6454 // We are in a potentially-evaluated expression, so this declaration is
6455 // "used"; handle this below.
6456 break;
Mike Stump1eb44332009-09-09 15:08:12 +00006457
Douglas Gregorac7610d2009-06-22 20:57:11 +00006458 case PotentiallyPotentiallyEvaluated:
6459 // We are in an expression that may be potentially evaluated; queue this
6460 // declaration reference until we know whether the expression is
6461 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00006462 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00006463 return;
6464 }
Mike Stump1eb44332009-09-09 15:08:12 +00006465
Douglas Gregore0762c92009-06-19 23:52:42 +00006466 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00006467 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006468 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006469 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
6470 if (!Constructor->isUsed())
6471 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00006472 } else if (Constructor->isImplicit() &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006473 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006474 if (!Constructor->isUsed())
6475 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
6476 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006477 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
6478 if (Destructor->isImplicit() && !Destructor->isUsed())
6479 DefineImplicitDestructor(Loc, Destructor);
Mike Stump1eb44332009-09-09 15:08:12 +00006480
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006481 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
6482 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
6483 MethodDecl->getOverloadedOperator() == OO_Equal) {
6484 if (!MethodDecl->isUsed())
6485 DefineImplicitOverloadedAssign(Loc, MethodDecl);
6486 }
6487 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00006488 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006489 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00006490 // class templates.
Douglas Gregor3b846b62009-10-27 20:53:28 +00006491 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006492 bool AlreadyInstantiated = false;
6493 if (FunctionTemplateSpecializationInfo *SpecInfo
6494 = Function->getTemplateSpecializationInfo()) {
6495 if (SpecInfo->getPointOfInstantiation().isInvalid())
6496 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00006497 else if (SpecInfo->getTemplateSpecializationKind()
6498 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006499 AlreadyInstantiated = true;
6500 } else if (MemberSpecializationInfo *MSInfo
6501 = Function->getMemberSpecializationInfo()) {
6502 if (MSInfo->getPointOfInstantiation().isInvalid())
6503 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00006504 else if (MSInfo->getTemplateSpecializationKind()
6505 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006506 AlreadyInstantiated = true;
6507 }
6508
6509 if (!AlreadyInstantiated)
6510 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
6511 }
6512
Douglas Gregore0762c92009-06-19 23:52:42 +00006513 // FIXME: keep track of references to static functions
Douglas Gregore0762c92009-06-19 23:52:42 +00006514 Function->setUsed(true);
6515 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006516 }
Mike Stump1eb44332009-09-09 15:08:12 +00006517
Douglas Gregore0762c92009-06-19 23:52:42 +00006518 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00006519 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00006520 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006521 Var->getInstantiatedFromStaticDataMember()) {
6522 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
6523 assert(MSInfo && "Missing member specialization information?");
6524 if (MSInfo->getPointOfInstantiation().isInvalid() &&
6525 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
6526 MSInfo->setPointOfInstantiation(Loc);
6527 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6528 }
6529 }
Mike Stump1eb44332009-09-09 15:08:12 +00006530
Douglas Gregore0762c92009-06-19 23:52:42 +00006531 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00006532
Douglas Gregore0762c92009-06-19 23:52:42 +00006533 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00006534 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00006535 }
Douglas Gregore0762c92009-06-19 23:52:42 +00006536}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00006537
6538bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
6539 CallExpr *CE, FunctionDecl *FD) {
6540 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
6541 return false;
6542
6543 PartialDiagnostic Note =
6544 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
6545 << FD->getDeclName() : PDiag();
6546 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
6547
6548 if (RequireCompleteType(Loc, ReturnType,
6549 FD ?
6550 PDiag(diag::err_call_function_incomplete_return)
6551 << CE->getSourceRange() << FD->getDeclName() :
6552 PDiag(diag::err_call_incomplete_return)
6553 << CE->getSourceRange(),
6554 std::make_pair(NoteLoc, Note)))
6555 return true;
6556
6557 return false;
6558}
6559
John McCall5a881bb2009-10-12 21:59:07 +00006560// Diagnose the common s/=/==/ typo. Note that adding parentheses
6561// will prevent this condition from triggering, which is what we want.
6562void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
6563 SourceLocation Loc;
6564
John McCalla52ef082009-11-11 02:41:58 +00006565 unsigned diagnostic = diag::warn_condition_is_assignment;
6566
John McCall5a881bb2009-10-12 21:59:07 +00006567 if (isa<BinaryOperator>(E)) {
6568 BinaryOperator *Op = cast<BinaryOperator>(E);
6569 if (Op->getOpcode() != BinaryOperator::Assign)
6570 return;
6571
John McCallc8d8ac52009-11-12 00:06:05 +00006572 // Greylist some idioms by putting them into a warning subcategory.
6573 if (ObjCMessageExpr *ME
6574 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
6575 Selector Sel = ME->getSelector();
6576
John McCallc8d8ac52009-11-12 00:06:05 +00006577 // self = [<foo> init...]
6578 if (isSelfExpr(Op->getLHS())
6579 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
6580 diagnostic = diag::warn_condition_is_idiomatic_assignment;
6581
6582 // <foo> = [<bar> nextObject]
6583 else if (Sel.isUnarySelector() &&
6584 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
6585 diagnostic = diag::warn_condition_is_idiomatic_assignment;
6586 }
John McCalla52ef082009-11-11 02:41:58 +00006587
John McCall5a881bb2009-10-12 21:59:07 +00006588 Loc = Op->getOperatorLoc();
6589 } else if (isa<CXXOperatorCallExpr>(E)) {
6590 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
6591 if (Op->getOperator() != OO_Equal)
6592 return;
6593
6594 Loc = Op->getOperatorLoc();
6595 } else {
6596 // Not an assignment.
6597 return;
6598 }
6599
John McCall5a881bb2009-10-12 21:59:07 +00006600 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00006601 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCall5a881bb2009-10-12 21:59:07 +00006602
John McCalla52ef082009-11-11 02:41:58 +00006603 Diag(Loc, diagnostic)
John McCall5a881bb2009-10-12 21:59:07 +00006604 << E->getSourceRange()
6605 << CodeModificationHint::CreateInsertion(Open, "(")
6606 << CodeModificationHint::CreateInsertion(Close, ")");
6607}
6608
6609bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
6610 DiagnoseAssignmentAsCondition(E);
6611
6612 if (!E->isTypeDependent()) {
6613 DefaultFunctionArrayConversion(E);
6614
6615 QualType T = E->getType();
6616
6617 if (getLangOptions().CPlusPlus) {
6618 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
6619 return true;
6620 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
6621 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
6622 << T << E->getSourceRange();
6623 return true;
6624 }
6625 }
6626
6627 return false;
6628}